\\\\NT Service Control

Properties	Methods	Events
The NTService control enables an application to run as a Windows NT service.

Syntax

NTService

Remarks

The NTService control, invisible to the user, enables communications with the Windows NT services controller that is necessary for running as a service. The application can process Start  and Stop events in response to system startup or administrator actions.

The control also provides functions for installing, uninstalling, event logging, and registry management.

Because Windows NT services can run without access to the desktop, you should ensure that the application does not require user input. You should detect all error conditions by placing On Error handlers in every event procedure.


No Help Available

No help is available for this area of the window.


No Help Available

No help is available for this message box.


NT Service Control Properties

Account Property

ControlsAccepted Property

Debug Property

Dependencies Property

DisplayName Property

Interactive Property

LoadOrderGroup Property

Password Property

ServiceName Property

StartMode Property


NT Service Control Methods

DeleteSetting Method

GetAllSettings Method

GetSetting Method

Install Method

LogEvent Method

SaveSetting Method

StartService Method

StopService Method

Uninstall Method


NT Service Control Events

Continue Event

Control Event

Pause Event

Start Event

Stop Event


Account Property

See Also	Example
Returns or sets the account name which the service will be logged on when it runs.

Syntax

object.Account [= account]

The Account property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

account	a string expression specifying a domain account name

Settings

The settings for account are:

Setting	Description

(None)	(Default) "LocalSystem" account.

(Account)	Specifies a domain account  name in the form of "DomainName\Username"

Remarks

Services run in security contexts that are defined by domain accounts. If your service needs to access resources on the network or usses integrated security, you must specify an account.

Although you can set the Account property at design time, you typically would use it at run-time prior to installation. Typically, you present the user with form that lets them enter the account name and password.

If the account belongs to the built-in domain, ".\Username" can be specified. If no account is specified, the service will be logged on as the "LocalSystem" account, in which case, the Password property must be blank.

If the service has a visible interface, you must leave Account empty and set Interactive to True.

Note	Once the service is installed, this property may not reflect the actual account being used by the service if the user manually changed the startup options in the Services Control Panel.


See Also

Install Method

Interactive Property

Password Property


ControlsAccepted Property

See Also	Example
Enables the service to process additional control signals like Pause and Continue.

Syntax

object.ControlsAccepted [= controls]

The ControlsAccepted property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

controls	Numeric expression that is the sum of values specifying control events that the service can process. If ommitted, the default value for controls is 0.

Settings

The settings for controls are:

Constant	Value	Description

svcCtrlStartStop	0	Enables Start and Stop events.

svcCtrlPauseContinue	2	Enables the Pause and Continue events.

svcCtrlShutdown	4	Enables shutdown events

(User Defined)	Enables user defined events.

Note	These constants are defined in the NTService control. As a result, the names can be used in anywhere in you code in place of the actual values.

Remarks

All services must process Start and Stop events, and you cannot disable notification for them. If your service can suspend processing, you can enable Pause and Continue event notification. Events other than Start, Stop, Pause, and Continue generate the generic Control event. The Services Control Panel does not have support for user defined event nofitication.

You must set the ControlsAccepted property prior to calling StartService. After the service has started, this property has no effect.

Shutdown events occurr when the system requests the service to perform cleanup tasks, because the system is shutting down. Due to extremely limited time available for shutdown, this control should only be used by services that absolutely need to shut down. The system gives the services controller a limited amount of time (about 20 seconds) to complete service shutdown, after which time system shutdown proceeds regardless of whether service shutdown is complete.


See Also

Control Event

Pause Event

Continue Event


Debug Property

See Also	Example
Enables the service to run in the development environment or from the console.

Syntax

object.Debug [= boolean ]

The Debug property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

boolean	A Boolean expression that specifies whether object should avoid initiating communication with the services controller.

Settings

The settings for boolean are:

Setting	Description

True	Prevents object to communicate with the services controller.

False	(Default) Allows object to communicate with the services controller.

Remarks

To debug an application that uses the NTService control, you must set the Debug property to True. On start-up, a Windows NT service communicates with the services controller to report its status, but when editing, the services controller is not available.

If Debug is not set when running from the development environment, StartService will succeed, but the Start event will not fire.


See Also

Start Event

