(C#) Windows Service,及一个helper类。

(C#) Windows Service - Basic

Using Microsoft Visual Studio or the Microsoft .NET Framework SDK, you can easily create services by creating an application that is installed as a service. This type of application is called a Windows Service. With framework features, you can create services, install them, and start, stop, and otherwise control their behavior.

1. Windows Service Applications

A service can exist in one of three basic states:

- Running
- Paused
- Stopped

The Service can alos reprot the state of a pending command:

- ContinuePending,
- PausePending
- StartPending
- StopPending


These statusesndeicate that a command has been issued , such as a command to pause a running service , but has not been carried out yet.
You can query the Stauts to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

Type of Services

- Win32OwnProcess
- Win32ShareProcess

2. Create Windows Services

如何创建Windows服务

 

3. 调试Windows Services.

MSDN上面已经将的很详细了,这里简单归纳如下:

1) 添加Installer :  即在Service项目上View Designer,然后在Designer上面的空白区域右击后选择 Add Installer

2) 配置ServiceInstall1 的属性:ServiceName (注意:必须和我们创建的服务的属性中的ServiceName完全一样)

3) 安装服务:Build Solution后,在生成的MyProject.exe目录下面,运行 InstallUtil.exe MyProject.exe 

4) 启动服务,挂起调试: 选择Debug->Attach to Process 后,进行调试。

参考: http://msdn.microsoft.com/zh-cn/library/9k985bc9(v=vs.90).aspx

 

4.记录使用一个Service helper类来完成 Windows Service的安装和启动。

1). 在WPF的button clieck方法中,安装一个Service

        private void btnRemove_Click(object sender, RoutedEventArgs e)

        {

            this.tbkMessage.Text = "Usb registry service is installing..."; 

            ServiceHelper.StartService();

            this.tbkMessage.Text = "Usb registry service is installed and starting..."; 

        }

2)serviceHelper类.



namespace UsbRegistryCleanUp { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; using System.ServiceProcess; using System.Configuration.Install; public static class ServiceHelper { private const string SERVICE_NAME = "UsbRegistryCleaner"; private const string SERVICE_FILE_NAME = "UsbRegistryCleaner.exe"; private const string APPLICATION_TITLE = "Usb register cleaner"; private const string SERVICE_FILE_NOT_EXIST = "Service file does not exist."; private const string INSTALL_SERVICE_ERROR = "Error found durring service installatin."; private const string UNINSTALL_SERVICE_ERROR = "Error found during service uninstallation."; /// <summary>

        /// Get the path of the service file. /// </summary>

        /// <returns></returns>

        private static string GetServiceFilePath() { return Path.Combine(Application.StartupPath, SERVICE_FILE_NAME); } /// <summary>

        /// Check whether the service file exists or not. /// </summary>

        /// <returns></returns>

        private static bool IsServiceFileExists() { return File.Exists(GetServiceFilePath()); } /// <summary>

        /// Display the error message. /// </summary>

        /// <param name="errMsg"></param>

        private static void OOPS(string errMsg) { MessageBox.Show(errMsg, APPLICATION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } /// <summary>

        /// Start service. /// </summary>

        public static bool StartService() { if (!IsWindowsServiceInstalled(SERVICE_NAME)) { if (InstallService() == false) return false; } ServiceController sc = new ServiceController(SERVICE_NAME); if (sc.Status != ServiceControllerStatus.Running) sc.Start(); return true; } /// <summary>

        /// Stop service. /// </summary>

        private static void StopService() { if (!IsWindowsServiceInstalled(SERVICE_NAME)) { if (InstallService() == false) return; } ServiceController sc = new ServiceController(SERVICE_NAME); if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop(); } /// <summary>

        /// Check whether the service has been installed or not. /// </summary>

        /// <param name="serviceName"></param>

        /// <returns></returns>

        private static bool IsWindowsServiceInstalled(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (string.Equals(service.ServiceName, serviceName, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; } /// <summary>

        /// Install service. /// </summary>

        /// <returns></returns>

        private static bool InstallService() { if (!IsServiceFileExists()) { OOPS(SERVICE_FILE_NOT_EXIST); return false; } try { string[] cmdline = {}; TransactedInstaller transactedInstaller = new TransactedInstaller(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(GetServiceFilePath(), cmdline); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Install(new System.Collections.Hashtable()); } catch (Exception ex) { OOPS(INSTALL_SERVICE_ERROR + ex.Message); return false; } return true; } /// <summary>

        /// Uninstall the service. /// </summary>

        /// <returns></returns>

        public static bool UninstallService() { if (!IsWindowsServiceInstalled(SERVICE_NAME)) return true; StopService(); if (!IsServiceFileExists()) { OOPS(SERVICE_FILE_NOT_EXIST); return false; } try { string[] cmdline = {}; TransactedInstaller transactedInstaller = new TransactedInstaller(); AssemblyInstaller assemblyInstaller = new AssemblyInstaller(GetServiceFilePath(), cmdline); transactedInstaller.Installers.Add(assemblyInstaller); transactedInstaller.Uninstall(null); } catch (Exception ex) { OOPS(UNINSTALL_SERVICE_ERROR + ex.Message); return false; } return true; } } }

 

 

你可能感兴趣的:(windows)