简体   繁体   中英

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

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM