Ejemplo n.º 1
0
        public void StartStopService()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                var access = ServiceAccessTypes.SERVICE_START | ServiceAccessTypes.SERVICE_STOP | ServiceAccessTypes.SERVICE_QUERY_STATUS;

                //opens print spooler service
                using (var service = AdvApi32.OpenService(scm, "Spooler", access))
                {
                    AssertHandleIsValid(service);

                    //query service status
                    var status = AdvApi32.QueryServiceStatusEx <SERVICE_STATUS_PROCESS>(service, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO);

                    if (status.dwCurrentState == ServiceState.SERVICE_RUNNING)
                    {
                        var ret4 = AdvApi32.StopService(service, out var _);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_STOPPED);

                        var ret6 = AdvApi32.StartService(service);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                    else
                    {
                        var ret4 = AdvApi32.StartService(service);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_RUNNING);

                        var ret6 = AdvApi32.StopService(service, out var _);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                }
            }
        }