与我相关的先前的问题 https://stackoverflow.com/questions/54811209/is-it-possible-to-create-a-console-window-as-created-by-allocconsole-as-a-gui:
我想出了以下方法,在其中创建了这个 WinForms 控件:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ConsoleWindow : Control
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
private static ConsoleWindow _theWindow;
public ConsoleWindow()
{
if (!DesignMode)
{
if (_theWindow != null)
{
throw new Exception("An application can have only one ConsoleWindow");
}
_theWindow = this;
AllocConsole();
var newOut = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
Console.SetOut(newOut);
Console.SetError(newOut);
var consoleHwnd = GetConsoleWindow();
SizeChanged += (sender, args) =>
{
SetWindowPos(consoleHwnd, IntPtr.Zero, 0, 0, Width, Height, 0);
};
SetWindowLong(consoleHwnd, -16 /*GWL_STYLE*/, 0x50000000 /* WS_CHILD|WS_VISIBLE*/);
SetParent(consoleHwnd, Handle);
SetWindowPos(consoleHwnd, IntPtr.Zero, 0, 0, 0, 0, 0);
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _theWindow != null)
{
FreeConsole();
_theWindow = null;
}
base.Dispose(disposing);
}
}
...然后我可以通过 XAML 在我的 WPF 应用程序中使用它,如下所示:
<WindowsFormsHost>
<WindowsFormsHost.Child>
<controls:ConsoleWindow></controls:ConsoleWindow>
</WindowsFormsHost.Child>
</WindowsFormsHost>
It mostly有效,只是鼠标交互似乎受到了损害。当您创建控制台窗口(通常作为顶级窗口运行)时,您可以使用鼠标单击/拖动任意选择,但在将其设置为子控件(就像我所做的那样)后,这不再起作用。我可以右键单击以调用控制台窗口的上下文菜单来选择/复制所有文本,但无法进行单击/拖动选择。
有没有办法解决这个问题(可能缺少/不正确的样式或消息路由?)以便我可以按预期与控制台窗口交互,或者以这种方式设置控制台窗口的父级是否存在根本问题?