Currently I'm checking it in the following way:
if (Environment.UserInteractive)
Application.Run(new ServiceControllerForm(service));
else
ServiceBase.Run(windowsService);
It helps debugging a little and service can also be run using the executable. But assume now that the service requires interaction with the user desktop so that I have to enable "Allow service to interact with desktop" in the properties. This of course breaks this way of checking. Is there another way?
Windows has always used the Services panel as a way to manage the services that are running on your computer. You can easily get there at any point by simply hitting WIN + R on your keyboard to open the Run dialog, and typing in services. msc.
In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button. The Processes dialog box appears. Select the Show processes from all users check box. In the Available Processes section, choose the process for your service, and then choose Attach.
Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.
The issue with the accepted answer is that checking the status of an service that isn't installed will throw. The IsService
Method I'm using looks like this:
private bool IsService(string name)
{
if (!Environment.UserInteractive) return true;
System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(name);
try
{
return sc.Status == System.ServiceProcess.ServiceControllerStatus.StartPending;
}
catch(InvalidOperationException)
{
return false;
}
}
Which should work more reliably than just checking Environment.UserInteractive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With