简体   繁体   English

如何检测我的Windows应用程序是否已结束?

[英]How to detect if my Windows application has ended?

Basically what the title says I need to detect when my program is ending like when someones clicks on end task in the task manager or something. 基本上,标题说的是我需要检测程序何时结束(例如有人单击任务管理器中的结束任务或诸如此类)。 Can anyone point me to some kind of event that handles this with an example or something? 谁能指出我通过某种例子来处理此类事件的事件吗? Thanks for any help given 感谢您提供的任何帮助

You need to open this process. 您需要打开此过程。 This way you will retrieve its handle. 这样,您将检索其句柄。 After that you can simply wait on this handle. 之后,您可以简单地等待此句柄。

HANDLE h = OpenProcess(....);
WaitForSingleObject(h);

Handles of the processes and threads in many ways look like Windows event handles. 进程和线程的处理在许多方面都类似于Windows事件处理。 Once this process or thread finishes, they get signaled. 一旦该过程或线程完成,就会发出信号。

It depends on how your app is terminated and what type of app it is. 这取决于您的应用如何终止以及它是什么类型的应用。

For apps with an UI: 对于具有UI的应用程序:

  • If the user clicks "End Task" in the task manager, you will actually receive WM_DESTROY and even WM_CLOSE messages to your message handler. 如果用户单击任务管理器中的“结束任务”,您实际上将收到WM_DESTROY甚至WM_CLOSE消息到您的消息处理程序。
  • If the user simply clicks the X button of your app, obviously the above also applies. 如果用户仅单击应用程序的X按钮,则显然上述内容同样适用。
  • If the user logs off or shuts down the PC, you'll receive WM_QUERYENDSESSION and WM_ENDSESSION messages. 如果用户注销或关闭PC,您将收到WM_QUERYENDSESSION和WM_ENDSESSION消息。

For console apps, you can use the SetConsoleCtrlHandler function to be notified of most cases of app termination (I don't have any experience with this so can't give many details). 对于控制台应用程序,您可以使用SetConsoleCtrlHandler函数来通知大多数应用程序终止情况(我对此没有任何经验,因此无法提供很多详细信息)。

For services, you can use the RegisterServiceCtrlHandler function in much the same way. 对于服务,可以以几乎相同的方式使用RegisterServiceCtrlHandler函数。

For all types of apps, if the app is terminated forcibly by another process via the TerminateProcess function, there is no way to get notified : 对于所有类型的应用程序,如果该应用程序通过TerminateProcess函数被另一个进程强行终止, 则无法获得通知

If a process is terminated by TerminateProcess, all threads of the process are terminated immediately with no chance to run additional code. 如果某个进程被TerminateProcess终止,则该进程的所有线程将立即终止,而没有机会运行其他代码。 This means that the thread does not execute code in termination handler blocks. 这意味着线程不执行终止处理程序块中的代码。 In addition, no attached DLLs are notified that the process is detaching. 此外,没有附加的DLL通知该进程正在分离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM