How to use VB to write NT service program

Source: Internet
Author: User
Tags chr goto implement win32
Program one, NT service program
The so-called NT service, in fact, is a process that can be automatically activated in a certain capacity at the time of system startup. such as FTP server, HTTP server, offline printing, etc. are provided in the form of NT services. This is actually similar to the UNIX root daemon process. NT Services summed up, NT services and the following features:
1, can start, do not need interactive start. This is an important feature for the server. Of course, you can decide whether the service will start or even block a service.
2, NT services do not have a user interface, basically similar to a DOS program, because the NT service must run for a long time, so do not want ordinary Win32 process has its own interface. However, NT service can interact with user interface, which is a special kind of service process. You can see the service process through the NT Task Manager.
3. NT services are managed through SCM (Services control Manager) interfaces, installation, start-up, stop, and removal require SCM interface functions. The Control Panel's service controller uses the SCM interface to manage all the services in the system. In fact, there are some programs or commands that can control the service, such as Net.exe, Server Manager, SCM.exe, etc.
4, these processes are running in a certain capacity to facilitate access to server resources. In general, use the LocalSystem account in the domain to run, this account for most of the resources on this computer (unless specifically prohibited) have full access rights, so as to ensure that the service program "strong." However, some services use a special account to run, you can also specifically set a service account.
5, the system automatically run by the thread, under normal circumstances but more occupy the system resources, this is different from the ordinary process, if not using threading, the general process often consumes the entire CPU resources. Generally need to be present, but not too much resources to consume the task of service to achieve the most appropriate.


Second, the service control
It is generally believed that writing NT services needs to be implemented using C + +, and VC6 uses the ATL wizards to provide a basic service framework. The implementation steps are: Fileànew...àatl COM appwizardàserviceàfinish. But using VC to write NT services requires too much coding, which means that too much debugging and maintenance is required. In fact, NT services do not have to be written by C/n + +, and can actually be implemented by any language that can implement several of the features of the previous section, including VB.
VB writing services have those benefits, at least can list the following:
1, coding simple, familiar with VB Grammar anyone understand this article can be written.
2, means that the modification of the service implementation of the logic is simple, simple maintenance.
3, you can use almost most of the components in VB function, write a strong service, such as ADO, if the VC to achieve, I believe anyone will be afraid.
4, (far-fetched point) can prove that VB under Bill's sky is how powerful.
So, how does VB implement NT service writing? As far as I can get, there are at least two ways:
1. Use WINAPI to realize the idea according to C + +.
2, the use of components in accordance with the traditional VB way to achieve.
If the use of Method 1 is actually a copy of C + +, if there is a better way to achieve, I believe that no one will go this "blind alley", because in contrast to other languages, this programming completely lost the characteristics of VB itself without acquiring any advantages of other languages. Here, want to tell everyone is to use OCX to achieve a service. If you search for samples\msdn\techart\4920\ in MSDN, you can see a VC5 engineering file that has been written. Compiling this project will actually get a ntsvc.ocx. If you are not familiar with C + +, you can download a ntsvc.ocx from Http://www.mywebtech.net/download/ntsvc.zip, which I obtained from the BackOffice disc and copy it to \winnt\ System32\, use the regsvr32 ntsvc.ocx command to register. In this way, your VB can be from the project\components ... The list of dialog boxes that is called "Microsoft NT Service Control" is shown in the. This component has the basic function of creating a service, if we want to write an NT service, we drag it into our form, then set its properties, call its function to interact with system, registry, SCM to accomplish a service.
We first look at the attributes of this component and explain the use of these properties to you:
Account String, id attribute, that is, this NT service in which NT domain account run, the default is LocalSystem account, in fact, most of the NT services can be in this account under the security of a successful operation.
controlsaccepted Long, this service accepts those SCM controls for the following values:
0 allows start and Stop.
2 Allow pause and Continue.
4 Allow shutdown.
Other values, some events that are customized by the user.
With this property, you can decide for yourself whether the NT service process (for example, an interruptible operation) allows SCM to stop, pause, start, and so on.
Dependencies String, you must specify a list of dependent services when registering the service if you are writing a service that depends on some or some services to function correctly. Dependencies chr (0) to separate multiple services in a dependency order and must end with two Chr (0). (You can see that this is a C + + presence traces)
DisplayName String, the display name, and what name the NT service is displayed to the observer.
Interactive Boolean, whether to allow the part that has interaction with the desktop user.
Loadordergroup String, related to dependencies, determines that the service must be started, the format is similar, and the Chr (0) is split and two consecutive Chr (0) ends if the service is started.
Password String, service startup password, if the default account is used, there is no need to set the service startup account.
ServiceName string, service name, if you use Net.exe to control the service, Net.exe specifies that the parameter of the service is a string in this property.
StartMode enum type, specifically:
Vcstartautomatic 2 service can be started on its own
Svcstartmanual 3 Service starts manually
Svcstartdisabled 4 service does not start from
There is also a debug attribute that is not discussed.
We want to use a VB program as an NT service, must make some "application" to the system, and the corresponding work VB is not very good to complete. Therefore, Ntsvc.ocx provides the corresponding method to stay as we want the system to pass relevant information.
Install, install the current VB program into NT service, before this, you must set up at least DisplayName, ServiceName, controlsaccepted and StartMode properties. In addition, you may also have to set account, Password, Loadordergroup, dependencies, and so on. Whether this information is set up correctly or not, determines if your service program starts and runs normally.
Uninstall, deletes the service specified by the current Ntsvc.ocx from the system registry. The NT service depends on the setup of the system service registry, which is a well-known secret.
StartService, start the specified service if the service is registered.
StopService, stop the service if the service is running.
LogEvent, log service events. In a service run, there may be errors and unexpected events, which can be recorded in this way for the administrator to view the relevant information through the Event Viewer to optimize the service. This method has three parameter event, ID, message. Event refers to the types of events that occur and can be set to the following values:
Svceventerror 1 Error events
Svceventwarning 2 Warning events.
Svceventinformation 4 provides reference information.
Svceventauditsuccess 8 Audit success.
Svceventauditfailure 10 Audit Failure
In addition to the above methods, you may also need to read and write the registry, which also provides access to the registry:
DeleteSetting (section[, key])
GetAllSettings (section)
GetSetting (section, key[, default])
SaveSetting (section, key, setting).



