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
2009-07-15 03:21:33
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
2009-07-15 03:22:22
need to read the question, @karthik wants to close a.n.other application
Hamish Smith
2009-07-15 03:24:30
@Hamish I think adding *other* would have helped like, *other small application like notepad*
TheVillageIdiot
2009-07-15 03:31:48
where do i need to give the name of applciation to close it ?
Anuya
2009-07-15 03:56:29
@karthik I've changed the whole answer to meet the **Requirement Specefication** :)
TheVillageIdiot
2009-07-15 04:13:48
@TheVillageIdiot, where have u used the WM_close ?
Anuya
2009-07-15 07:31:51
It is just killing the applicaiton directly, right ? Thats why i want to use WM_close. Thanks.
Anuya
2009-07-15 07:32:47