Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if starting inside a windows service?

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?

like image 774
mikoro Avatar asked Mar 07 '10 17:03

mikoro


People also ask

How do I know if my Windows Service is working?

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.

How do I trace a Windows service?

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.

Can a Windows Service start a process?

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.


1 Answers

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

like image 120
Yaur Avatar answered Sep 28 '22 07:09

Yaur