III. Preparation of services
To understand the above, we begin to design a service, through examples, let you understand how to write a service in VB.
Before that, we decided to write a kind of service. I refer to an example in C++build to write a service process that keeps alerting. The process starts 5 seconds in the background after the beep call, which makes you more aware of the existence of this service, although some annoying. The name of the service is VBBEEPSVC and is displayed as the VB NT SVC View in the SCM.
Come along with me!
1, create the project, set related to the use of control.
All VB controls must have a form as a carrier, so first we create a standard project, select Menu Project->components ..., and then choose (Microsoft NT Service control), The NT service control will appear in the toolbar. Drag a Timer control onto the form. and save it for a second. Basically, the creation process is complete.
2, set control properties.
Select the Ntsvc.ocx instance and set it in the property bar: Displayname:the VB NT SVC view,servicename:vbbeepsvc,startmode:3 (start the service manually). The rest is by default.
Since we wanted to beep every 5 seconds, we had to rely on a timer mechanism, so we set the timer's interval to 5000 milliseconds.
The above set of attributes depends on your needs, I just say it's enough in my vbbeepsvc.
3, write code to achieve service logic and service installation, removal.
Because the service program is actually an EXE file, and you need to solve the installation, removal problems, so you need to add the use of NT service controls to implement installation, removal problems. So, when should it be done? When the VB program is started when the form is loaded, we need to add some code to the form's Load event:
On Error GoTo Err_load ' If there is an error on the record for reference
Dim Strdisplayname as String
Strdisplayname = Ntservice1.displayname
If Command = "-install" Then ' when a parameter with –install is on at startup
Ntservice1.interactive = True
If Ntservice1.install Then
Call Ntservice1.savesetting ("Parameters", "TimerInterval", "1000") ' System parameter storage
MsgBox Strdisplayname & "Installation successful!" "
Else
MsgBox Strdisplayname & "Installation Failed"
End If
End ' Terminate installation
Else
If Command = "-uninstall" Then if a removal parameter is taken on startup
If Ntservice1.uninstall Then
MsgBox Strdisplayname & "removal Success"
Else
MsgBox Strdisplayname & "Removal failed"
End If
End ' terminate the removal
Else
End If
End If
' If it is not an installation or removal operation, it starts the service
Timer1.interval = CInt (ntservice1.getsetting ("Parameters", "TimerInterval", "2000"))
' Use the Timer control to simulate the threading characteristics of the service
ntservice1.controlsaccepted = Svcctrlpausecontinue ' Accept pause, stop operation, meaning need to encode for this
Ntservice1.startservice ' Set the parameters and start the service.
Err_load:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.Description) ' Svcmessa Geerror the error value for the NT service control
4, add the code to control the service.
Although features such as continuous threading of services are dependent on timer implementations, but the service control is the SCM interface to each service issued, performance in the VB Service program for the NT Service control to capture the relevant events, we should be in these events in accordance with the specific circumstances of the response, decide whether, How to control the service logic. Of course, the specific logic behaves in the timer event, but by changing the global variables supported by the NT Service control and the timer control, the logic implementation of the control service can be realized. Specific Code Demo:
Private Sub Ntservice1_control (ByVal EventID as Long)
On Error GoTo Err_control
' Add some of your own processing logic here, and of course it can be as vacant as this example
Err_control:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.descriptio N) ' record
End Sub
Private Sub Ntservice1_pause (Success as Boolean)
On Error GoTo Err_pause
timer1.enabled = False ' Disables the timer event, so it also stops the occurrence of the service
Call Ntservice1.logevent (Svceventerror, Svcmessageerror, "Service paused")
Success = True ' returns to the SCM command, indicating that the service was successfully stopped
Err_pause:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.Description)
End Sub
Private Sub Ntservice1_start (Success as Boolean)
On Error GoTo Err_start
Success = True
timer1.enabled = True ' allows service logic to be performed
Err_start:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.Description)
End Sub
Private Sub Ntservice1_stop ()
On Error GoTo Err_stop
Unload Me ' removal form, natural timer does not exist, service logic stopped
Err_stop:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.Description)
End Sub
5, write the service logic.
Specifically in the Timer event, according to the agreement to write a number of service details. In this case, the been is emitted but, given the response to the SCM command, it needs to be encoded as:
On Error GoTo Err_timer
Beep ' Here is the specific service details
Err_timer:
Call Ntservice1.logevent (Svcmessageerror, Svceventerror, "[" & Err.Number & "]" & Err.Description)
End Sub
6, compile installation, test
If there is nothing wrong with the above, you can now compile the program. Suppose we get the service program file name: VBBeepSVC.exe, we need to install the following command:
D:\vbprog\>vbbeepsvc–install
If you need to remove a service that is already installed:
D:\vbprog\>vbbeepsvc–uninstall
When you are finished installing, open the Services in Control Panel (Win2000 in Administrative Tools), OK, see the list of NT services in which we have joined the service, shown as: "The VB NT SVC View", we can start any other services like start, stop, suspend this service. When we start the service, we hear the annoying beep sound of the service. Our tests are complete.


Four, VB to write the service of several instructions:
1, the first statement: VB writing service is an attempt, technical research, not advocating all services to use VB to write just the right. Similarly, it also shows that the service is not VC write.
2, VB to write the service is only suitable for Win32 services, not suitable for NT low-level services.
3, the advantages of VB in ActiveX control, NT services we can use most of the control to complete our service logic, such as involving database operations, we can use ADO components, this aspect, compared with VC, VB has a natural advantage.
4, do a good service within the error event records, only use this point, can really meet the service to write norms, but also facilitate our debugging.
5, the last point, this article is for reference only, if there are errors and errors caused by the consequences, I am not responsible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.