StartService Method


LoadOrderGroup Property

See Also	Example
Names the load ordering group of which the service is a member

Syntax

object.LoadOrderGroup [= group]

The LoadOrderGroup property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

group	a string expression specifying the load order group.

Settings

The settings for group are:

Setting	Description

(None)	(Default) The service does not belong to a group.

(Group)	Load ordering group of which this service is a member. The registry has a list of load ordering groups located at:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ServiceGroupOrder.

Remarks

The startup program uses this property to load groups of services in a specified order with respect to the other groups in the list. You can place a service in a group so that another service can depend on the group.

The order in which a service starts is determined by the following criteria:

1.	The order of groups in the registry's load-ordering group list. Services in groups in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list and then services that do not belong to a group.

2.	The service's dependencies listed in the Dependencies property and the dependencies of other services dependent on the service.


See Also

Dependencies Property


Dependencies Property

See Also	Example
Names services or load ordering groups that must start before this service.

Syntax

object.Dependencies [= dependencies]

The Dependencies property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

dependencies	A string expression containing names of services or load ordering groups.

Settings

The settings for dependencies are:

Setting	Description

(None)	(Default) The service does depend on any service or load order group.

(List)	Specifies the dependency list. The list must be a string expression of null-separated names of services or load ordering groups that must start before this service. The array is double null-terminated.

Remarks

The startup program uses this list to load groups of services in a specified order with respect to the other groups in the list. If your service depends on another service or group, you instruct the startup program to load those before loading your service.

The order in which a service starts is determined by the following criteria:

1.	The order of groups in the registry's load-ordering group list. Services in groups in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list and then services that do not belong to a group.

2.	The service's dependencies listed in the Dependencies property and the dependencies of other services dependent on the service.

If a group name is specified, it must be prefixed by the SC_GROUP_IDENTIFIER character ('+') to differentiate it from a service name, because services and service groups share the same name space. Dependency on a service means that this service can only run if the service it depends on is running. 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.


See Also

LoadOrderGroup Property


DisplayName Property

See Also	Example
Returns or sets the string that is to be used by user interface programs to identify the service.

Syntax

object.DisplayName [= name]

The DisplayName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

name	a string expression specifying the name to be displayed by user interface programs. This string has a maximum length of 255 characters.

Remarks

All services must include a DisplayName.

The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.


See Also

ServiceName Property

Install Method


Interactive Property

See Also	Example
Enables the service to interact with the desktop.

Syntax

object.Interactive [= boolean ]

The Interactive property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

boolean	A Boolean expression that specifies whether object is allowed to interact with the desktop.

Settings

The settings for boolean are:

Setting	Description

True	Allows the service to interact with the desktop.

False	(Default) Does not allow the service to interact with the desktop.

Remarks

Only services that in the "LocalSystem" account are allowed to interact with the desktop.

You cannot depend on the service having access to the desktop because the user can prevent it by changing the startup setting in the Services Control Panel. As a general rule, services should not depend on any user interaction. This includes handling all error conditions with On Error blocks to prevent error message boxes.


See Also

Account Property

Password Property

Install Method


Password Property

See Also	Example
Returns or sets the password for the account which the service will be logged on when it runs.

Syntax

object.Password [= password]

The Password property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

password	a string expression specifying the account password.

Settings

The settings for password are:

Setting	Description

(None)	(Default) The service has no passoword.

(Password)	A password to the account specified in the Account property.

Remarks

Although you can set the Password property at design time, you typically would use it at run-time prior to installation. Typically, you present the user with form that lets them enter the account name and password.

If the account is empty or it is set to "LocalSystem", you should leave Password empty.

Note	Once the service is installed, this property may not reflect the actual account being used by the service if the user manually changed the startup options in the Services Control Panel.


See Also

Account Property

Password Property

Install Method


ServiceName Property

See Also	Example
Returns or sets the name of the service.

Syntax

object.ServiceName [= name]

The ServiceName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

name	a string expression that names the service to install. This string has a maximum length of 255 characters. Forward-slash (/) and back-slash (\) are invalid service name characters.

Remarks

All services must include a ServiceName.

The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.


See Also

DisplayName Property

Install Method

LogEvent Method


StartMode Property

See Also	Example
Returns or sets when to start the service.

