如何在 C# 中使用 WM_Close?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1129204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use WM_Close in C#?
提问by Anuya
Can anyone provide me an example of how to use WM_CLOSE to close a small application like Notepad?
谁能给我一个如何使用 WM_CLOSE 关闭像记事本这样的小应用程序的例子?
采纳答案by Kevin Montrose
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).
获得句柄可能很棘手。控件后代类(基本上是 WinForms)具有 Handle,您可以使用EnumWindows枚举所有顶级窗口(这需要更高级的 p/invoke,尽管只是轻微的)。
回答by TheVillageIdiot
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.
如果您想使用 PInvoke 方式,您可以使用所选项目的句柄。
item.Handle; //this will return IntPtr object containing handle of process.