问题
Why UIAutomation is not able to fetch chrome's context menu elements.
C# Code: The below code will subscribe to the root element.
public void SubscribeToInvoke()
{
Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent,
AutomationElement.RootElement,
TreeScope.Descendants, UIAEventHandler);
Automation.AddAutomationEventHandler(AutomationElement.MenuClosedEvent,
AutomationElement.RootElement,
TreeScope.Descendants, UIAEventHandler);
}
The bellow event is not getting fired in the case of google chrome, but in other cases (i.e. IE or Firefox or any other application) it is fine.
private void UIAEventHandler(object sender, AutomationEventArgs e)
{
AutomationElement sourceElement;
sourceElement = sender as AutomationElement;
if (e.EventId == AutomationElement.MenuOpenedEvent)
{
}
else if (e.EventId == AutomationElement.MenuClosedEvent)
{
}
}
Is there any code changes required or is there any alternative solution for this problem?
回答1:
I have achieved this task by using a method called as FromPoint(). My use case was to get right click and paste event.
Step 1: Subscribe to the menu open and close event:
public void SubscribeToInvoke()
{
Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent,
AutomationElement.RootElement,
TreeScope.Descendants, UIAEventHandler);
Automation.AddAutomationEventHandler(AutomationElement.MenuClosedEvent,
AutomationElement.RootElement,
TreeScope.Descendants, UIAEventHandler);
}
Step 2: When MenuOpenedEvent start timer which will get the current location of your mouse and on MenuCloseEvent strop timer.
if (e.EventId == AutomationElement.MenuOpenedEvent)
{
timer_Chrome.Enabled = true;
}
else if (e.EventId == AutomationElement.MenuClosedEvent)
{
timer_Chrome.Enabled = false;
}
Step 3: Get the element at the mouse location
System.Windows.Point point = new System.Windows.Point(Cursor.Position.X, Cursor.Position.Y);
AutomationElement sourceElement = AutomationElement.FromPoint(point);
来源:https://stackoverflow.com/questions/41463275/microsoft-ui-automation-not-able-to-fetch-chromes-context-menu-elements