You will find the solution here.
I need some method/event to be fired when i close my application from task manager.
Hi Team,
I have the scenario like I have WPF application running on my machine with only one window.
I am making that window visibility hidden when the window got loaded.
Now have senario to fire the event/method to check the process/window got closed from task manager.
Best Regards,
Sunil
3 answers
Sort by: Most helpful
-
-
Hui Liu-MSFT 40,271 Reputation points Microsoft Vendor
2022-08-05T08:38:50.683+00:00 Hi,@Sunil A M . You could use the following code to prompt the application to close with an empty window.
Codebehind:private void Window_Loaded(object sender, RoutedEventArgs e) { this.Visibility = Visibility.Hidden; Window wnd = new Window(); wnd.Width = 0; wnd.Height = 0; wnd.WindowStyle = WindowStyle.None; wnd.Loaded += delegate { HwndSource source = (HwndSource)PresentationSource.FromDependencyObject(wnd); // wnd.Visibility = Visibility.Hidden; source.AddHook(WindowProc); }; wnd.Show(); } private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case 0x11: case 0x16: MessageBox.Show("Close reason: WindowsShutDown"); break; case 0x112: if ((LOWORD((int)wParam) & 0xfff0) == 0xf060) { MessageBox.Show("Close reason: UserClosing"); } break; } return IntPtr.Zero; }
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html
-
RLWA32 40,651 Reputation points
2022-08-05T10:38:19.583+00:00 I created a WPF App (.Net Framework 4.8) using the Window_Loaded event to hide the window as shown above. Following is the process window tree shown by Spy++. The MainWindow is not visible and Spy++ is set to log all window messages that MainWindow receives.
Then I used Task Manager to End Task on WPFApp1.exe. The application closed but no window messages were seen by Spy++. It seems to me that Task Manager used TerminateProcess instead of sending a WM_SYSCOMMAND (SC_CLOSE) or WM_CLOSE message to the hidden window.
For comparison, this is what Spy++ sees when MainWindow is not hidden and the process is closed by Task Manager -
Consider a different way to allow a user to end the hidden window application -- use a notification area icon to allow the user to close the application instead of Task Manager.