Syntax

object.StartMode [= mode]

The StartMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

mode	Numeric expression that indicates when to start the service. If ommitted, the default value for mode is 2.

Settings

The settings for mode are:

Constant	Value	Description

svcStartAutomatic	2	The service starts automatically during system startup

svcStartManual	3	The serivice can be started on demand.

svcStartDisabled	4	The service that cannot be started.

Note	These constants are defined in the NTService control. As a result, the names can be used in anywhere in you code in place of the actual values.

Remarks

Once the service has been installed, changing the StartMode property will have no effect on when the service is started.


See Also

Install Method


DeleteSetting Method

See Also	Example
Deletes a section or key setting from the Windows registry entry.

Syntax

object.DeleteSetting(section[, key])

The DeleteSetting method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

section	String expression containing the name of the section where the key setting is being deleted.  If only the section is provided, the specified section is deleted along with all related key settings.

key	String expression containing the name of the key setting being deleted.

Remarks

If all arguments are provided, the specified key setting is deleted.  However, the DeleteSetting statement does nothing if the specified section or key setting does not exist.

This method differs form the DeleteSetting statement in Visual Basic because settings are saved in the registstry under:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\ServiceName.


See Also

GetAllSettings Method

GetSetting Method

SaveSetting Method


GetAllSettings Method

See Also	Example
Returns a list of key settings and their respective values from an application's Windows registry entry.

Syntax

object.GetAllSettings(section)

The GetAllSettings method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

section	String expression containing the name of the section whose key settings are requested.  GetAllSettings returns a Variant whose contents is a two-dimensional array of strings containing all the key settings in the specified section and their corresponding values.

Remarks

GetAllSettings returns an uninitialized Variant if either appname or section do not exist.

This method differs form the GetAllSettings statement in Visual Basic because settings are saved in the registstry under:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\ServiceName.


See Also

DeleteSetting Method

GetSetting Method

SaveSetting Method


GetSetting Method

See Also	Example
Returns a key setting value from an application's Windows registry entry.

Syntax

object.GetSetting(section, key[, default])

The GetSetting method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

section	String expression containing the name of the section where the key setting is found.

key	String expression containing the name of the key setting to return.

default	Expression containing the value to return if no value is set in the key setting.  If omitted, default is assumed to be a zero-length string ("").

Remarks

If any of the items named in the GetSetting arguments do not exist, GetSetting returns the value of default.

This method differs form the GetSetting statement in Visual Basic because settings are saved in the registstry under:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\ServiceName.


See Also

DeleteSetting Method

GetAllSettings Method

SaveSetting Method


Install Method

See Also	Example
Installs a service and adds it to the services controller database

Syntax

object.Install

The Install method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

Remarks

Prior to installing the service, you should set properties that define how the service is configured. At a minimum, these are: DisplayName, ServiceName, ControlsAccepted, and StartMode.


See Also

Account Property

ControlsAccepted Property

Debug Property

Dependencies Property

DisplayName Property

Interactive Property

LoadOrderGroup Property

Password Property

ServiceName Property

StartMode Property

Uninstall Method


LogEvent Method

See Also	Example
Writes an entry at the end of the application event log.

Syntax

object.LogEvent (event, id, message)

The Install method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

event	The type of event being logged.

id	The event identifier. The identifier specifies the message asociated with the event

message	Additional message information that is written with the event.

Settings

The settings for event  are:

Constant	Value	Description

svcEventError	1	Error event.

svcEventWarning	2	Warning event.

svcEventInformation	4	Information event.

svcEventAuditSuccess	8	Audit success event.

svcEventAuditFailure	10	Audit failure event.

The settings for id are:

Constant	Value	Description

svcMessageDebug	108	Debugging message

svcMessageError	109	Error message

svcMessageInfo	110	Information message

Note	These constants are defined in the NTService control. As a result, the names can be used in anywhere in you code in place of the actual values.

Remarks

This method is used to log an event. The entry is written to the end of the application logfile with the ServiceName as the source. The LogEvent method adds the time, the user name before storing the entry in the log.


See Also

ServiceName Property


SaveSetting Method

See Also	Example
Saves or creates an application entry in the Windows registry entry.

Syntax

object.SaveSetting(section, key, setting)

