CloseHandle()给出一个异常:外部组件抛出了一个异常

本文关键字:一个 异常 组件 CloseHandle 外部 | 更新日期: 2023-09-27 18:19:06

我正在寻找一种方法来关闭类名称窗口。因为Process类没有像GetProcessByClassName这样的东西,所以我寻找了一种使用Win32 API来做到这一点的方法。我写了下面的代码:

public partial class Form1 : Form
{
    [DllImport("user32", CharSet = CharSet.Unicode)]
    public static extern
    IntPtr FindWindow(string lpClassName,string lpWindowName);
    [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]
    public static extern
    bool CloseHandle(IntPtr handle);
    private void button1_Click(object sender, EventArgs e)
    {
        IntPtr handle = FindWindow("Notepad", null);
        if (handle != IntPtr.Zero)
        {
           bool hresult = CloseHandle(handle);
        }
        else
        {
            MessageBox.Show("app is not running..");
        }
    }
}

然而,当我执行CloseHandle()时,它会给出以下错误:

seheexception was unhandle:外部组件抛出异常。

我不知道如何解决这个问题

CloseHandle()给出一个异常:外部组件抛出了一个异常

我不认为您需要关闭从FindWindow打开的句柄。

然而,根据您的需要,您可能最好使用。net框架等效的GetProcessesByName:

var processes = System.Diagnostics.Process.GetProcessesByName("notepad");
foreach (System.Diagnostics.Process process in processes)
{
    // The main window handle can now be accessed 
    // through process.MainWindowHandle;
}

我终于找到了解决办法。非常感谢@competent_tech和@Alexm,@Deanna,@Hans passant,你们的评论帮了我很多忙!

using System.Runtime.InteropServices;
    // ... 
       public class MyWindowHandling {
       private const int WM_CLOSE = 0x0010;
       [DllImport("user32", CharSet = CharSet.Unicode)]
        private static extern
        IntPtr FindWindow(
                string lpClassName,
                string lpWindowName
        );
       [DllImport("user32")]
        private static extern
        IntPtr SendMessage(
                IntPtr handle,
                int Msg,
                IntPtr wParam,
                IntPtr lParam
         );
         public void CloseWindowByClassName(string className) {
             IntPtr handle = FindWindow(null, className);
              if (handle != IntPtr.Zero) {
                   SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
               }
        }
      }