如何找到桌面上報錯的窗口,不管是父窗口還是子窗口,而且獲得它的出錯信息呢?
主要是利用API函數:
[DllImport("user32.dll")] public static extern int FindWindowEx(int hwndParent, int hwndChildAfter,string lpszClass, string lpszWindow); [DllImport("user32.dll")] public static extern int FindWindow(string strclassName, string strWindowName); [DllImport("user32.dll")] public static extern int GetLastActivePopup(int hWnd); [DllImport("user32.dll")] public static extern int AnyPopup(); [DllImport("user32.dll")] public static extern int GetWindowText(int hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll")] public static extern int EnumThreadWindows(int dwThreadId, CallBack lpfn, int lParam); [DllImport("user32.dll")] public static extern int EnumWindows(CallBack lpfn, int lParam); [DllImport("user32.dll")] public static extern int EnumChildWindows(int hWndParent, CallBack lpfn, int lParam);
最關鍵的是對windows操作系統中窗口本質的認識,使用Spy++工具,查找窗口就可以發現,其實對於給定
的對話框窗口,其中的任何控件,如圖標、文本、確定、取消按鈕等都是它的子窗口,本質上還是窗口,
所不同的只是,頂級父窗口查找時,用FindWindow函數,而查找子窗口時用FindWindowEx。
另外比較有用的是EnumWindows,可以遍歷所有的頂級父窗口,而EnumChildWindows則是遍歷其子窗口。
經過測試,EnumThreadWindows的回調函數無法調用,不知道是什么原因,望高手指教。
問題的解決思路就是使用EnumWindows遍歷所有的頂級父窗口,對每個頂級父窗口使用EnumChildWindows遍歷它的所有控件,每個控件其實也是窗口,拿到該控件的句柄后,就可以調用GetWindowText來獲取文本信息了。
具體實現時,首先需要定義以上API函數的回調函數代理:
/// <summary> /// 回調函數代理 /// </summary> public delegate bool CallBack(int hwnd, int lParam); //然后必須針對每個API函數定義代理的實例函數: /// <summary> /// 進程回調處理函數 /// </summary> /// <param name="hwnd"></param> /// <param name="lParam"></param> /// <returns></returns> public static bool ThreadWindowProcess(int hwnd, int lParam) { EnumChildWindows(hwnd,callBackEnumChildWindows, 0); return true; } /// <summary> /// 窗口回調處理函數 /// </summary> /// <param name="hwnd"></param> /// <param name="lParam"></param> /// <returns></returns> public static bool WindowProcess(int hwnd, int lParam) { EnumChildWindows(hwnd,callBackEnumChildWindows, 0); return true; } /// <summary> /// 子窗口回調處理函數 /// </summary> /// <param name="hwnd"></param> /// <param name="lParam"></param> /// <returns></returns> public static bool ChildWindowProcess(int hwnd, int lParam) { StringBuilder title = new StringBuilder(200); int len; len = GetWindowText(hwnd, title, 200); if(len > 0) { if(title.ToString().IndexOf(GlobalManager.ErrorMessage) != -1 ) { FindError = true; } } return true; } //最后要定義回調代理的實例 /// <summary> /// 進程窗口回調函數代理 /// </summary> public static CallBack callBackEnumThreadWindows = new CallBack(ThreadWindowProcess); /// <summary> /// 窗口回調函數代理 /// </summary> public static CallBack callBackEnumWindows = new CallBack(WindowProcess); /// <summary> /// 子窗口回調函數代理 /// </summary> public static CallBack callBackEnumChildWindows = new CallBack(ChildWindowProcess); //使用的例子: /// <summary> /// 客戶端是否彈出對話框 /// </summary> /// <returns></returns> public bool IsClientPopupWindows() { bool FindError = false; EnumWindows(callBackEnumWindows,0); return FindError; }
轉載自:http://qianglc.blog.163.com/blog/static/10306850320097111045667/