C# – How to communicate with a windows service

cipcwindows-services

I want to create a windows service that validates data and access it from another windows application, but I'm new to services and I'm not sure how to start.

So, while the service is running, a windows application should somehow connect to the service, send some data and get a response, true or false.

Best Answer

I could successfully handle the (almost) same issue as yours doing the following:

In your Class : ServiceBase, that represents your Service class, you might have:

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

Now, implement:

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

AND

protected override void OnStop()
{...}

To handle custom commands calls:

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

Now, use this in the application where you'll call the Windows Service:

Enum to reference your methods: (remember, Services custom methods always receive an int32 (128 to 255) as parameters and using Enum you make it easier to remember and control your methods

private enum YourMethods
  {
    methodX = 128
  };

To call a specific method:

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

Doing this, you can control your service.

Here you can check how to create and install a Windows Service. More about the ExecuteCommand method.

Good luck!