如何在第三方应用程序中获得控件的窗口自动化id与UIAutomation在特定的屏幕坐标
本文关键字:id 自动化 屏幕坐标 窗口 UIAutomation 控件 第三方 应用程序 | 更新日期: 2023-09-27 17:51:02
我正在使用UIAutomation并试图获得第三方应用程序中任何控件的窗口Id。我想知道如何找出屏幕上特定坐标处的控件ID
例子:我有计算器,记事本,和Word在桌面上运行。它们都在运行并部分共享屏幕。我希望能够运行我的程序,然后在屏幕上的任何位置单击,并获得底层控件的窗口ID(如果有任何在鼠标下)。
我需要用什么来实现这个功能?我明白,我需要有某种鼠标钩子,但真正的问题是如何获得窗口ID(不是窗口句柄)在屏幕上的鼠标被点击的控制。
AutomationElement.FromPoint()
将在给定的点返回自动化元素。一旦有了这些,您就可以轻松地获得自动化ID:
private string ElementFromCursor()
{
// Convert mouse position from System.Drawing.Point to System.Windows.Point.
System.Windows.Point point = new System.Windows.Point(Cursor.Position.X, Cursor.Position.Y);
AutomationElement element = AutomationElement.FromPoint(point);
string autoIdString;
object autoIdNoDefault = element.GetCurrentPropertyValue(AutomationElement.AutomationIdProperty, true);
if (autoIdNoDefault == AutomationElement.NotSupported)
{
// TODO Handle the case where you do not wish to proceed using the default value.
}
else
{
autoIdString = autoIdNoDefault as string;
}
return autoIdString;
}
如果我理解正确的话,你想要达到的是->在屏幕的任意位置单击,从运行的元素中获取底层元素的窗口id(如果有的话):
如果是这种情况,下面应该可以帮助你理解(注意:这不仅会扩展光标位置,还会继续沿着x轴搜索100像素,间隔为10):
/// <summary>
/// Gets the automation identifier of underlying element.
/// </summary>
/// <returns></returns>
public static string GetTheAutomationIDOfUnderlyingElement()
{
string requiredAutomationID = string.Empty;
System.Drawing.Point currentLocation = Cursor.Position;//add you current location here
AutomationElement aeOfRequiredPaneAtTop = GetElementFromPoint(currentLocation, 10, 100);
if (aeOfRequiredPaneAtTop != null)
{
return aeOfRequiredPaneAtTop.Current.AutomationId;
}
return string.Empty;
}
/// <summary>
/// Gets the element from point.
/// </summary>
/// <param name="startingPoint">The starting point.</param>
/// <param name="interval">The interval.</param>
/// <param name="maxLengthToTraverse">The maximum length to traverse.</param>
/// <returns></returns>
public static AutomationElement GetElementFromPoint(Point startingPoint, int interval, int maxLengthToTraverse)
{
AutomationElement requiredElement = null;
for (Point p = startingPoint; ; )
{
requiredElement = AutomationElement.FromPoint(new System.Windows.Point(p.X, p.Y));
Console.WriteLine(requiredElement.Current.Name);
if (requiredElement.Current.ControlType.Equals(ControlType.Window))
{
return requiredElement;
}
if (p.X > (startingPoint.X + maxLengthToTraverse))
break;
p.X = p.X + interval;
}
return null;
}