2008-08-20 28 views
4

是否有可能從C#中的外部應用獲取UI文本?從C#中的外部應用獲取UI文本

特別是,有沒有辦法從第三方編寫的外部Win32應用程序讀取標籤中的Unicode文本(我認爲這是一個正常的Windows標籤控件)?該文本是可見的,但不能通過用戶界面中的鼠標進行選擇。

我假設有一些可訪問的API(例如,用於屏幕閱讀器)允許這樣做。

編輯:目前正在研究使用類似Managed Spy App的東西,但仍然會欣賞任何其他線索。

回答

5

如果通過發送WM_GETTEXT消息,該unicode文本實際上是帶有標題的窗口,則可以這樣做。

[DllImport("user32.dll")] 
public static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text); 

System.Text.StringBuilder text = new System.Text.StringBuilder(255) ; // or length from call with GETTEXTLENGTH 
int RetVal = Win32.SendMessage(hWnd , WM_GETTEXT, text.Capacity, text); 

如果它只是畫在畫布上,如果知道應用程序使用什麼框架,可能會有一些運氣。如果它使用WinForms或Borland的VCL,則可以使用這些知識來獲取文本。

+0

這也適用於標準的win32標籤和按鈕。 Interop nit:SendMessage應該返回IntPtr,併爲wParam提取IntPtr。在WM_TEXT的情況下可能無關緊要(雖然不正確的wParam可能會成爲一個問題,如果以64位代碼運行?),但是在代碼被剪切並粘貼的情況下使用正確的類型是一種很好的做法。 – BrendanMcK 2012-06-14 22:42:58

2

沒有看到WM_GETTEXT或WM_GETTEXTLENGTH值在那篇文章中,所以以防萬一..

const int WM_GETTEXT = 0x0D; 
const int WM_GETTEXTLENGTH = 0x0E; 
5

如果你只關心標準的Win32標籤,然後將WM_GETTEXT做工精細,如概述其他答案。

-

有一個輔助功能API - UIAutomation - 標準的標籤,它也使用WM_GETTEXT幕後。但是,它的一個優點是它可以從其他幾種控件(包括大多數系統控件)獲取文本,並且通常使用非系統控件(包括WPF,IE和Firefox中的文本等)的UI。

// compile as: 
// csc file.cs /r:UIAutomationClient.dll /r:UIAutomationTypes.dll /r:WindowsBase.dll 
using System.Windows.Automation; 
using System.Windows.Forms; 
using System; 

class Test 
{ 
    public static void Main() 
    { 
     // Get element under pointer. You can also get an AutomationElement from a 
      // HWND handle, or by navigating the UI tree. 
     System.Drawing.Point pt = Cursor.Position; 
     AutomationElement el = AutomationElement.FromPoint(new System.Windows.Point(pt.X, pt.Y)); 
     // Prints its name - often the context, but would be corresponding label text for editable controls. Can also get the type of control, location, and other properties. 
     Console.WriteLine(el.Current.Name); 
    } 
}