1. 程式人生 > >如何獲取視窗內文字框的控制代碼

如何獲取視窗內文字框的控制代碼

一  背景

  某種情況下,需要從某窗體獲取該窗體文字框內的內容,發現文字框並沒有標題名,無法獲取文字框控制元件的控制代碼。接下來,我將介紹我獲取所需文字框控制元件控制代碼方法。

二  使用Spy++獲取

  如圖,開啟Spy++可以直接獲取到“測試視窗”的所有控制元件控制代碼。

      

三  EnumChildWindows遍歷所有控制代碼

  一般窗體內文字框前面都有一個lable控制元件來標註,比如“測試視窗”內有一個名為“Test”的標示。在使用EnumChildWindows遍歷時,發現lable控制元件控制代碼後的那個控制代碼一般都是對應文字框的。所以,我們可以使用FindWindowEx(h,

IntPtr.Zero, null, lpszWindow)函式獲取lable控制元件的控制代碼。然後遍歷出所有控制代碼,查詢到label控制元件的控制代碼後,往後+1即可找到文字框的控制代碼。

  public static List<IntPtr> GetIntPtr(IntPtr hwd)
        {
            List<IntPtr> listIntPtr = new List<IntPtr>();
            ExternApi.EnumChildWindows(hwd, delegate (IntPtr hWnd, int lParam)
            { 
                listIntPtr.Add(hWnd);
                return true;
            }, 0);
            return listIntPtr;
        }
        public static IntPtr FindWindowEx(IntPtr hwnd, string lpszWindow, bool bChild)
        {
            IntPtr iResult = IntPtr.Zero;
            // 首先在父窗體上查詢控制元件
            iResult = ExternApi.FindWindowEx(hwnd, IntPtr.Zero, null, lpszWindow);
            // 如果找到直接返回控制元件控制代碼
            if (iResult != IntPtr.Zero) return iResult;

            // 如果設定了不在子窗體中查詢
            if (!bChild) return iResult;

            // 列舉子窗體,查詢控制元件控制代碼
            int i = ExternApi.EnumChildWindows(
            hwnd,
            (h, l) =>
            {
                IntPtr f1 = ExternApi.FindWindowEx(h, IntPtr.Zero, null, lpszWindow);
                if (f1 == IntPtr.Zero)
                    return true;
                else
                {
                    iResult = f1;
                    return false;
                }
            },
            0);
            // 返回查詢結果
            return iResult;
        }

程式碼段共包含兩個方法,FindWindowEx方法:獲得lable控制元件控制代碼;GetIntPtr方法:遍歷所有控制元件控制代碼。