从C#中的外部应用获取UI文本
问题描述:
是否有可能从C#中的外部应用获取UI文本?从C#中的外部应用获取UI文本
特别是,有没有办法从第三方编写的外部Win32应用程序读取标签中的Unicode文本(我认为这是一个正常的Windows标签控件)?该文本是可见的,但不能通过用户界面中的鼠标进行选择。
我假设有一些可访问的API(例如,用于屏幕阅读器)允许这样做。
编辑:目前正在研究使用类似Managed Spy App的东西,但仍然会欣赏任何其他线索。
答
如果通过发送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,则可以使用这些知识来获取文本。
答
没有看到WM_GETTEXT或WM_GETTEXTLENGTH值在那篇文章中,所以以防万一..
const int WM_GETTEXT = 0x0D;
const int WM_GETTEXTLENGTH = 0x0E;
答
如果你只关心标准的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);
}
}
这也适用于标准的win32标签和按钮。 Interop nit:SendMessage应该返回IntPtr,并为wParam提取IntPtr。在WM_TEXT的情况下可能无关紧要(虽然不正确的wParam可能会成为一个问题,如果以64位代码运行?),但是在代码被剪切并粘贴的情况下使用正确的类型是一种很好的做法。 – BrendanMcK 2012-06-14 22:42:58