0

When trying to press the standard Windows 7 logoff button while my WPF app is running, I get "This program is preventing Windows from logging off". I would like to force it to close without having to press "Force log off".

Similarly, pressing "End Task" in the (applications) Task Manager causes it to become non-responsive rather than just close the program.

I have tried adding this to Window_Closing, but this doesn't seem to do it:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Environment.Exit(0);
}

I'm new to WPF, but it seems to me that the window is not closing properly. How can I prevent the "program is preventing Windows from logging off" when executing the Windows logoff, or "Program is not responding" when killing it from task manager?

Alex
  • 689
  • 1
  • 8
  • 22

1 Answers1

1

This should only be an issue if your application is not responding to the close events sent from Windows.

This will typically happen if you are executing code on the UI thread, which prevents it from responding to messages. As such, putting something in the closing events and similar will have no effect, as they won't be able to process until after your "work" finishes.

The proper way to handle this is to move your work onto background threads. This keeps the application responsive, which allows it to respond to the request from Windows to Close.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • I think that makes sense to me. My program is doing a lot of database work. I had originally developed this with winforms and as my first WPF project copied all of my classes into a WPF and created some dispatchtimers. So from what you wrote, the proper way to develop a WPF app is to have all of the work done on a separate thread from the UI? – Alex Mar 04 '15 at 22:33
  • @AlexB Yes, though that's also true in Windows Forms. If you did it in the main thread there, you'd get the same problem. – Reed Copsey Mar 04 '15 at 23:57
  • Is it ok to have a lot of database functions and other background work on 4 separate dispatchertimers running on the UI thread? – Alex Mar 05 '15 at 19:11
  • 1
    @AlexB That'll cause them to lock up the UI, and make this behavior. – Reed Copsey Mar 05 '15 at 21:51