我正在使用 UIAutomation 并尝试获取 3rd 方应用程序中任何控件的窗口 ID。我想知道如何在屏幕上的特定坐标处找出控件的 ID。
示例:我在桌面上运行了计算器、记事本和 Word。他们都在运行并部分共享屏幕。我希望能够运行我的程序,然后单击屏幕上的任何位置并获取底层控件的窗口 ID(如果有任何在鼠标下)。
我需要使用什么来实现此功能。我知道我需要某种鼠标钩子,但真正的问题是如何在单击鼠标的屏幕上获取控件的窗口 ID(而不是窗口句柄)。
我正在使用 UIAutomation 并尝试获取 3rd 方应用程序中任何控件的窗口 ID。我想知道如何在屏幕上的特定坐标处找出控件的 ID。
示例:我在桌面上运行了计算器、记事本和 Word。他们都在运行并部分共享屏幕。我希望能够运行我的程序,然后单击屏幕上的任何位置并获取底层控件的窗口 ID(如果有任何在鼠标下)。
我需要使用什么来实现此功能。我知道我需要某种鼠标钩子,但真正的问题是如何在单击鼠标的屏幕上获取控件的窗口 ID(而不是窗口句柄)。
如果我理解正确,您要实现的是->单击屏幕的任何位置,从正在运行的元素中获取底层元素的窗口 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;
}
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;
}