The SaveSetting statement syntax has these named arguments:

Part	Description

object	An object expression that evaluates to an NTService object.

section	String expression containing the name of the section where the key setting is being saved.

key	String expression containing the name of the key setting being saved.

setting	Expression containing the value that key is being set to.

Remarks

An error occurs if the key setting could not be saved for any reason.

This method differs form the SaveSetting statement in Visual Basic because settings are saved in the registstry under:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\ServiceName.


See Also

DeleteSetting Method

GetAllSettings Method

GetSetting Method


StartService Method

See Also	Example
Connects the service to the services controller.

Syntax

object.StartService

The StartService method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

Remarks

When the services controller starts a service process, it waits for the process to connect back to it.The service control manager uses this connection to send control and service Start requests to the the service process.

When running in the development environment or from the console, the services controller will not be available. In those situations, you must set the Debug property to enable firing of the Start event


See Also

ControlsAccepted Property

Debug Property

StopService Method

Pause Event

Start Event


StopService Method

See Also	Example
Stops a running service and notifies the services controller.

Syntax

object.StopService

The StopService method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

Remarks

To programatically stop a service, you can call the StopService method. The user can also stop the service manually with the Services Control Panel. In that case, you do not need to call this method.


See Also

ControlsAccepted Property

StartService Method

Stop Event


Uninstall Method

See Also	Example
Uninstalls a service and removes it from the services controller database

Syntax

object.Uninstall

The Uninstall method syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

Remarks

The database entry is not removed until the service is not running. A running service is stopped with the stop control code. If the service cannot be stopped, the database entry is removed when the system is restarted.

The service controller deletes the service by deleting the service key and its subkeys from the registry.


See Also

Install Method


Continue Event

See Also	Example
Occurs when the services controller notifies the service that the user or another program has requested the service to continue processing.

Syntax

Private Sub object_Continue(success as Boolean)

The Continue event syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

success	A boolean. Setting this argument to any value other than 0 informs the services controller that the event was handled successfully.

Remarks

Use this event procedure to resume processing by your service. To enable receiving Continue events, the ControlsAccepted property must include svcCtrlPauseContinue as one of the composite values.


See Also

ControlsAccepted Property

Continue Event

Pause Event

Start Event

Stop Event


Control Event

See Also	Example
Occurs when the services controller notifies the service of shutdown or user defined events.

Syntax

Private Sub object_Control(event as Long)

The Control event syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

event	A long integer. This parameter specifies the event that occurred.

Remarks

Use this event procedure to recive user defined event notifications. To enable receiving Control events, the ControlsAccepted property must include a value that corresponds to event as one of the composite values.

Other than svcCtrlShutdown, there is support for generating the events in the Services Control Panel or in the NTService control. Signaling these events would have to be peformed by a custom program.


See Also

ControlsAccepted Property

Continue Event

Control Event

Pause Event

Start Event

Stop Event


Pause Event

See Also	Example
Occurs when the services controller notifies the service that the user or another program has requested the service to suspend processing.

Syntax

Private Sub object_Pause(success as Boolean)

The Pause event syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

success	A boolean. Setting this argument to any value other than 0 informs the services controller that the event was handled successfully.

Remarks

Use this event procedure to suspend processing by your service. To enable receiving Pause events, the ControlsAccepted property must include svcCtrlPauseContinue as one of the composite values.


See Also

ControlsAccepted Property

Continue Event

Start Event

Stop Event


Start Event

See Also	Example
Occurs when the services controller notifies the service that the user or another program has requested the service to start.

Syntax

Private Sub object_Start(success as Boolean)

The Start event syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

success	A boolean. Setting this argument to any value other than 0 informs the services controller that the event was handled successfully.

Remarks

Use this event procedure to initiate processing by your service. If your service was able to perform its intialization operation, you must set the success parameter to True. Otherwise, the services controller will report an error.


See Also

ControlsAccepted Property

Debug Property

StartService Method

Stop Event


Stop Event

See Also	Example
Occurs when the services controller notifies the service that the user or another program has requested the service to stop.

Syntax

Private Sub object_Stop()

The Stop event syntax has these parts:

Part	Description

object	An object expression that evaluates to an NTService object.

Remarks

