前言:

要如何用滑鼠座標抓取到視窗的 Handle,進而取得資訊或文字呢?

 

觀念:

請參考MSDN Window Functions (參考以下連結),可以找到幾個實作的方法,

 1.FindWindow,當有已知視窗資訊,可以使用這一個,將資訊傳入,取得 Handle。

 2.GetForegroundWindow,會抓取到目前執行緒的視窗,也就是你正在看的視窗的 Handle。

 3.如果想要用滑鼠座標決定取得某個視窗的 Handle,可用 WindowFromPoint 

 今天主要利用WindowFromPoint 取得視窗的 Handle。

 

實作:

1.DllImport 

  DllImport 需using System.Runtime.InteropServices;

 IntPtr 型態則需 using System;


        [DllImport("user32.dll")]
        public static extern IntPtr WindowFromPoint(Point lpPoint);


 

2.利用滑鼠座標抓取到 Handle


IntPtr hWindow = WindowFromPoint(Control.MousePosition);


 

3.注意!用此方法抓取到的 Handle,如果滑鼠是指到視窗中的控件 (Control),

 則得到的是控件的 Handle(Control Handle)。

 

4.因此我們要利用另一個 Function GetAncestor ,取得最上層控件 Root Handle

 a.DllImport


[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
        public static extern IntPtr GetAncestor(IntPtr hWnd, int flags); 


 b.將步驟2得到的 Handle 傳入此 Function,


IntPtr hParentWindow = GetAncestor(hWindow, 2);


 第二個參數,可以傳入1、2、3,

 1的話會得到 hWindow 的 Parent Handle,但不一定是最上層的 Handle (Root Handle)。

 2的話會得到 hWindow 的 Root Handle,也就是整個視窗的 Handle。

 3的話就留給你們研究啦。

 

5.取得 Root Handle 後就可以進階取得視窗的資訊,或者往下取得每一個控件的 Handle

(Child Handle)(可參考以下連結)

 

6.如果有了 Handle 要抓取視窗或控件的文字 Text,

 a.DllImport,GetWindowText


 

 

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);


 

 b.將指定視窗或控件的 Handle 傳入


StringBuilder tempStr = new StringBuilder(512);

        GetWindowText(hParentWindow, tempStr, tempStr.MaxCapacity);


 c.取得的文字存在 tempStr,可用tempStr.ToString();取得字串

 

參考:

1.MSDN Window Functions http://msdn.microsoft.com/en-us/library/ff468919(v=VS.85).aspx

2.抓取 Child Handle http://jimmy1p4204.pixnet.net/blog/post/13457585

 

低調的關鍵字:

取得視窗的Title 取得視窗資訊 取得視窗的文字 取得視窗的內容 視窗 Window 控件 Control Handle

arrow
arrow
    全站熱搜

    GiMi 發表在 痞客邦 留言(0) 人氣()