C# 窗口模拟点击按钮或关闭窗口
public class CloseForm { [DllImport("user32", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(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 void SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam); private const int WM_CLOSE = 0x10;//关闭 private const int BM_CLICK = 0xF5;//点击 private DateTime dt = DateTime.Now;//当前时间 private string MsgTitle { get; set; } public void CloseTitleForm(string title) { this.MsgTitle = title; System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer(); timer1.Tick += new EventHandler(timer1_Tick); timer1.Interval = 1000; timer1.Enabled = true; //MessageBox.Show("若不回應的話,X秒後此 MsgBox 會自動關閉", MsgTitle); //timer1.Enabled = false; } private void timer1_Tick(object sender, EventArgs e) { IntPtr hWnd = FindWindow(null, MsgTitle); //窗体按钮 IntPtr childHwnd = FindWindowEx(hWnd, IntPtr.Zero, null, "是(&Y)"); if (childHwnd != IntPtr.Zero) { //模拟点击 是(&Y) SendMessage(childHwnd, BM_CLICK, IntPtr.Zero, 0); } else { //没有找到按钮则关闭 SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, 0); } if (DateTime.Now.Subtract(dt).TotalSeconds > 10) { //10秒后停止执行 ((System.Windows.Forms.Timer)sender).Stop(); } } }