Get name of window which is being closed using automation events c#

女生的网名这么多〃 提交于 2020-04-15 15:32:08

问题


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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!