views:

88

answers:

1

Hi,

I am developing a windows service in .Net 3.5 in C#. This service is used to periodically invoke a windows form. Now I would like to hook an event to the service so that when the user tries to shut down the system, then also the windows form will appear, preventing the shut down process. User can then only make the system shutdown through the windows application.

Is there a way to do this in a windows service?

Edit

I want this to be done in Win 2000 and Win XP only.

Thanks

+2  A: 

Services should not interact with the user session. In Vista and Win7 this is actually prohibited. The proper way to interact with the user session is to have an application in the session that communicates with the service, so your approach to create a service that starts periodically a form is flawed. Preventing system shutdown sounds just as bad, and again Win7 will just overwrite your application with a dim screen suggesting the user to kill the vandal (that is the misbehaving appp, yours).

Legitimate applications that alter the user experience the way you suggest have proper APIs to do so, like shell replacements for example.

Remus Rusanu
Your app part of the service/app pair can respond to shutdown events, http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx. Not the service. Consider the case when there is no user logged on but the service is running. Or when there are multiple users logged on on remote terminal services.
Remus Rusanu
And while is true that a service can also receive shutdown notifications, see http://msdn.microsoft.com/en-us/library/ms685058(VS.85).aspx, it should not display dialogs to the user.
Remus Rusanu
You might also run into problems trying to execute a new program during shutdown... if you've ever tried running a program after hitting shutdown you get the message "Unable to complete request: shutdown in progress". So there may be some restrictions in place.
Mike Weller
Mike is also right. You won't event be able to load a new module. You're trying to implement a horrible hack, when there is a perfectly legitimate approach: an interactive application that runs in the user session and communicates with the service (the typical 'tray icon' application).
Remus Rusanu
As valid as all advises may be, I guess adamantium wants to write an application just for himself, not for the public, to prevent shutdown for i.e. a server that shouldn't be shutdown unless absolutely sure (hence the warning / form / whatever).In that case I'd suggest a service that pop a dialog "really shut down?" with Ok and Cancel on the shutdown event, with shutdown cancel event args if possible.
Webleeuw
@Webleeuw exactly this is what I am looking for. But I don't know how to hook shutdown event in a windows service.
rahul
See the two links in my second comment on how to receive shutdown notifications in a service
Remus Rusanu