tags:

views:

400

answers:

2

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

+4  A: 

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

Kevin Montrose
A: 

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.
TheVillageIdiot
need to read the question, @karthik wants to close a.n.other application
Hamish Smith
@Hamish I think adding *other* would have helped like, *other small application like notepad*
TheVillageIdiot
where do i need to give the name of applciation to close it ?
Anuya
@karthik I've changed the whole answer to meet the **Requirement Specefication** :)
TheVillageIdiot
@TheVillageIdiot, where have u used the WM_close ?
Anuya
It is just killing the applicaiton directly, right ? Thats why i want to use WM_close. Thanks.
Anuya