我想用c#编写一个UI自动化程序,但我找不到一些带有“Inspect.exe”的元素,找不到文字标签的图片(如图片1),为什么?
image1:https://i.stack.imgur.com/NqpKA.png
image2:https://i.stack.imgur.com/2PIuj.png
代码示例:
var desktop = AutomationElement.RootElement;
var condition = new PropertyCondition(AutomationElement.NameProperty, "Customer Register");
var window = desktop.FindFirst(System.Windows.Automation.TreeScope.Children, condition);
答案 0 :(得分:0)
您发布的用于获取元素的代码与我在屏幕截图中看到的内容相符。我有一种感觉,由于文本编码,UI Automation没有得到回名。除非您有权访问源代码并且可能会弄乱它并为这些标签设置文本,否则将无法通过UI Automation检索文本。
您可以使用您拥有的代码并使用win32 api窗口的本机窗口句柄来获取文本。
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);
public static string GetWindowTextRaw(IntPtr hwnd)
{
// Allocate correct string length first
int length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
StringBuilder sb = new StringBuilder(length + 1);
SendMessage(hwnd, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
return sb.ToString();
}
public static void YourMethod()
{
var desktop = AutomationElement.RootElement;
var process = Process.Start("Path/To/Your/Process.exe");
var condition = new PropertyCondition(AutomationElement.ProcessId, process.Id);
var window = desktop.FindFirst(System.Windows.Automation.TreeScope.Children, condition);
var windowTitle = GetWindowTextRaw(window.NativeWindowHandle)
}
来源: