c# - 如何与Windows服务通信?

标签 c# windows-services ipc

我想创建一个 Windows 服务来验证数据并从另一个 Windows 应用程序访问它,但我是服务的新手,我不确定如何开始。

因此,当服务运行时,Windows 应用程序应该以某种方式连接到该服务,发送一些数据并获得响应,无论是对还是错。

最佳答案

我可以通过以下方式成功处理(几乎)与您相同的问题:

在您的 Class : ServiceBase 中,代表您的服务类,您可能有:

public Class () //constructor, to create your log repository
    {
      InitializeComponent();

      if (!System.Diagnostics.EventLog.SourceExists("YOURSource"))
      {
        System.Diagnostics.EventLog.CreateEventSource(
           "YOURSource", "YOURLog");
      }
      eventLog1.Source = "YOURSource";
      eventLog1.Log = "YOURLog";
    }

现在,实现:

protected override void OnStart(string[] args)
{...}

protected override void OnStop()
{...}

处理自定义命令调用:

protected override void OnCustomCommand(int command)
    {
      switch (command)
      {
        case 128:
          eventLog1.WriteEntry("Command " + command + " successfully called.");
          break;
        default:
          break;
      }
    }

现在,在调用 Windows 服务的应用程序中使用它:

引用您的方法的枚举:(请记住,服务自定义方法总是接收一个 int32(128 到 255)作为参数,使用枚举可以让您更容易记住和控制您的方法

private enum YourMethods
  {
    methodX = 128
  };

调用特定方法:

ServiceController sc = new ServiceController("YOURServiceName", Environment.MachineName);
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "YOURServiceName");//this will grant permission to access the Service
    scp.Assert();
    sc.Refresh();

    sc.ExecuteCommand((int)YourMethods.methodX);

这样做,您可以控制您的服务。

Here您可以查看如何创建和安装 Windows 服务。 More关于 ExecuteCommand 方法。

祝你好运!

关于c# - 如何与Windows服务通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4451216/

相关文章:

c - 从 parent 向 child 发送信号

perl - 运行和监视进程并使用 Perl(在 Windows 上)捕获其所有输出?

c# - Visual Studio 2008 不断将输出目录设置为相对路径

c# - asp.net登录后如何获取当前用户的用户名

c# - 有没有办法从 FCKEditor 中删除所有不必要的 MS Word 格式

c# - 调用 Web 服务时出现 HTTP 407 代理身份验证错误

c# - 将 HttpClient 类与 WinRT 结合使用

c# - 编译输出类型为 Exe 的 Windows 服务

asp.net - 云中的 Windows 服务

docker - docker进程能否通过ipc访问主机上的程序