Reputation: 1412
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:
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
Upvotes: 2
Views: 1355
Reputation: 1662
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.
Upvotes: 1
Reputation: 8642
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.
Upvotes: 0