c#中将WM_CLOSE消息发送到没有窗口的进程的方法
開始一個過程-
?
ProcessStartInfo psi = new ProcessStartInfo("G:\SampleWinApp.exe"); psi.UseShellExecute = false;psi.CreateNoWindow = true; Process prcs = Process.Start(psi); 復制代碼使用PostMessage發送WM_CLOSE
?
const int WM_CLOSE = 0x0010;public void SendCloseSignal(Process proc) {uint uiPid = (uint) proc.Id;bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);if (!bResult && Marshal.GetLastWin32Error() == 0) {object objWnd = processWnd[uiPid];if (objWnd != null) {IntPtr ptrWnd = (IntPtr) objWnd;PostMessage(ptrWnd, WM_CLOSE, 0, 0);return;}}foreach (ProcessThread thread in proc.Threads) {PostThreadMessage((uint) thread.Id, WM_CLOSE, UIntPtr.Zero, IntPtr.Zero);}}private static bool EnumWindowsProc(IntPtr hwnd, uint lParam) {uint uiPid = 0;if (GetParent(hwnd) == IntPtr.Zero){GetWindowThreadProcessId(hwnd, ref uiPid);if (uiPid == lParam){processWnd[uiPid] = hwnd;return false;}}return true; } 復制代碼使用CreateNoWindow = false啟動exe,發送WM_CLOSE消息,并正常關閉應用程序.
如果CreateNoWindow = true,則WM_CLOSE消息永遠不會到達進程.甚至PostThreadMessage似乎也不起作用.有什么方法可以發送WM_CLOSE消息?我有一天要尋找解決辦法,..不走運.
編輯:為每個應用程序都安裝了Windows服務.啟動/停止服務將啟動/停止應用程序.目前,我們在服務停止時終止了該應用程序.由于其殘酷的殺傷力,應用程序無法正常終止.一些應用程序監聽CTRL signals.現在,我只需要一些方法即可將WM_CLOSE消息發送到這些應用程序.
Edit2:如果存在窗口,則WM_CLOSE會觸發CTRL_CLOSE_EVENT.但是,當任何進程以CreateNoWindow = true啟動時,都不會觸發.
最佳答案
Is there any way to send WM_CLOSE message?
WM_CLOSE發送到窗口.如果在此過程中沒有窗口,則沒有任何可處理的消息.如果您希望關閉沒有窗口的進程,那么發送WM_CLOSE不是解決方案.
看來您只是想終止進程.當控制臺進程具有關聯的窗口時,您將使用WM_CLOSE消息來觸發CTRL_CLOSE_EVENT信號.
由于CTRL_CLOSE_EVENT已經是殺死進程的一種相當殘酷的方式,因此,我認為完全可以證明殺死它是合理的.您已經有一個Process對象.只需使用Process.Kill()將其殺死.
總結
以上是生活随笔為你收集整理的c#中将WM_CLOSE消息发送到没有窗口的进程的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: int 和 Integer 的区别
- 下一篇: C# 重写WndProc及发送消息