[英]Using WM_Close in c#
我正在使用以下代码以编程方式退出进程。 因为我是这个概念的新手。 我想知道如何在下面的代码中使用此代码。
逻辑:我将终止进程名称,我将其分配给该函数。
如果要终止记事本,如何将参数[Process Name]传递给该函数?
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static uint WM_CLOSE = 0xF060;
public void CloseWindow(IntPtr hWindow)
{
SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
使用Process.CloseMainWindow
而不是手动发送消息。 这会将消息发送到流程的主窗口:
using System.Diagnostics;
// ...
foreach (var process in Process.GetProcessesByName("notepad.exe"))
process.CloseMainWindow();
或者,您可以使用MainWindowHandle
来获取Process
主窗口的句柄并向其发送消息:
foreach (var process in Process.GetProcessesByName("notepad.exe"))
CloseWindow(process.MainWindowHandle); // CloseWindow is defined by OP.
如果要立即终止进程而不是关闭主窗口,则这不是一个好方法。 您应该改用Process.Kill
方法。
虽然我同意Mehrdad的回答,但如果您真的想重新发明轮子,那么这就是这样做的方法(这没有任何错误检查,请您自己添加)。
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static uint WM_CLOSE = 0x10;
static bool CloseWindow(IntPtr hWnd)
{
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
return true;
}
static void Main()
{
IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");
bool ret = CloseWindow(hWnd);
}
顺便说一句, 这里是查看本机API的托管声明的好地方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.