Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WM_Close in C#?

Tags:

c#

pinvoke

Can anyone provide me an example of how to use WM_CLOSE to close a small application like Notepad?

like image 863
Anuya Avatar asked Jul 15 '09 03:07

Anuya


2 Answers

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).

like image 160
Kevin Montrose Avatar answered Oct 17 '22 09:10

Kevin Montrose


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.
like image 38
TheVillageIdiot Avatar answered Oct 17 '22 08:10

TheVillageIdiot