【发布时间】:2013-11-24 10:56:23
【问题描述】:
我需要一个具有以下行为的 Windows 窗体应用程序:
- 当程序从资源管理器运行时,无需任何控制台即可工作(例如)。
- 当程序从命令行运行时重定向来自
Console.WriteLine()的所有文本(因此程序必须将所有输出重定向到父控制台)
为此适用以下代码:
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[STAThread]
static void Main()
{
AttachConsole(-1);
Console.WriteLine("Test1");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.WriteLine("WinForms exit");
}
但这里有一个问题:当打开表单并且用户关闭控制台时,我的程序会自动关闭。用户关闭控制台后,我需要让程序运行。我尝试使用SetConsoleCtrlHandler() 并在处理程序中调用FreeConsole(),但在调用处理程序后程序仍然关闭:
static class Program
{
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
Console.OutputEncoding = Console.OutputEncoding;
FreeConsole();
return true;
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool FreeConsole();
[STAThread]
static void Main()
{
AttachConsole(-1);
SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
Console.WriteLine("Test1");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.WriteLine("WinForms exit");
}
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
}
当用户关闭控制台时如何防止关闭 Windows 窗体应用程序?
【问题讨论】:
-
@SriramSakthivel 谢谢你的链接!但不幸的是,这里只是说明这是不可能的事实......
-
如果事实不可能那么答案也是一样的吧?也许您应该问另一个问题,说明您对要实现的目标的问题,您可能需要考虑是否真的需要一个控制台?
-
@SriramSakthivel 是的,你是对的。我只是对这个事实不满意 :) 我的程序真的只需要控制台窗口而不需要其他任何东西,所以我将不得不接受这个事实......感谢您参与我的问题。