如何在Windows服务C#中显示消息框

如何在Windows服务C#中显示消息框

问题描述:

嗨开发者,



任何机构都可以分享如何在Windows服务中显示消息框,我听说我们无法在Windows服务中显示消息框但是使用 WTSSendMessage这个我们可以显示消息框但是怎么做,请帮我这个。



谢谢和问候

Aravidn G

Hi Developers,

Can any body will share how to show message box in Windows Service, i heard that we cannot show message box in Windows Service but using "WTSSendMessage" this we can show the message box but how to do,please help me this.

Thanks & regards
Aravidn G

你不能,你不应该尝试这样做。即使所有用户都注销,Windows服务也应该继续运行,因此它可以在没有桌面显示任何内容的情况下工作。



与UI相关的UI方法服务是不同的。您应该开发一个单独的应用程序,应该通过某种IPC机制与服务进行通信,例如通过远程或WCF的IPC通道(在这种情况下,在您的服务中自托管),但它可以是套接字或命名管道通讯。其中一种方法是:在某些用户登录时启动此类应用程序(为此目的有一个注册表项Run)并尝试连接到该服务。使用此频道进行服务与此UI应用程序之间的通信,尤其是显示服务通知。



-SA
You cannot and you should not try to do it. The Windows Service is supposed to keep running even if all users log off, so it can work without having a desktop to show anything.

The approach to UI related to the service is different. You should develop a separate application with should communicate with the service through some IPC mechanism, for example through an IPC channel of remoting or WCF (in this case, self-hosted in your service), but it can be a socket or named pipe based communication. One of the approaches is this: you start such application when some user logs on (there is a registry entry "Run" for this purpose) and try to connect to the service. Use this channel for communications between the service and this UI application, in particular, to show service notifications.

—SA


[DllImport("wtsapi32.dll", SetLastError = true)]
    static extern bool WTSSendMessage(
                IntPtr hServer,
                [MarshalAs(UnmanagedType.I4)] int SessionId,
                String pTitle,
                [MarshalAs(UnmanagedType.U4)] int TitleLength,
                String pMessage,
                [MarshalAs(UnmanagedType.U4)] int MessageLength,
                [MarshalAs(UnmanagedType.U4)] int Style,
                [MarshalAs(UnmanagedType.U4)] int Timeout,
                [MarshalAs(UnmanagedType.U4)] out int pResponse,
                bool bWait);







bool result = false;
                  String title = "Alert";
                  int tlen = title.Length;
                  String msg = sb.ToString();
                  int mlen = msg.Length;
                  int resp = 7;
                  result = WTSSendMessage(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, title, tlen, msg, mlen, 4, 3, out resp, true);
                  int err = Marshal.GetLastWin32Error();