问题
I'm working on a project where I need to get the name of windows which is being closed. I'm using C# Automation events for this.
I've pasted below the code that I'm using:
Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent,
AutomationElement.RootElement, TreeScope.Subtree, (sender, eve) =>
{
AutomationElement winElemnt = sender as AutomationElement;
if (winElemnt != null)
{
Console.WriteLine("Window closed : " + winElemnt.Current.Name);
}
});
The above code get triggered when any window closes but I'm getting following error on execution:
- Value of variable sender will be null.
- Unable to get automation element's Current.Name (I'm getting this error most of the time)
On debugging I was able to find that the 2nd error is due to window closing before completing event handler execution.
Please let me know how to fix these errors and get the name of window for which close is triggered.
Thanks in advance
回答1:
I believe you need to use caching to be able to retrieve the property when the window closes since the automation element will be gone.
The remarks for the WindowPattern says the following
A client application may need to listen for WindowClosedEvent from a cached object since a window is removed from the UI Automation control view structure immediately upon being closed.
回答2:
This is what it says in the documents:
When your application receives a window-closed event, the sender parameter of the event handler cannot be used to obtain information about the window that has closed, because the corresponding UI Automation element is no longer valid.
I'm afraid you'll have to find another way to get the window name.
来源:https://stackoverflow.com/questions/49256992/get-name-of-window-which-is-being-closed-using-automation-events-c-sharp