我正在寻找一种通过类名关闭窗口的方法。由于 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() 时,会出现以下错误:
SEHEExeption was unhandle:External component has thrown an exception.
我不知道如何解决这个问题。
请您参考如下方法:
我认为您不需要关闭从 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;
}
