Catch Windows terminal closing on running process

ぐ巨炮叔叔 提交于 2019-11-29 12:24:24

The equivalent of SIGHUP is provided through the callback you register with SetConsoleCtrlHandler. Your callback function will be called on an arbitrary threadpool thread with dwCtrlType = CTRL_CLOSE_EVENT. You've got 5 seconds to clean-up, you cannot cancel the close.

Sample code is available in this MSDN article

This cannot be done directly from command prompt. You would need a secondary anything (vbs, powershell or custom MyApp.exe) to catch cmd.exe when it is closed and react accordingly.

For instance, a VBS WMI monitor.

strComputer = "."
Set objSWbemServices = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!" & "\\" & strComputer & "\root\cimv2")
Set objEventSource = objSWbemServices.ExecNotificationQuery( "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'cmd.exe'")
Set objEventObject = objEventSource.NextEvent()
Wscript.Echo "CMD.exe closed"

"SIGHUP"... tested on Windows 8.1 pro + Node.js 0.10.24 works fine..

process.on('SIGHUP', function(){
    //Your code goes here.
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!