我正在使用UIAutomation并尝试在第三方应用程序中获取任何控件的窗口ID。我想知道如何在屏幕上的特定坐标处找出控件的ID。
示例:我在桌面上运行了计算器,记事本和Word。所有这些都在运行并部分共享屏幕。我希望能够运行我的程序然后单击屏幕上的任何位置并获取基础控件的窗口ID(如果鼠标下方有任何内容)。
我需要使用什么来实现此功能。我知道我需要有一些鼠标钩子,但真正的问题是如何在点击鼠标的屏幕上获得控件的窗口ID(而不是窗口句柄)。
答案 0 :(得分:1)
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;
}
答案 1 :(得分:1)
如果我理解正确,你想要达到的是 - > 单击屏幕的任意位置,从运行元素中获取基础元素的窗口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;
}