简体   繁体   English

在C#中使用WM_Close

[英]Using WM_Close in c#

I am using the below code to exit a process programatically. 我正在使用以下代码以编程方式退出进程。 since i am new to this concept. 因为我是这个概念的新手。 I want to know how to use this below code. 我想知道如何在下面的代码中使用此代码。

Logic : I will have the process name to be terminated, i shud assign that to this function. 逻辑:我将终止进程名称,我将其分配给该函数。

Say if want to terminate a notepad, how to pass parameter [Process Name] to this function ? 如果要终止记事本,如何将参数[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);
    }

Use the Process.CloseMainWindow instead of manually sending the message. 使用Process.CloseMainWindow而不是手动发送消息。 This will send the message to the main window of the process: 这会将消息发送到流程的主窗口:

using System.Diagnostics;
// ...

foreach (var process in Process.GetProcessesByName("notepad.exe"))
    process.CloseMainWindow();

Alternatively, you can use MainWindowHandle to get the handle of the main window of a Process and send a message to it: 或者,您可以使用MainWindowHandle来获取Process主窗口的句柄并向其发送消息:

foreach (var process in Process.GetProcessesByName("notepad.exe"))
    CloseWindow(process.MainWindowHandle); // CloseWindow is defined by OP.

If you want to kill the process immediately instead of closing the main window, this is not a good approach. 如果要立即终止进程而不是关闭主窗口,则这不是一个好方法。 You should use the Process.Kill method instead. 您应该改用Process.Kill方法。

Although I agree with Mehrdad's answer but if you really want to re-invent the wheel, then this is how to do it (This is without any error checking etc. Please add that yourself). 虽然我同意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);
}

BTW, Here is a good place to view Managed declarations of native API's 顺便说一句, 这里是查看本机API的托管声明的好地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM