【发布时间】:2009-07-15 03:13:44
【问题描述】:
谁能给我一个例子,说明如何使用 WM_CLOSE 关闭像记事本这样的小应用程序?
【问题讨论】:
谁能给我一个例子,说明如何使用 WM_CLOSE 关闭像记事本这样的小应用程序?
【问题讨论】:
假设您要关闭记事本。下面的代码就可以了:
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();
}
}
注意事项:
如果记事本有一些未保存的文本,它会弹出“你想保存....?”对话框,或者如果进程没有 UI,则会引发以下异常
'item.CloseMainWindow()' threw an exception of type
'System.InvalidOperationException' base {System.SystemException}:
{"No process is associated with this object."}
如果您想立即强制关闭进程,请替换
item.CloseMainWindow()
与
item.Kill();
如果您想使用 PInvoke 方式,您可以使用所选项目的句柄。
item.Handle; //this will return IntPtr object containing handle of process.
【讨论】:
前提是你已经有一个句柄可以发送到。
...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...
获取句柄可能很棘手。控件后代类(基本上是 WinForms)具有 Handle,并且您可以使用 EnumWindows 枚举所有顶级窗口(这需要更高级的 p/invoke,尽管只是稍微有点)。
【讨论】: