user3894187
user3894187

Reputation: 35

control my application from a windows service

I have a C# desktop application which has some user input fields and 2 buttons - START & STOP. On clicking START, it will connect to a server/external device. Once connected, the user can input data and send the information to the server/external device. Now I need to create a Windows service to automatically START and STOP the connectivity with servers. I mean a service to establish the connection with the servers (as START button does).

Currently I have added a new Windows service project in my solution file. Now my solution file has two .exe files. First one is for building the user application, and other one is to build the Windows service.

My actual question is: Can I write the START button's click event code under the Service1.cs files's OnStart event (to automatically START & STOP the servers)?

Upvotes: 0

Views: 1155

Answers (1)

Matt Davis
Matt Davis

Reputation: 46052

The answer to your specific question is no. Since the Start button resides in the user application, the Clicked event will be triggered and handled there, not in the Windows service.

In order to control your Windows service from your user application, you'll have to use some kind of inter-process communication (IPC). This just makes sense, right? As I've already said, events in the application will not even be visible to the service for the service to act upon simply because they are two different processes. This is where IPC comes in. As the user interacts with the application, the interactions are translated into commands that are sent via the IPC mechanism to the service so that the service can perform the logic dictated by the commands. Likewise, results from the service can be sent via the IPC mechanism to the application for display to the user.

There are all kinds of IPC mechanisms - sockets, remoting, pipes, shared memory, etc. For .NET-based software, the recommended approach is the Windows Communication Foundation (WCF). In a nutshell, WCF allows you to define a programmatic API specific to your usage for exchanging information between more than one application domains. In essence, you exchange data by simply calling a method. From the developer's perspective, it's simply a function call. How the information is packaged and sent to the other application domain is dictated by how the WCF plumbing is configured. Want to use sockets? Want to use pipes? Want to use HTTP? All of these options (and more) are available by simply changing the WCF configuration.

I've used WCF successfully, but the learning curve is admittedly steep. In fact, I've fallen back to using sockets as my IPC mechanism for performance reasons. Still, WCF is worth a look because you don't have to worry about the intricacies of the chosen IPC mechanism. I've answered another question dealing with this here. It should get you started.

HTH

Upvotes: 1

Related Questions