Closing a minimized/iconized process from C#

前端 未结 4 692
北海茫月
北海茫月 2021-01-20 10:15

Here\'s my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the u

4条回答
  •  执念已碎
    2021-01-20 11:09

    This should work:

    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    private static extern IntPtr FindWindow(string className, string windowName);
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    
    private const int WM_CLOSE = 0x10;
    private const int WM_QUIT = 0x12;
    
    public void SearchAndDestroy(string windowName) 
    {
        IntPtr hWnd = FindWindow(null, windowName);
        if (hWnd == IntPtr.Zero)
            throw new Exception("Couldn't find window!");
        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    }
    

    Since some windows don't respond to WM_CLOSE, WM_QUIT might have to be sent instead. These declarations should work on both 32bit and 64bit.

提交回复
热议问题