How to execute a method from Application.Shutdown

Scottintexas

Well-known member
Joined
Jun 21, 2018
Messages
47
Location
Texas
Programming Experience
5-10
I want to run a method in the MainWindowViewModel (I want to make sure some Com Ports are closed before the app closes). In the App.XAML I added Exit = "ExitEventHandler." I want the MainWindowViewModel to watch for this event and run the method to close the ports. I am not getting the setup right. Can you help?

App.XAML:
<Application x:Class="AFresh.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup"
             ShutdownMode="OnExplicitShutdown"
             Exit="ExitEventHandler">
</Application>

App.XAML.cs:
        public event EventHandler OnEndApplication;
        private void ExitEventHandler(object sender, ExitEventArgs e)
        {
            OnEndApplication?.Invoke(this, EventArgs.Empty);
        }

MainWindowViewModel:
        private void OnEndApplication(object sender, ExitEventArgs e)
        {
            stopButtonPressed = true;
            scanner.ClosePorts();
        }

When I click on the Close X the screen vanishes, but my code is off somewhere and does not hit the break points at the ExitEventHandler or in the MainWindowViewModel. It just goes away without ending.

It is my understanding that I can listen for an even anywhere and in multiple places in my logic just by adding the "listener" method where ever I want to do something with the event. Please tell me where I am seeing this wrong.

Scott
 
Are you sure that OnEndApplicaiton was not null?
 

Latest posts

Back
Top Bottom