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();
            }
        }
    }

  

转载于:https://www.cnblogs.com/XuPengLB/p/6473069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值