0

in C# I currently want to add an event which will fire when any window gets closed (not only a WPF or forms window). I got that step so far and that works perfectly fine. The SubscribeWindowClose event will be added when another program starts.

I had a look at Microsoft's documentation about the Automation.AddAutomationEventHandler.
In the doc was a description about caching the AutomationElement which I didn't quite get.
I just want to compare the closed window title with window titles I've got in a list (List).
Can anyone help me with this or show me a better way to solve my "issue"?
Thanks in advance!



Code:

     private void SubscribeWindowClose(AutomationElement window) {
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, 
                window, TreeScope.Element, OnWindowClose);
        }

        private void OnWindowClose(object src, AutomationEventArgs e) {
            try {
                var element = src as AutomationElement;
                Debug.WriteLine(element);

                if (e.EventId == WindowPattern.WindowClosedEvent) {
                    // if window title is in List, run method
                    return;
                }
            } catch (ElementNotAvailableException) {
                return;
            }
        }
RoXaS
  • 25
  • 4
  • [This answer](https://stackoverflow.com/a/49349831/2557128) has a comment linking to how you use caching with Automation so you can retrieve the name of the Window that just closed. – NetMage Jan 30 '20 at 20:08
  • Thanks @NetMage. This was the right direction! I used [this method](https://learn.microsoft.com/en-us/dotnet/api/system.windows.automation.automationelement.cachedchildren?view=netframework-4.8) at the end because it was more suitable. Thanks a lot! :) – RoXaS Jan 30 '20 at 21:33

1 Answers1

0

The comment from @NetMage was the step in the right direction.
Ended up with a modified version of this excample.
Condition was modified to ControlType.TitleBar and worked like a charm!

RoXaS
  • 25
  • 4