This example shows how to start/stop remote Windows Service from client machine using C# application.
First, create a Windows application and put 4 label controls for displaying service name and status of the service.
On the button click event, we need to write the following lines of code.
- private void btnStartStop_Click(object sender, EventArgs e) {
- try {
- string serviceName = "ServiceName";
- string IP = "xxx.xxx.x.xx";
- string username = "username";
- string password = "password";
- ConnectionOptions connectoptions = new ConnectionOptions();
- connectoptions.Username = username;
- connectoptions.Password = password;
- ManagementScope scope = new ManagementScope("\\\\xxx.xxx.x.xx\\root\\Machine Name");
- scope.Options = connectoptions;
-
- SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");
- using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) {
- ManagementObjectCollection collection = searcher.Get();
- foreach(ManagementObject service in collection.OfType < ManagementObject > ()) {
- if (service["started"].Equals(true)) {
-
- service.InvokeMethod("StopService", null);
- btnStartStop.Text = "Start";
- lblServiceName.Text = serviceName;
- lblServiceStatus.Text = "Stopped";
- } else {
-
- service.InvokeMethod("StartService", null);
- btnStartStop.Text = "Stop";
- lblServiceName.Text = serviceName;
- lblServiceStatus.Text = "Running";
- }
- }
- }
- } catch (NullReferenceException) {
- throw;
- }
- }
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }