I have a Windows Forms application that when the Main Window is closing, it displays a basic dialog box, confirming the action. If the user decides to cancel the application
SystemEvents can help you. The SessionEnding occurs when the user is trying to log off or shut down the system.
Microsoft.Win32.SystemEvents.SessionEnding += (sender, e) => DoYourJob();