在C#中从外部应用程序获取UI文本

是否可以从C#中的外部应用程序获取UI文本。

特别是,有没有办法从第三方编写的外部Win32应用程序读取标签中的Unicode文本(我认为它是一个普通的Windows标签控件)? 文本是可见的,但在UI中不能通过鼠标选择。

我假设有一些可访问性API(例如用于屏幕阅读器)允许这样做。

编辑:目前正在寻找使用类似管理间谍应用程序的东西,但仍然会欣赏任何其他线索。

如果该unicode文本实际上是一个带有标题的窗口,您可以通过发送WM_GETTEXT消息来执行此操作。

[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); 

如果它只是画在canvas上,如果你知道应用程序使用什么框架,你可能会有一些运气。 如果它使用WinForms或Borland的VCL,您可以使用该知识来获取文本。

如果您只关心标准的Win32标签,那么WM_GETTEXT将正常工作,如其他答案中所述。

有一个辅助functionAPI – UIAutomation – 用于标准标签,它也在后台使用WM_GETTEXT。 然而,它的一个优点是它可以从几种其他类型的控件中获取文本,包括大多数系统控件,以及通常使用非系统控件的UI – 包括WPF,IE和Firefox中的文本等。

 // 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 ); } } 

在那篇文章中没有看到wm_gettext或wm_gettextlength的值,所以以防万一..

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