I am looking for a way to close a window by class name. Since the Process class does not have something like GetProcessByClassName, I searched for a way to do this using the Win32 API. I have written the following code:
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..");
}
}
}
However, when I do CloseHandle(), it gives the following error:
SEHEExeption was unhandle:External component has thrown an exception.
I have no idea of how to fix this.