没什么话说,方法如下,以供参考:
- [DllImport("user32", EntryPoint = "FindWindow")]
- public static extern IntPtr FindWindowA(string lpClassName, string lpWindowName);
- [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
- private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
- [DllImport("User32.dll", EntryPoint = "SendMessage")]
- private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
- private const int WM_CLOSE = 0x0010;
- private const int WM_GETTEXT = 0x000D;
- private const int WM_SETTEXT = 0x000C;
- private const int WM_CLICK = 0x00F5;
- private int _autoCloseTime = 3;
- public string MsgTitle =string.Empty;
- string lpszClass_Submit = "Button"; //需要查找的Button的类名
- string lpszName_Submit = "确定"; //需要查找的Button的标题
- private Timer timer1;
- public Form1()
- {
- InitializeComponent();
- MsgTitle = "还剩下" + _autoCloseTime.ToString() + "秒";
- timer1 = new System.Windows.Forms.Timer();
- timer1.Tick += new EventHandler(timer1_Tick);
- timer1.Interval = 1000;
- }
- private void KillMessageBox(Timer timer)
- {
- //查找MessageBox的弹出窗口,注意对应标题
- IntPtr hWnd = IntPtr.Zero;
- if(_autoCloseTime == 3)
- {
- hWnd = FindWindowA(null, MsgTitle);
- }
- else
- {
- hWnd = FindWindowA(null, "还剩下" + (_autoCloseTime + 1).ToString() + "秒");
- }
- if (hWnd != IntPtr.Zero)
- {
- string str = "还剩下" + _autoCloseTime.ToString() + "秒";
- SendMessage(hWnd, WM_SETTEXT, (IntPtr)0, str);
- _autoCloseTime --;
- if (_autoCloseTime < 0)
- {
- IntPtr EdithWnd = new IntPtr(0);
- EdithWnd = FindWindowEx(hWnd,EdithWnd, lpszClass_Submit, lpszName_Submit);
- if (!EdithWnd.Equals(IntPtr.Zero))
- {
- SendMessage(EdithWnd, WM_CLICK, (IntPtr)0, "0");
- }
- 查找到窗口则关闭
- //SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, "");
- //停止计时器
- timer.Stop();
- _autoCloseTime = 3;
- }
- }
- }
- private void StartKiller()
- {
- timer1.Enabled = true;
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- KillMessageBox(sender as Timer);
- }
- private void button1_Click(object sender, EventArgs e)
- {
- StartKiller();
- DialogResult result = MessageBox.Show("若不响应,程序将在3秒后自动关闭", MsgTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
- if (result == DialogResult.OK)
- {
- timer1.Stop();
- _autoCloseTime = 3;
- MessageBox.Show("关闭");
- }
- }