views:

471

answers:

4

Can you display a message box (or any form of notification) from a windows service? Can't get it to work. I used:

            global::System.Windows.Forms.MessageBox.Show("A fatal error occurred. " +
                ServiceName + " is now terminating.");

but it didn't work and just produced an error.

+2  A: 

No, you cannot show a message box from a service. If you want to report errors, the standard way to do this is with the event log.

For more "advanced" kinds of UI (not just error reporting), the way this is typically done is via a regular windows application that you put in the user's Startup folder (or the Run key in the registry) and that talks to the service via some kind of IPC mechanism (.NET remoting, WCF, regular sockets, named pipes, etc).

Dean Harding
Ohh.. I was hoping for a general exception handler that would notify the user when an error occurred with the service. In some cases it would crash silently and the users wouldn't be aware that the service had crashed.
Jonn
A: 

No you can't. Windows services have no GUI. But you can show a little system tray notification.

Marcel
I don't think you can do this, since they have no interaction with the desktop.
rwmnau
Would you mind showing me an example of this? I haven't considered this possibility yet.
Jonn
@Jonn: I have not done this for myself, but this could help you out:http://msdn.microsoft.com/en-us/magazine/cc188923.aspx. Use P/Invoke to talk to the OS. It is important that you do not call any GUI component directly, as Windows Services can not have a GUI by design.
Marcel
A: 

From Wikipedia:

Although typically services do not have a user interface, developers can add forms and other UI components. In this case, the "Allow service to interact with desktop" should be checked on the Logon tab in the Service properties dialog (though care should be taken with this approach as this can cause a security risk since any logged in user would be able to interact with the service).

With this option enabled you should be able to display message boxes from a service.

Gart
You can enable that in code?
Jonn
@Jonn: I guess there is some API to change that in code, but generally this option shouldn't be relied on.
Gart
+1  A: 

Allow service to interact with desktop will help you doing this from the Services.msc console.

BUT, this is a very bad idea. Especially if you forget to remove this messagebox later on. The service will hang since you will have a messagebox which no one can click on.

Rahul Soni