6

I have an issue that occurs during shutdown. I have piece of code written in C++ that is wrapped in a .dll and injected into other applications. It does a bunch of stuff including starting another application (sever) that is written in C#.

However, after a shutdown is initiated, the c++ code starts the C# application, because its been killed by the shutdown, which promptly crashes because the system is about to shutdown.

Then an error box halts the shutdown until the user deals with it, which is annoying. Is there a way to ask the OS, "Hey, are you shutting down/rebooting/logging out?" so I do not start an application while that's happening? I suppose a solution on either end would be fine.

== EDIT ==

For a little more clarification. The code that is running as an injected .dll, can't assume that the application its injected into has any kind of "window". Also, I would like something that I could query, not an event I have to listen to because I may miss that event due to timing. I'm wondering if there is any sort of function that would effectively give me something like this

bool IsSystemShutting();

And in this respect at C# option would work for me as well as a C++ option. But in the .NET framework SystemEvents.SessionEnding and SystemEvents.SessionEnded are both events versus properties. Its very often the case that I'd be signing up for this event AFTER the event has occurred, so it does me no good right.

Ultratrunks
  • 2,464
  • 5
  • 28
  • 48

1 Answers1

4

The WM_ENDSESSION and WM_QUERYENDSESSION messages are meant for this scenario. Windows will send these window messages to a window when a shutdown, restart, or logoff process is initiated.

syazdani
  • 4,760
  • 1
  • 26
  • 35
  • 1
    I'm not sure this will work for me. It looks like you have to setup a callback to capture this message. My code is injected into another application so is it possible that it can trap this message and I not receive it. I really don't want to be told when the OS is shutting down, I want to ask on my own schedule. Is that possible or is this call back the only way. Also, I'm residing in processes that don't have windows. Will this be a problem with this method? – Ultratrunks Feb 19 '13 at 18:21
  • You can always create a stub singleton executable that spawns a hidden window and maintains the shutdown state (using those two messages) in shared memory. That stub can be spawned by the first instance of your core application. Then, your applications can query for the shutdown state by peeking into the shared memory of the stub singleton. Its not the easiest code to write, but it will work. – syazdani Feb 19 '13 at 21:24