Csharp/C Sharp/Windows/Windows Service
Версия от 15:31, 26 мая 2010; (обсуждение)
Activating a program remotely.
using System;
using System.ServiceProcess;
class MainClass {
public static void StartService(string server, string service) {
Console.WriteLine("About to start the {0} Service", service);
ServiceController svcCtrl;
if (server.Length != 0)
svcCtrl = new ServiceController(server, service);
else
svcCtrl = new ServiceController(service);
svcCtrl.Start();
}
public static void StopService(string server, string service) {
Console.WriteLine("About to stop the {0} Service", service);
ServiceController svcCtrl;
if (server.Length != 0)
svcCtrl = new ServiceController(server, service);
else
svcCtrl = new ServiceController(service);
svcCtrl.Stop();
}
public static void ShowServices(string server) {
ServiceController[] services;
if (server.Length != 0)
services = ServiceController.GetServices(server);
else
services = ServiceController.GetServices();
foreach (ServiceController svc in services) {
Console.WriteLine("Found service : {0}", svc.DisplayName);
}
}
public static void Main(string[] args) {
StartService(args[0], args[2]);
StopService(args[0], args[2]);
ShowServices(args[0]);
}
}
Creating a windows service.
using System;
using System.Collections;
using System.ruponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
public class WinService1 : System.ServiceProcess.ServiceBase {
private EventLog eventLog;
public WinService1() {
this.ServiceName = "WinService1";
string source = "Main";
eventLog = new EventLog();
eventLog.Source = source;
}
static void Main() {
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
protected override void OnStart(string[] args) {
eventLog.WriteEntry("starting up!");
}
protected override void OnStop() {
eventLog.WriteEntry("shutting down!");
}
}