///
///
窗口类名(例:Button)
///
窗口标题
///
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
///
/// 找到窗口
///
///
父窗口句柄(如果为空,则为桌面窗口)
///
子窗口句柄(从该子窗口之后查找)
///
窗口类名(例:Button
///
窗口标题
///
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private extern static IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
///
/// 发送消息
///
///
消息接受窗口句柄
///
消息
///
指定附加的消息特定信息
///
指定附加的消息特定信息
///
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);
//窗口发送给按钮控件的消息,让按钮执行点击操作,可以模拟按钮点击
private const int BM_CLICK = 0xF5;
通过窗体标题,循环查找该窗体,然后找到确定按钮,通过句柄发送点击消息,主动关闭弹窗
private void Form1_Load(object sender, EventArgs e)
Task task = new Task(() =>
while (true)
//测试警告框
IntPtr maindHwnd = FindWindow(null, "提示");//主窗口标题
if (maindHwnd != IntPtr.Zero)
IntPtr childHwnd = FindWindowEx(maindHwnd, IntPtr.Zero, null, "确定");//按钮控件标题
if (childHwnd != IntPtr.Zero)
SendMessage(childHwnd, BM_CLICK, 0, 0);
task.Start();