- Develop Windows service apps
- In this section
- Related sections
- Практическое руководство. Создание службы программным способом How to: Write Services Programmatically
- Создание службы программным способом To write a service programmatically
- CreateServiceA function (winsvc.h)
- Syntax
- Parameters
- Return value
- Remarks
Develop Windows service apps
Using Visual Studio or the .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.
In Visual Studio you can create a service in managed code in Visual C# or Visual Basic, which can interoperate with existing C++ code if required. Or, you can create a Windows service in native C++ by using the ATL Project Wizard.
In this section
Provides an overview of Windows service applications, the lifetime of a service, and how service applications differ from other common project types.
Provides an example of creating a service in Visual Basic and Visual C#.
Explains the language elements used in service programming.
Describes the process of creating and configuring Windows services using the Windows service project template.
Related sections
ServiceBase — Describes the major features of the ServiceBase class, which is used to create services.
ServiceProcessInstaller — Describes the features of the ServiceProcessInstaller class, which is used along with the ServiceInstaller class to install and uninstall your services.
ServiceInstaller — Describes the features of the ServiceInstaller class, which is used along with the ServiceProcessInstaller class to install and uninstall your service.
Create Projects from Templates — Describes the projects types used in this chapter and how to choose between them.
Практическое руководство. Создание службы программным способом How to: Write Services Programmatically
Если вы решили не использовать шаблон проекта «Служба Windows», для создания собственной службы вам придется настроить наследование и другие элементы инфраструктуры самостоятельно. If you choose not to use the Windows Service project template, you can write your own services by setting up the inheritance and other infrastructure elements yourself. Создавая службу программным способом, вам необходимо выполнить несколько действий, которые в случае с шаблоном выполняются автоматически. When you create a service programmatically, you must perform several steps that the template would otherwise handle for you:
Для класса службы необходимо настроить наследование от класса ServiceBase. You must set up your service class to inherit from the ServiceBase class.
Для проекта службы необходимо создать метод Main , который определяет запускаемые службы и вызывает для них метод Run. You must create a Main method for your service project that defines the services to run and calls the Run method on them.
Необходимо переопределить процедуры OnStart и OnStop и добавить код, который они должны выполнять. You must override the OnStart and OnStop procedures and fill in any code you want them to run.
Создание службы программным способом To write a service programmatically
Создайте пустой проект, а затем создайте ссылку на необходимые пространства имен. Create an empty project and create a reference to the necessary namespaces by following these steps:
В окне Обозреватель решений щелкните правой кнопкой мыши узел Ссылки и выберите пункт Добавить ссылку. In Solution Explorer, right-click the References node and click Add Reference.
На вкладке .NET Framework найдите System.dll и щелкните Выбрать. On the .NET Framework tab, scroll to System.dll and click Select.
Найдите System.ServiceProcess.dll и щелкните Выбрать. Scroll to System.ServiceProcess.dll and click Select.
Нажмите кнопку ОК. Click OK.
Добавьте класс и настройте для него наследование от ServiceBase. Add a class and configure it to inherit from ServiceBase:
Настройте класс службы, добавив следующий код: Add the following code to configure your service class:
Создайте для класса метод Main и с его помощью определите службы, которые будет содержать класс. userService1 — имя класса. Create a Main method for your class, and use it to define the service your class will contain; userService1 is the name of the class:
Переопределите метод OnStart и укажите обработку, которая должна выполняться при запуске службы. Override the OnStart method, and define any processing you want to occur when your service is started.
Переопределите все прочие методы, для которых нужно задать определенную обработку, и напишите код, благодаря которому служба будет понимать, что нужно делать в каждом случае. Override any other methods you want to define custom processing for, and write code to determine the actions the service should take in each case.
Добавить установщики, необходимые для приложения службы. Add the necessary installers for your service application. Дополнительные сведения см. в разделе Практическое руководство. Добавление установщиков в приложение-службу. For more information, see How to: Add Installers to Your Service Application.
Скомпилируйте проект, выбрав в меню Сборка пункт Собрать решение. Build your project by selecting Build Solution from the Build menu.
Не нажимайте клавишу F5 для запуска проекта — таким способом нельзя запустить проект службы. Do not press F5 to run your project — you cannot run a service project in this way.
Создайте проект установки и настраиваемые действия для установки службы. Create a setup project and the custom actions to install your service. Пример см. в разделе Пошаговое руководство. Создание приложения служб Windows в конструкторе компонентов. For an example, see Walkthrough: Creating a Windows Service Application in the Component Designer.
Установите службу. Install the service. Дополнительные сведения см. в разделе Практическое руководство. Установка и удаление служб. For more information, see How to: Install and Uninstall Services.
CreateServiceA function (winsvc.h)
Creates a service object and adds it to the specified service control manager database.
Syntax
Parameters
A handle to the service control manager database. This handle is returned by the OpenSCManager function and must have the SC_MANAGER_CREATE_SERVICE access right. For more information, see Service Security and Access Rights.
The name of the service to install. The maximum string length is 256 characters. The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive. Forward-slash (/) and backslash (\) are not valid service name characters.
The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.
The access to the service. Before granting the requested access, the system checks the access token of the calling process. For a list of values, see Service Security and Access Rights.
The service type. This parameter can be one of the following values.
Value | Meaning |
---|---|
SERVICE_ADAPTER 0x00000004 | Reserved. |
SERVICE_FILE_SYSTEM_DRIVER 0x00000002 | File system driver service. |
SERVICE_KERNEL_DRIVER 0x00000001 | Driver service. |
SERVICE_RECOGNIZER_DRIVER 0x00000008 | Reserved. |
SERVICE_WIN32_OWN_PROCESS 0x00000010 | Service that runs in its own process. |
SERVICE_WIN32_SHARE_PROCESS 0x00000020 | Service that shares a process with one or more other services. For more information, see Service Programs. |
SERVICE_USER_OWN_PROCESS 0x00000050 | The service runs in its own process under the logged-on user account. |
SERVICE_USER_SHARE_PROCESS 0x00000060 | The service shares a process with one or more other services that run under the logged-on user account. |
В
If you specify either SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS, and the service is running in the context of the LocalSystem account, you can also specify the following value.
Value | Meaning | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SERVICE_INTERACTIVE_PROCESS 0x00000100 | The service can interact with the desktop. The service start options. This parameter can be one of the following values.
The severity of the error, and action taken, if this service fails to start. This parameter can be one of the following values.
The fully qualified path to the service binary file. If the path contains a space, it must be quoted so that it is correctly interpreted. For example, «d:\my share\myservice.exe» should be specified as «»d:\my share\myservice.exe»». The path can also include arguments for an auto-start service. For example, «d:\myshare\myservice.exe arg1 arg2». These arguments are passed to the service entry point (typically the main function). If you specify a path on another computer, the share must be accessible by the computer account of the local computer because this is the security context used in the remote call. However, this requirement allows any potential vulnerabilities in the remote computer to affect the local computer. Therefore, it is best to use a local file. The names of the load ordering group of which this service is a member. Specify NULL or an empty string if the service does not belong to a group. The startup program uses load ordering groups to load groups of services in a specified order with respect to the other groups. The list of load ordering groups is contained in the following registry value: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ServiceGroupOrder A pointer to a variable that receives a tag value that is unique in the group specified in the lpLoadOrderGroup parameter. Specify NULL if you are not changing the existing tag. You can use a tag for ordering service startup within a load ordering group by specifying a tag order vector in the following registry value:HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\GroupOrderList Tags are only evaluated for driver services that have SERVICE_BOOT_START or SERVICE_SYSTEM_START start types. A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify NULL or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. You must prefix group names with SC_GROUP_IDENTIFIER so that they can be distinguished from a service name, because services and service groups share the same name space. The name of the account under which the service should run. If the service type is SERVICE_WIN32_OWN_PROCESS, use an account name in the form DomainName\UserName. The service process will be logged on as this user. If the account belongs to the built-in domain, you can specify .\UserName. If this parameter is NULL, CreateService uses the LocalSystem account. If the service type specifies SERVICE_INTERACTIVE_PROCESS, the service must run in the LocalSystem account. If this parameter is NT AUTHORITY\LocalService, CreateService uses the LocalService account. If the parameter is NT AUTHORITY\NetworkService, CreateService uses the NetworkService account. A shared process can run as any user. If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, the name is the driver object name that the system uses to load the device driver. Specify NULL if the driver is to use a default object name created by the I/O system. A service can be configured to use a managed account or a virtual account. If the service is configured to use a managed service account, the name is the managed service account name. If the service is configured to use a virtual account, specify the name as NT SERVICE\ServiceName. For more information about managed service accounts and virtual accounts, see the Service Accounts Step-by-Step Guide. Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В Managed service accounts and virtual accounts are not supported until WindowsВ 7 and Windows ServerВ 2008В R2. The password to the account name specified by the lpServiceStartName parameter. Specify an empty string if the account has no password or if the service runs in the LocalService, NetworkService, or LocalSystem account. For more information, see Service Record List. If the account name specified by the lpServiceStartName parameter is the name of a managed service account or virtual account name, the lpPassword parameter must be NULL. Passwords are ignored for driver services. Return valueIf the function succeeds, the return value is a handle to the service. If the function fails, the return value is NULL. To get extended error information, call GetLastError. The following error codes can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.
RemarksThe CreateService function creates a service object and installs it in the service control manager database by creating a key with the same name as the service under the following registry key:HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services Information specified by CreateService, ChangeServiceConfig, and ChangeServiceConfig2 is saved as values under this key. The following are examples of values stored for a service.
В Setup programs and the service itself can create additional subkeys for service-specific information. The returned handle is only valid for the process that called CreateService. It can be closed by calling the CloseServiceHandle function. If you are creating services that share a process, avoid calling functions with process-wide effects, such as ExitProcess. In addition, do not unload your service DLL. |