C#根據彈窗標題獲取窗體句柄並模擬點擊按鈕(FindWindow,FindWindowEx,SendMessage)


任務:將下面彈窗自動關閉

 

        /// <summary>
        /// 找到窗口
        /// </summary>
        /// <param name="lpClassName">窗口類名(例:Button)</param>
        /// <param name="lpWindowName">窗口標題</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 找到窗口
        /// </summary>
        /// <param name="hwndParent">父窗口句柄(如果為空,則為桌面窗口)</param>
        /// <param name="hwndChildAfter">子窗口句柄(從該子窗口之后查找)</param>
        /// <param name="lpszClass">窗口類名(例:Button</param>
        /// <param name="lpszWindow">窗口標題</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private extern static IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        /// <summary>
        /// 發送消息
        /// </summary>
        /// <param name="hwnd">消息接受窗口句柄</param>
        /// <param name="wMsg">消息</param>
        /// <param name="wParam">指定附加的消息特定信息</param>
        /// <param name="lParam">指定附加的消息特定信息</param>
        /// <returns></returns>
        [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();
        }

  

 

參考:

https://www.cnblogs.com/easypass/p/4067484.html

https://www.cnblogs.com/tary2017/articles/8031782.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM