[VB] [win] How to use VB to compile the NT Service Program-ntsvc. ocx

Source: Internet
Author: User

How to use VB to compile the NT Service Program-ntsvc. ocx

I. NT service programs
The so-called NT Service is actually a process that can automatically start with a certain identity when the system starts. Such as FTP server, HTTP server, and offline printing are provided in the form of NT services. This is actually similar to the Unix root daemon process. In summary, the NT Service has the following features:

1. It can be started automatically without interactive startup. This is an important feature for servers. Of course, you can decide whether the service is self-started or even block a service.
2. the NT Service has no user interface, which is basically similar to a DOS program. Because the NT Service must run for a long time, you do not want to have your own interface like the common Win32 process. However, the NT Service can interact with the user interface, which is a special service process. You can view the service process through the task manager of NT.
3. the NT Service is managed through the SCM interface. The SCM interface functions are required for installation, start, stop, and removal. The service controller of the Control Panel uses the SCM interface to manage all services in the system. In addition, there are some program commands that can control the service, such as 、scm.exe, such as net.exe, Server Manager, and so on.
4. These processes run in a certain identity to facilitate access to server resources. Generally, the LocalSystem account in the domain is used to run the program. This account has full access permissions to most resources on the machine (unless otherwise prohibited), which ensures that the service program is "powerful ". However, some services run with special accounts. You can also set a service account.
5. the system automatically runs in the thread mode. Generally, it only occupies more system resources. This is different from common processes. If the thread mode is not used, generally, processes consume the entire CPU resource. Generally, tasks that need to exist from time to time and do not consume too much resources are most suitable for Service implementation.

 

Ii. Service controls
C/C ++ is generally used to compile NT services. vc6 uses the ATL Wizard to provide a basic service framework. The specific implementation steps are: file à New... À atl com Appwizard à service à finish. But using VC to compile NT services requires too much code, which also means too much debugging and maintenance. In fact, the NT Service cannot be written only by C/C ++. In fact, it can be implemented by any language that can implement the features of the previous section, including Vb.

What are the advantages of the VB Compiling Service? At least the following items can be listed:

1. Simple coding. anyone familiar with the VB syntax can write this article after understanding it.
2. It means that the logic for modifying service implementation is simple, and maintenance is simple.
3. You can write a powerful service, such as ADO, by using almost all the component functions in VB. If you use VC to implement it, I believe anyone will issue a warning.
4. (far-fetched) prove how powerful Vb is under Bill's sky.
So how does VB compile the NT Service? As far as I am concerned, there are at least two ways:

1. Use winapi Based on the C/C ++ idea.

2. The component is implemented in the traditional way of VB.

If method 1 is actually a copy of the C/C ++ routine, and if there is a better way to achieve it, I believe no one will take this "no way ", compared with other languages, this programming completely loses the features of VB and does not have any advantages in other languages. Here, we want to tell you how to use OCX to implement a service. If you search for samples/msdn/TechArt/4920/In msdn, you can see a project file of the prepared vc5. Compile this project to get an ntsvc. ocx. If you are not familiar with C/C ++, you can download an ntsvc from the http://www.mywebtech.net/download/ntsvc.zip. OCX, which is obtained from BackOffice. Copy it to/winnt/system32/and use regsvr32 ntsvc. OCX command registration. In this way, your VB can be retrieved from project/components... In the displayed dialog box, the item "Microsoft NT Service Control" is displayed. This component has the basic functions for creating a service. To write an NT Service, we drag it into our form and set its properties, you can call the function of interacting with the system, registry, and SCM to complete a service.

First, let's understand the attributes of this component and explain the usage of these attributes to everyone:
Account string, account attribute, that is, the NT domain account under which the NT Service runs. The default is the LocalSystem account. In fact, most NT services can run safely and satisfactorily under this account.
Controlsaccepted long, which is controlled by SCM and has the following values:
0. Allow start and stop.

2. allow pause and continue.

4. shutdown is allowed.

