2

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:

  1. Value of variable sender will be null.
  2. 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

akhi1
  • 1,322
  • 1
  • 16
  • 25
  • simple tip:Why not do something specific on each window's `Closing` event like passing the name to a `My.Settings` variable or any global string variable that may hold their names? then retieve them back ? – Software Dev Mar 13 '18 at 13:07
  • @zackraiyan its a part of automation project and here window close can happen due to multiple reasons. So its best for me to work with event handlers – akhi1 Mar 13 '18 at 13:13
  • ow,i understand :) – Software Dev Mar 13 '18 at 13:15

2 Answers2

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.

Max Young
  • 1,522
  • 1
  • 16
  • 42
0

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.

Simply Ged
  • 8,250
  • 11
  • 32
  • 40