简体   繁体   中英

How to use WM_Close in C#?

任何人都可以提供一个如何使用WM_CLOSE关闭像记事本这样的小应用程序的例子吗?

Provided you already have a handle to send to.

...Some Class...
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

//I'd double check this constant, just in case
static uint WM_CLOSE = 0x10;

public void CloseWindow(IntPtr hWindow)
{
  SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
...Continue Class...

Getting a handle can be tricky. Control descendant classes (WinForms, basically) have Handle's, and you can enumerate all top-level windows with EnumWindows (which requires more advanced p/invoke, though only slightly).

Suppose you want to close notepad. the following code will do it:

    private void CloseNotepad(){
        string proc = "NOTEPAD";

        Process[] processes = Process.GetProcesses();
        var pc = from p in processes
                 where p.ProcessName.ToUpper().Contains(proc)
                 select p;
        foreach (var item in pc)
        {
            item.CloseMainWindow();
        }
    }

Considerations:

If the notepad has some unsaved text it will popup "Do you want to save....?" dialog or if the process has no UI it throws following exception

 'item.CloseMainWindow()' threw an exception of type 
 'System.InvalidOperationException' base {System.SystemException}: 
    {"No process is associated with this object."}

If you want to force close process immediately please replace

item.CloseMainWindow()

with

item.Kill();

If you want to go PInvoke way you can use handle from selected item.

item.Handle; //this will return IntPtr object containing handle of process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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