How to pass a message from windows service to windows desktop application using c#?

我只是一个虾纸丫 提交于 2019-12-10 16:25:51

问题


I want to pass a message from windows service to an windows desktop application that is already running. I have implemented a timer on windows service. after an interval the service send a message to the windows application.

The service or sender code is below:

System.Diagnostics.Process[] lProcs = System.Diagnostics.Process.GetProcessesByName("TestProcess2");

        if (lProcs.Length > 0)
        {
            IntPtr handle = lProcs[0].MainWindowHandle;

            if (handle != IntPtr.Zero)
                SendMessage(handle, 232, IntPtr.Zero, IntPtr.Zero);
        }

and the windows desktop application (receiver) code are as follows:

protected override void WndProc(ref Message m)
    {
        if (m.Msg == 232)
        {
            MessageBox.Show("Received");
        }
        else
        {
            base.WndProc(ref m);
        }
    }

the above code is working fine when both process are windows desktop application. when i used windows service as a sender then the windows desktop application process can not receive the message. Can you help me please?


回答1:


The service and the desktop application are running in two different Window Stations. For security reasons it is impossible to send window messages between applications running in separate Window Stations.

In order to communicate between a service and a desktop application you must use some sort of inter-process communication method (good possibilities are sockets, named pipes, DCOM, etc.) or some framework running on top of one of these, such as Remoting or WCF.




回答2:


I suspect this is because the two processes are running under different user accounts.

I think you need to use the change message filter function to allow it to be received, see here:

ChangeWindowMessageFilterEx function




回答3:


One way to do this, is to host a WCF interface in your service. This then allows communication between (potentially) any application and the service.

Check out these links for detailed examples:

http://www.codeproject.com/Articles/38160/WCF-Service-Library-with-Windows-Service-Hosting http://msdn.microsoft.com/en-us/library/ms733069.aspx



来源:https://stackoverflow.com/questions/12976140/how-to-pass-a-message-from-windows-service-to-windows-desktop-application-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!