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

6.1k views Asked by At

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?

3

There are 3 answers

0
Stephen Martin On

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.

1
Justin Harvey On

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

0
Adam On

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