在我的 WPF 应用程序中,我使用控制台窗口作为调试/消息窗口 - 我有选项设置来根据用户的需要显示和隐藏窗口,所有这些都很好。唯一的问题是当用户关闭控制台窗口时,它会退出整个程序。如何覆盖它,以便当用户单击 X 时它只是隐藏控制台而不是退出应用程序?
这就是我到目前为止所拥有的:
const int SW_HIDE = 0;
const int SW_SHOW = 5;
public static bool ConsoleVisible { get; private set; }
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void HideConsole()
{
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
ConsoleVisible = false;
}
public static void ShowConsole()
{
var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);
ConsoleVisible = true;
}
** 对于想要使用此功能的人,您需要:using System.Runtime.InteropServices;
此代码源自此答案:https ://stackoverflow.com/a/3571628/649382
** 编辑 **
环顾四周,似乎这是不可能的。我在这里看到了一个答案:https ://stackoverflow.com/a/12015131/649382 谈到删除退出按钮也是可以接受的,但它看起来像代码在 C++ 中,我无法弄清楚它是 C#选择。
** 编辑 2 **
我能够弄清楚到 C# 的转换并将其写为下面的答案。