在c#中使用WM_Close

时间:2009-07-27 05:44:15

标签: c#

我使用以下代码以编程方式退出进程。 因为我对这个概念不熟悉。我想知道如何使用下面的代码。

逻辑:我将终止进程名称,我将其分配给 这个功能。

假设是否要终止记事本,如何传递参数[进程名称] 这个功能?

    [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);
    }

2 个答案:

答案 0 :(得分:5)

使用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方法。

答案 1 :(得分:2)

虽然我同意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