如何使用 c# 将消息从 Windows 服务传递到 Windows 桌面应用程序? [英] How to pass a message from windows service to windows desktop application using c#?

查看:85
本文介绍了如何使用 c# 将消息从 Windows 服务传递到 Windows 桌面应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将消息从 Windows 服务传递到已在运行的 Windows 桌面应用程序.我已经在 Windows 服务上实现了一个计时器.一段时间后,该服务向 Windows 应用程序发送一条消息.

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);
        }

和windows桌面应用(接收器)代码如下:

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);
        }
    }

当两个进程都是 Windows 桌面应用程序时,上面的代码工作正常.当我使用 Windows 服务作为发件人时,Windows 桌面应用程序进程无法接收消息.你能帮我吗?

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?

推荐答案

服务和桌面应用程序在两个不同的 Window Station 中运行.出于安全原因,无法在运行于不同窗口站的应用程序之间发送窗口消息.

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.

为了在服务和桌面应用程序之间进行通信,您必须使用某种进程间通信方法(很好的可能性是套接字、命名管道、DCOM 等)或运行在其中一个之上的一些框架,例如远程处理或 WCF.

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.

这篇关于如何使用 c# 将消息从 Windows 服务传递到 Windows 桌面应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