【发布时间】:2011-02-13 20:21:03
【问题描述】:
我有一个 Windows 窗体,它在后台启动一些控制台应用程序 (CreateNoWindow = rue,WindowStyle = ProcessWindowStyle.Hidden)。
Windows 窗体让我有机会随时停止控制台应用程序。但我想以某种方式处理控制台应用程序中的关闭消息。我尝试使用如下钩子:
[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);
// 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
}
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
StaticLogger.Instance.DebugFormat("Main: ConsoleCtrlCheck: Got event {0}.", ctrlType);
if (ctrlType == CtrlTypes.CTRL_CLOSE_EVENT)
{
// Handle close stuff
}
return true;
}
static int Main(string[] args)
{
// Subscribing
HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck);
SetConsoleCtrlHandler(hr, true);
// Doing stuff
}
但只有在创建控制台窗口时,我才会在 ConsoleCtrlCheck 中收到消息。但如果窗口被隐藏 - 我没有收到任何消息。
在我的 Windows 窗体中关闭我使用的控制台应用程序进程 proc.CloseMainWindow(); 将消息发送到控制台窗口。
附: AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; - 也无济于事
您现在有其他方法来处理这种情况吗? 谢谢。
【问题讨论】: