Show a message box from a Windows Service

2019-01-18 09:55发布

问题:

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.

回答1:

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).



回答2:

You can display a message from a service with "WTSSendMessage" function, here is a good article: http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx



回答3:

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.



回答4:

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.



回答5:

OS:XP Enabling Interactive Mode for Windows Services

Procedure

  1. Open the Services control panel. For example: Start > Control Panel > Administrative Tools > Services.
  2. Select the Cast Iron Secure Connector service.
  3. Right-click the service name, and select Properties. The Service Properties window is displayed.
  4. Select the Log On tab.
  5. Select Local System account and then select Allow service to interact with desktop.
  6. Click OK.
  7. Click Restart.


回答6:

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