如何在C#中使用WM_Close?

时间:2009-07-15 03:13:45

标签: c# pinvoke

有人能为我提供一个如何使用WM_CLOSE关闭记事本等小应用程序的示例吗?

2 个答案:

答案 0 :(得分:11)

如果您已经有一个发送到的句柄。

...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,尽管只是略微)。

答案 1 :(得分:1)

假设您要关闭记事本。以下代码将执行此操作:

    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.
相关问题