Use this event procedure to close your service.


See Also

ControlsAccepted Property

StopService Method

Start Event


StartService Example

This example starts the service and shows trivial start and stop event handlers.

Private Sub Form_Load()

    Dim bStarted As Boolean

    If Command = "-install" Then

        If NTService1.Install Then

            ' Save default service settings in registry

            NTService1.SaveSetting "Parameters", "Interval", "1000"

            MsgBox NTService1.DisplayName & " installed successfully"

        Else

            MsgBox NTService1.DisplayName & " failed to install"

        End If

        End

    ElseIf Command = "-uninstall" Then

        If NTService1.Uninstall Then

            MsgBox NTService1.DisplayName & " uninstalled successfully"

        Else

            MsgBox NTService1.DisplayName & " failed to uninstall"

        End If

        End

    ElseIf Command = "-debug" Then

        NTService1.Debug = True

    ElseIf Command <> "" Then

        MsgBox "Invalid command option"

        End

    End If

    ' Get service settings from registry

    Timer.Interval = CInt(NTService1.GetSetting("Parameters", _

        "Interval", "2000"))

    NTService1.StartService

End Sub

Private Sub NTService1_Start(Success As Boolean)

    Success = True

End Sub

Private Sub NTService1_Stop()

    Unload Me

End Sub


Installation Example

This example installs a service that starts automatically and supports of Pause and Continue events

Private Function InstallService() as Boolean

    NTService1.ServiceName = "MyService"

    NTService1.DisplayName = "My Service"

    NTService1.StartMode = 2          'svcStartAutomatic

    NTService1.ControlsAccepted = 2   'svcCtrlPauseContinue

    If NTService1.Install Then

        ' Save default service settings in registry

        NTService1.SaveSetting "Parameters", "Interval", "1000"

        InstallService = True

    Else

        InstallService = False

    End If

End Function

Private Sub NTService1_Continue(Success As Boolean)

    Timer.Enabled = True

    Success = True

End Sub

Private Sub NTService1_Pause(Success As Boolean)

    Timer.Enabled = False

    Success = True

End Sub


Account Example

This example installs a service to log on as an account or interactively.

Private Function InstallService(Interactive as Boolean) as Boolean

    Dim sAccount as String

    Dim sPassword as String

    If Interactive Then

        ' Prompt user for account and password

        Call GetAccountAndPassword (sAccount, sPassword)

        NTService1.Account = sAccount

        NTService1.Password = sPassword

        NTService1.Interactive = False

    Else

        NTService1.Interactive = True

    End If

    If NTService1.Install Then

        InstallService = True

    Else

        InstallService = False

    End If

End Function


Dependencies Example

This example installs a service with dependencies.

Private Function InstallService() as Boolean

    Dim sDepend as String

    sDepend = "OLE" + Chr(0)                    'depends on OLE

    sDepend = sDepend + "MSSQLServer" + Chr(0)  'depends on SQL

    sDepend = sDepend + Chr(0)                  'terminates list

    NTService1.LoadOrderGroup = ""   'does not belong to a group

    NTService1.Dependencies = sDepend

    If NTService1.Install Then

        InstallService = True

    Else

        InstallService = False

    End If

End Function


Settings Example

This example saves and gets registry settings.

' Variant to hold 2-dimensional array returned by GetAllSettings.

Dim Folders As Variant

' Place some settings in the registry.

NTService1.SaveSetting("Parameters", "TimerInterval", 1000)

NTService1.SaveSetting("Parameters\Folders", "hr", 50)

NTService1.SaveSetting("Parameters\Folders", "finance", 45)

NTService1.SaveSetting("Parameters\Folders", "is", 60)

Debug.Print NTService1.GetSetting("Parameters", _

                "TimerInterval", "2000")

Folders = NTService1.GetAllSettings("Parameters\Foldes")

NTService1.DeleteSetting("Parameters")


Stop Service Example

This example stops the service on a fatal error and logs the error to the event log.

Private Sub NTService1_Continue(Success As Boolean)

On Error Goto Err_Continue

   'Continue the service

   ...

Err_Continue:

    Success = False

    NTService1.LogEvent(svcEventError, svcMessageError, _

       "A fatal error occurred")

    NTService1.StopService

End Sub