The tool class and the restart service process of calling Windows system to serve exe program in C#

Keywords: C# Windows Programming

scene

Use the Windows service program written by C to call in Winform.

Common tool class methods are used to detect whether the service exists or is installed, obtain the service status, start the service, and stop the service.

Take restarting a service in Winform for example.

Note:

Blog home page:
https://blog.csdn.net/badao_liumang_qizhi
Pay attention to the public address
Domineering procedural ape
Get programming related e-books, tutorial push and free download

Realization

New tool class WinServiceHelper

Method to check whether the service is installed or exists

 

       /// <summary>
        /// Whether the service is installed/existence
        /// </summary>
        /// <param name="serviceName">service name</param>
        /// <returns></returns>
        public static bool IsServiceInstalled(string serviceName)
        {
            bool exists = false;
            System.ServiceProcess.ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
            foreach (System.ServiceProcess.ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    exists = true;
                    break;
                }
            }
            return exists;
        }

 

How to get service status

        /// <summary>
        /// Get service status
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static String GetServiceStatus(string serviceName)
        {
            string result = "Service does not exist";
            System.ServiceProcess.ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
            foreach (System.ServiceProcess.ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    result = s.Status.ToString();
                    break;
                }
            }
            return result;
        }

 

Note:

The service status return value is an enumeration type. The specific return value is as follows

 

   // abstract: 
    //     Indicates the current state of the service.
    public enum ServiceControllerStatus
    {
        // abstract: 
        //     Service is not running. This corresponds to Win32 SERVICE_STOPPED Constant, defined as 0 x00000001. 
        Stopped = 1,
        //
        // abstract: 
        //     The service is starting. This corresponds to Win32 SERVICE_START_PENDING Constant, defined as 0 x00000002. 
        StartPending = 2,
        //
        // abstract: 
        //     The service is stopping. This corresponds to Win32 SERVICE_STOP_PENDING Constant, defined as 0 x00000003. 
        StopPending = 3,
        //
        // abstract: 
        //     The service is running. This corresponds to Win32 SERVICE_RUNNING Constant, defined as 0 x00000004. 
        Running = 4,
        //
        // abstract: 
        //     The service is about to continue. This corresponds to Win32 SERVICE_CONTINUE_PENDING Constant, defined as 0 x00000005. 
        ContinuePending = 5,
        //
        // abstract: 
        //     The service is about to be suspended. This corresponds to Win32 SERVICE_PAUSE_PENDING Constant, defined as 0 x00000006. 
        PausePending = 6,
        //
        // abstract: 
        //     Service paused. This corresponds to Win32 SERVICE_PAUSED Constant, defined as 0 x00000007. 
        Paused = 7,
    }

 

How to start a service

 

       /// <summary>
        /// Startup service
        /// </summary>
        /// <param name="serivceExeFullPath">Full service path</param>
        /// <param name="serviceName">service name</param>
        /// <returns></returns>
        public static bool ServiceStart(string serivceExeFullPath ,string serviceName)
        {
            if (!IsServiceInstalled(serviceName))
            {
                MessageBox.Show("Service is not installed, please install first!");
                return false;
            }
            try
            {
                using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.FileName = serivceExeFullPath;
                    p.StartInfo.Arguments = "start";
                    p.Start();
                    p.Close();
                }
                System.Threading.Thread.Sleep(2000);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Service installation exception:" + ex.Message);
                return false;
            }
        }

 

Method to stop service

        /// <summary>
        ///  Out of Service
        /// </summary>
        /// <param name="serivceExeFullPath">Full service path</param>
        /// <param name="serviceName">service name</param>
        /// <returns></returns>
        public static bool ServiceStop(string serivceExeFullPath, string serviceName)
        {
            if (!IsServiceInstalled(serviceName))
            {
                MessageBox.Show("Service is not installed, please install first!");
                return false;
            }
            try
            {
                using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                {
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.FileName = serivceExeFullPath;
                    p.StartInfo.Arguments = "stop";
                    p.Start();
                    p.WaitForExit();
                    p.Close();
                }
                System.Threading.Thread.Sleep(2000);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Service stop exception:" + ex.Message);
                return false;
            }
        }

 

Restart service example

In the click event of the button to restart the service

 

     //Check whether the service is installed
            bool isInstalled = WinServiceHelper.IsServiceInstalled(Global.BTS_DATA_SERVICE_NAME);
            if (!isInstalled)
            {
                MessageBox.Show("Restart failure,service"+Global.BTS_DATA_SERVICE_NAME+"Not installed or started");
                return;
            }
            string serviceStatus = WinServiceHelper.GetServiceStatus(Global.BTS_DATA_SERVICE_NAME);
            if (!serviceStatus.Equals(System.ServiceProcess.ServiceControllerStatus.Running.ToString()))
            {
                MessageBox.Show("Restart failure,service" + Global.BTS_DATA_SERVICE_NAME + "Status as:" + serviceStatus);
                return;
            }
            string serivceExeFullPath = Global.AppConfig.BtsDataServiceExe;
            string serviceName = Global.BTS_DATA_SERVICE_NAME;
            bool isStopSuccess = WinServiceHelper.ServiceStop(serivceExeFullPath,serviceName);
            //Stop failure
            if (!isStopSuccess)
            {
                MessageBox.Show("Restart failure,service" + Global.BTS_DATA_SERVICE_NAME + "Stop failure");
                return;
            }
            //Method has been dormant for 2 seconds
            bool isStartSuccess = WinServiceHelper.ServiceStart(serivceExeFullPath, serviceName);
            //Startup failure
            if (!isStartSuccess)
            {
                MessageBox.Show("Restart failure,service" + Global.BTS_DATA_SERVICE_NAME + "Startup failure");
                return;
            }
            MessageBox.Show("service" + Global.BTS_DATA_SERVICE_NAME + "Restart successfully");

Posted by marksie1988 on Tue, 07 Jan 2020 06:13:28 -0800