標籤:pac 程式 cts 重疊 返回 text dll raw 問題
實現以下功能:
- 找到表單
- 找到控制項(也叫子表單)
- 擷取內容
- 擷取位置
- 設定
- 滑鼠點擊
示範1. 找表單
以作業系統內建的計算機為例
string clWindow = "CalcFrame";
//整個視窗的類名
string tlWindow = "計算機";
//視窗標題
IntPtr ParenthWnd = FindWindow(clWindow, tlWindow);
這樣就得到了視窗的控制代碼 ParenthWnd ,如果 ParenthWnd==IntPtr.Zero
說明沒有找到表單;
[DllImport("User32.dll", EntryPoint = "FindWindow")]public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
參數 lpClassName,lpWindowName 可以只填寫一個,但另一個需要填寫: null 而不是 :"" (即 string.Empty)。
如果同時開了幾個同樣的視窗,比如啟動了2個 計算機, 那返回的控制代碼是哪個的呢 ? 答案是:最頂層的那個。
1、如果計算機2介面,在計算機1介面的前面,那麼會返回計算機2的控制代碼。 2、如果兩個計算機介面是並排的,即不存在重疊(包括部分重疊), 先切換計算機1,然後切換計算機
2,然後切換別的程式,會返回計算機2的控制代碼,反之返回計算機1的控制代碼。
這個問題說的可能是Windows系統介面裡某個名詞的概念,如頂層視窗,Z次序,使用中視窗。但我不是特別明白,姑且舉例說明實際情況了。
2. 找控制項,擷取內容,擷取位置
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
這個函數使用起來比較麻煩,hwndParent 指的是目標控制項的直接上級的控制代碼,有時候你知道視窗的控制代碼還不行,還需要知道之間的層級關係,逐層尋找才行。這裡舉例說明一下怎麼用 :
FindWindowEx(ParenthWnd, IntPtr.Zero, "TPanel", "預覽列印");
我想說的是:參數 hwndChildAfter 可以寫 IntPtr.Zero,lpszClass和lpszWindow 可以為null 。
我一般是用枚舉的方法:枚舉得到這個視窗的所有控制代碼列表,然後篩選這個列表,從而得到想要的控制代碼。 上代碼:
[DllImport("user32.dll", ExactSpelling = true)]public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, int lParam);[DllImport("user32.dll")]public static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);[DllImport("user32.dll")]public static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);[DllImport("user32.dll")]public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);public delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);public struct WindowInfo{ public IntPtr hWnd;//控制代碼 public string szWindowName;//視窗名 public string szClassName;//類名 public System.Drawing.Rectangle Rect;//位置大小資訊}List<WindowInfo> EnumChildWindowsCallback(IntPtr handle){ //用於儲存控制代碼列表 List<WindowInfo> wndList = new List<WindowInfo>(); win32Api.EnumChildWindows(handle, delegate (IntPtr hWnd, int lParam) { WindowInfo wnd = new WindowInfo(); StringBuilder sb = new StringBuilder(256); //get hwnd wnd.hWnd = hWnd; //get window name GetWindowTextW(hWnd, sb, sb.Capacity); wnd.szWindowName = sb.ToString(); //get window class GetClassNameW(hWnd, sb, sb.Capacity); wnd.szClassName = sb.ToString(); RECT rect = new RECT(); if (GetWindowRect(hWnd, ref rect) == true) wnd.Rect = rect.ToRectangle(); wndList.Add(wnd); return true; }, 0); //這裡已經得到控制代碼列表 “wndList” ,對wndList進行篩選即可。 return wndList;}
C#調用win32 api 操作其它視窗