VC ++ 6 Development of Windows service programs

Source: Internet
Author: User

The following describes how to use VC ++ to develop a Windows service program.
Run VC ++ 6, select new project, select "atl com Appwizard" in the window that appears, select the project placement location and the corresponding project name, and then select OK.

In this case, the window appears, select "Service (exe)", and then click "finish.

In the following window, select OK.

Then VC completes the wizard and generates the corresponding code (the effect is as follows ).

The program entry point is the global function _ twinmain. Take a closer look at this function and we will find that when we run the program, we can add parameters, such as winsvr/regserver or winsvr-regserver, this is used for local Server Registration (register as local s register as service erver ).
Here, winsvr/service or winsvr-service is the registration of the service (register as service); winsvr/unregserver or winsvr-unregserver, which is the deletion of the service.
Therefore, when we write the service program and add the parameter service during running, we will see our service in SCM.
After each encoding test, it is very troublesome to add parameters to the command line to run the service so that it can be listed in SCM. Therefore, the following methods can be used for processing: choose vc ide's menu project-> Settings, and then select the custom build Panel (as shown in)

Add "$ (targetpath)"/regserver to "$ (targetpath)"/service, so that when we compile the program after each encoding, you no longer need to add parameters in the command line to execute our service program to complete service registration.
At the same time, we can also see that the wizard creates a class for us: cservicemodule, and the global variable _ module is an instance of this class.
Init (): This function is used to complete initialization;
Run (): this function is the content after the service starts running. Here we will modify the content.
Install (): There is a piece of code
SC _handle hservice =: createservice (
Hscm, m_szservicename, m_szservicename,
Service_all_access, service_win32_own_process,
Service_demand_start, service_error_normal,
Szfilepath, null, null, _ T ("RPCSS \ 0"), null, null );
Note: If the program started in the service has a window (that is, the following code is required for interaction)
SC _handle hservice =: createservice (
Hscm, m_szservicename, m_szservicename,
Service_all_access, service_win32_assist_process | service_interactive_process,
Service_auto_start, service_error_normal,
Szfilepath, null, null, _ T ("RPCSS \ 0"), null, null );

The createservice function is originally as follows:
SC _handle createservice (
SC _handle hscmanager, // handle to SCM Database
Lptstr lpservicename, // name of service to start
Lpctstr lpdisplayname, // display name
DWORD dwdesiredaccess, // type of access to service
DWORD dwservicetype, // type of service
DWORD dwstarttype, // when to start service
DWORD dwerrorcontrol, // severity of service failure
Lpctstr lpbinarypathname, // name of binary file
Lpctstr lploadordergroup, // name of load ordering Group
Lpdword lpdwtagid, // tag identifier
Lptstr lpdependencies, // array of dependency names
Lpctstr lpservicestartname, // account name
Lpctstr lppassword // account password
);
The sixth parameter is the Service Startup type.
Service_demand_start is manual and service_auto_start is automatic.
11th parameters are service dependencies. For example, if you want to enable a service to depend on the startup of SQL Server, you can write this parameter as follows:
_ T ("MSSQLServer \ 0 ");
If the service we write is not stored in any other service, we can set this parameter to null.
Next we will implement the business we need to implement.
First, find the run function in the class cservicemodule and find the following code in the run function:
MSG;
While (getmessage (& MSG, 0, 0, 0 ))
Dispatchmessage (& MSG );
Add your own code before this Code. The Code I added here is customfunc1 ().
Different applications are written in different ways:
1. If you want to start a window for interaction, the Code is as follows:
Define two member functions: customfunc1 and customfunc2
Void cservicemodule: customfunc1 ()
{
Tchar szfilepath [max_path + 1];
Getmodulefilename (null, szfilepath, max_path );
(_ Tcsrchr (szfilepath, _ T ('\') [1] = 0; // delete the file name and only obtain the path
Cstring str_url = szfilepath;
Str_url = str_url + "B .exe ";
Logevent ("running program:" + str_url );
Uint RTN = winexec (str_url, sw_show );

// Uint RTN = winexec ("C: \ WINDOWS \ system32 \ cmd.exe", sw_shownormal );

If (RTN> 31 ){
Logevent ("successful call ");
}
Else {
If (RTN = 0 ){
Logevent ("insufficient memory ");
}
Else {
If (RTN = error_bad_format) {// error_bad_format = 11
Logevent ("the EXE file is invalid ");
}
Else {
If (RTN = error_file_not_found) {// error_file_not_found = 2
Logevent ("file name error ");
}
Else {
If (RTN = error_path_not_found) {// error_path_not_found = 3
Logevent ("Incorrect path name ");
}
Else {
Logevent ("other errors occurred ");
}
}
}
}
}

}

Bool cservicemodule: customfunc2 ()
{
Hdesk hsf-current;
Hdesk;
Hwinsta hwinstacurrent;
Hwinsta;

Hwinstacurrent = getprocesswindowstation ();
If (hwinstacurrent = NULL ){
Logevent (_ T ("Get window station Err "));
Return false;
}

Hsf-current = getthreaddesktop (getcurrentthreadid ());
If (hsf-current = NULL ){
Logevent (_ T ("Get window desktop Err "));
Return false;
}

// Enable winsta0
Hwinsta = openwindowstation ("winsta0", false,
Winsta_accessclipboard |
Winsta_accessglobalatoms |
Winsta_createdesktop |
Winsta_enum1_tops |
Winsta_enumerate |
Winsta_exitwindows |
Winsta_readattributes |
Winsta_readscreen |
Winsta_writeattributes );
If (hwinsta = NULL ){
Logevent (_ T ("open window station Err "));

Return false;
}

If (! Setprocesswindowstation (hwinsta )){
Logevent (_ T ("set window station Err "));

Return false;
}

// Open the Desktop
Hdesk = opendesktop ("default", 0, false,
Optional top_createmenu |
Optional top_createwindow |
Optional top_enumerate |
Optional top_hookcontrol |
Optional top_journalplayback |
Optional top_journalrecord |
Optional top_readobjects |
Optional top_switchdesktop |
Optional top_writeobjects );
If (hdesk = NULL ){
Logevent (_ T ("Open desktop Err "));

Return false;
}

Setthreaddesktop (hdesk );

Customfunc1 ();

If (! Setprocesswindowstation (hwinstacurrent ))
Return false;

If (! Setthreaddesktop (hsf-current ))
Return false;

If (! Closewindowstation (hwinsta ))
Return false;

If (! Closedesktop (hdesk ))
Return false;

Return true;

}
2. If there is no interaction window, the Code is as follows:
Void cservicemodule: customfunc1 (){
Logevent (_ T ("custorm function invoked"); // you can change it to any code you need. Of course, there cannot be any code in the display window, to display the code in the window, use method 1 above.
}
Now you can compile and execute the program.
At this time, an error "cstring": Undeclared identifier will be reported during compilation.
In this case, you need to view some settings of the project:
Menu project-> Settings, General Panel, default settings: use MFC as the static Connection Library. For this setting, do the following:
Open the stdafx. h file, find the # include <atlbase. h> position, and add # include <afx. h> before it. Recompile.
To modify the service name that appears in SCM, you can find the ids_servicename item in the resource file in the project.

Note: The compiled program must enter the following commands in the console:
1. Registration Service
Winsvr/regserver
Winsvr/service // This command is very important. If it is not executed, it will not be visible in SCM.

2. log out of service
Winsvr/unregserver

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.