Other values, user-defined events.
With this attribute, you can decide whether to allow the SCM to stop, pause, start, and other operations at a certain time point of the NT service process (such as an operation that cannot be interrupted.
Dependencies string. if the service you write depends on one or more services for normal operation, you must specify the list of services that you depend on when registering the service. Dependencies separate multiple services by CHR (0) according to the dependency order, and end with two CHR (0. (We can see that this is a trace of C/C ++)
Displayname string, display name. The name of the NT Service displayed to the viewer.
Interactive Boolean: whether to allow interaction with desktop users.
Loadordergroup string, which is related to dependencies. It is determined that the services must be started before the service is started. The format is similar. It is also separated by CHR (0) and ends with two consecutive CHR (0.
Password string indicates the password for starting the service. If you use the default account, you do not need to set the account for starting the service.
Servicename string, service name. If you use net.exeto control the service, the parameter specified by net.exe is a string in this attribute.
Startmode Enumeration type, specifically:
Vcstartautomatic 2 service can be started by yourself

Svcstartmanual 3 Service Manual start

Svcstartdisabled 4 service cannot be started by itself
There is also a debug attribute, which is not discussed.

To treat a vbprogram as an NT Service, we must "Apply" to the system, and the corresponding work VB cannot be well completed. Therefore, ntsvc. ocx provides the corresponding method for us to transfer relevant information to the system.
Install to install the current vbprogram into the NT Service. Before that, you must set at least displayname, servicename, controlsaccepted, startmode, and other attributes. In addition, you may also need to set the account, password, loadordergroup, dependencies, and so on. Whether the information is correctly set determines whether your service program can start and run properly.
Uninstall: Delete the service specified by ntsvc. ocx from the system registry. The NT service depends on the settings of the system service registry, which is a well-known secret.
Startservice: starts the specified service if it is registered.
Stopservice: stop the service if the service is running.
Logevent, which records service events. Errors and unexpected events may occur during service running. You can use this method to record these events, so that the administrator can use the "Event Viewer" to view relevant information to optimize the service. This method has three parameters: event, ID, and message. event, which indicate the event type and can be set to the following values:
Svceventerror 1 error event
Svceventwarning 2 warning event.
Svceventinformation 4 provides reference information.

Svceventauditsuccess 8 Audit successful.

Svceventauditfailure 10 audit failed
In addition to the above methods, you may also need to read and write the Registry. This control also provides the Registry access method:
Deletesetting (Section [, key])
Getallsettings (Section)
Getsetting (section, key [, default])
Savesetting (section, key, setting ).

 

 

 

 

3. Write services
To understand the above content, let's start designing a service. Through examples, let everyone understand how to compile the service in VB.
Before that, we decided to write a service. I refer to an example in C ++ build to write a service process that keeps alarming. After the process is started, the beep call is sent every five seconds in the background, which gives you a deeper understanding of the existence of the service, although somewhat annoying. The service name is vbbeepsvc, which is displayed as the VB nt SVC view in SCM.
Come with me!
1. Create a project and SET related controls.
All VB controls must have a form as the carrier. Therefore, first create a standard project, select the menu project-> components ..., Then select (Microsoft NT Service Control). The NT Service Control appears in the toolbar. Drag another Timer control to form. Save it. Basically, the creation process is complete.
2. Set control properties.
Select the ntsvc. ocx instance, and set displayname: the VB nt SVC view, servicename: vbbeepsvc, startmode: 3 (manually start the service) in the attribute bar.
Because we want to beep every 5 seconds, we have to rely on a timing mechanism. Therefore, we set the interval of timer to 5000 milliseconds.
The setting of the above attributes depends on your needs. I just said that this setting is sufficient in my vbbeepsvc.
3. write code to implement Service Logic and install and remove services.
Because the service program is actually an EXE file, and you need to solve the installation and removal problems by yourself, you need to add the use of NT Service Control in this program for installation and removal. Then, when should we proceed. When the vbprogram is started, when the form is loaded, we need to add some code to the load event of the form:
On Error goto err_load
Dim strdisplayname as string
Strdisplayname = ntservice1.displayname
If command = "-install" then' when the-install parameter is included at startup
Ntservice1.interactive = true
If ntservice1.install then
Call ntservice1.savesetting ("Parameters", "timerinterval", "1000") 'System Parameter Storage
Msgbox strdisplayname & "installed successfully! "
Else
Msgbox strdisplayname & "Installation failed"
End if
End 'end Installation
Else
If command = "-Uninstall" then'
If ntservice1.uninstall then
Msgbox strdisplayname & "removed successfully"
Else
Msgbox strdisplayname & "failed to remove"
End if
End' terminate Removal
Else
End if
End if
'If the installation or removal is not performed, it is the startup service.
Timer1.interval = CINT (ntservice1.getsetting ("Parameters", "timerinterval", "2000 "))
'Use the timer control to simulate the thread feature of the service.
Ntservice1.controlsaccepted = svcctrlpausecontinue 'Accept the pause and stop operations, meaning the Encoding
Ntservice1.startservice
Err_load:
Call ntservice1.logevent (svcmessageerror, svceventerror, "[" & err. Number & "]" & err. Description) 'svcmessageerror is the error value of the NT Service Control
4. Add the Control Service Code.
Although the continuous threads and other features of the service are implemented by timer, the control of the service is implemented by the SCM interface to every service, when a related event is captured for the NT Service Control in the VB service program, we should respond to these events according to the specific situation and decide whether or how to control the service logic. Of course, the specific logic is manifested in the timer event. However, by changing the global variables supported by the NT Service Control and Timer control, you can implement the logic of the Control Service. DEMO code:
Private sub ntserviceinclucontrol (byval eventid as long)
On Error goto err_control
'Add some processing logic here, which can also be vacant like this example.
Err_control:
Call ntservice1.logevent (svcmessageerror, svceventerror, "[" & err. Number & "]" & err. Description) 'Record
End sub
Private sub ntservice‑pause (success as Boolean)
On Error goto err_pause
Timer1.enabled = false' the timer event is disabled, so the service is stopped.
Call ntservice1.logevent (svceventerror, svcmessageerror, "service paused ")
Success = true' return to the sender of the SCM command, indicating that the service has stopped successfully.
Err_pause:
Call ntservice1.logevent (svcmessageerror, svceventerror, "[" & err. Number & "]" & err. description)
End sub
Private sub ntserviceinclustart (success as Boolean)
On Error goto err_start
Success = true
Timer1.enabled = true' allows Service Logic
Err_start:
Call ntservice1.logevent (svcmessageerror, svceventerror, "[" & err. Number & "]" & err. description)
End sub
Private sub ntserviceappsstop ()
On Error goto err_stop
Unload me 'remove form, natural timer does not exist, Service Logic stopped

Err_stop:
Call ntservice1.logevent (svcmessageerror, svceventerror, "[" & err. Number & "]" & err. description)
End sub
5. Write service logic.
Specifically, some service details are written in the timer event according to the Conventions. In this example, been is issued, but considering the response to the SCM command, the Code must be:
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, install, and test
If there are no errors above, you can compile the program now. Assume that the name of the service program we get is vbbeepsvc.exe. We need to run the following command to install it:
D:/vbprog/> vbbeepsvc-install
To remove the installed services:
D:/vbprog/> vbbeepsvc-uninstall
After the installation is complete, open the "service" on the control panel ("Management Tools" in Win2000). Now, the NT Service list contains the services we added and is displayed: "The VB nt SVC view", we can start, stop, and pause the service like starting any other service. When starting the service, we will hear the annoying beep sound from the service. Our test is complete.

 

Iv. Instructions on compiling services in VB:
1. First of all, it should be declared that compiling a service in VB is an attempt. Technical research does not advocate that all services must be written in VB. Similarly, it also indicates that the service is not writable by VC.
2. VB-written services are only applicable to Win32 services and not to underlying NT services.
3. Advantages of VB in ActiveX controls and NT services we can use the vast majority of controls to complete our service logic. For example, we can use ADO components for database operations, compared with VC, VB has a natural advantage.
4. Make a good record of internal error events of the service. Only by making good use of this information can we truly comply with the service coding specifications and facilitate our debugging.
5. The last point is for reference only. I am not responsible for any errors or consequences.

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.