【问题标题】:How to use WM_Close in C#?如何在 C# 中使用 WM_Close?
【发布时间】:2009-07-15 03:13:44
【问题描述】:

谁能给我一个例子,说明如何使用 WM_CLOSE 关闭像记事本这样的小应用程序?

【问题讨论】:

    标签: c# pinvoke


    【解决方案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.
    

    【讨论】:

    • 需要阅读问题,@karthik 想要关闭一个.n.other 应用程序
    • @Hamish 我认为添加 other 会有所帮助,其他小型应用程序,如记事本
    • 我需要在哪里提供应用程序的名称才能关闭它?
    • @karthik 我已经更改了整个答案以满足需求规范 :)
    • @TheVillageIdiot,你在哪里使用过 WM_close ?
    【解决方案2】:

    前提是你已经有一个句柄可以发送到。

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

    【讨论】:

    • 我尝试了这种方法,但是,当发送到 WPF 应用程序时,它会抛出 System.Reflection.targetParameterCountException。虽然它适用于记事本。
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多