Windows Services Programming

Source: Internet
Author: User

First of all, this article is not writing services, but programming control of existing services.

A service is a type of program that runs in the background and that a service program can often provide users with functionality both locally and over the network. A service program may be an EXE program with its own process, or it may be that the DLL file is attached to a process and more likely the SYS file is in the kernel of the system.

Under Windows, you can right-click on my Computer and then choose Manage on the menu that pops up, open Computer Management tools, click Services and applications in the tree list on the left to open the sub-list, select Services, and the Service list item appears on the right. You can also open the Service Manager by entering "Services.msc" directly in the Run window. Service Manager is used primarily to display application services that already exist on the system, to display a description of the service, and to control the start and start of the service. The Service Manager interface looks like this:


The common API for service programming is as follows:

1. Open Service Manager

Sc_handleopenscmanager (LPCTSTR lpmachinename,//points to the target host name to open the service controller database, this machine is set to nulllpctstrlpdatabasename,// Point to target host SCM database name string DWORD dwdesiredaccess//specifies access to the SCM database);

2. Close the service handle

BOOL Closeservicehandle (sc_handlehscobject//the service or service Manager handle to close);

3. enumeration of services

BOOL enumservicesstatus (  sc_handle hscmanager,//openscmanager function returns the handle  DWORD dwservicetype,//specifies enum service type  DWORD dwservicestate,//Enumeration Specifies the state of the service  lpenum_service_status lpservices,//struct pointer  DWORD cbbufsize,//Specifies the buffer size  Lpdword pcbbytesneeded,//returns the actual amount of memory space used  Lpdword lpservicesreturned,//returns the number of enumerated services  Lpdword lpresumehandle// Returns whether the enumeration succeeded);

4. Open the specified service

Sc_handleopenservice (  sc_handle hscmanager,//Specifies the service handle opened by the OpenSCManager function  LPCTSTR lpservicename,// Specifies the name of the service to open  DWORD dwdesiredaccess//to open access for the service, which can be specified as sc_manager_all_access for convenience. );

5. Start the service

BOOL StartService (  sc_handle hservice,//Specifies the handle to start the service, which is returned by the OpenService function to  DWORD dwnumserviceargs,// The number of parameters required to start the service  lpctstr* lpserviceargvectors//point to the start service parameter);

6. Stop the service

BOOL ControlService (  sc_handle hservice,//specifies a service handle opened by the OpenService  DWORD dwcontrol,//Specifies the control code  to be sent Lpservice_status lpservicestatus//Returns the status of the service);

ControlService () can control multiple services, each of which corresponds to a control code. When you want to stop the service, the control code used is service_control_stop.

Below we will write a project to implement the WIN32 Program service and drive service on the computer respectively, and can stop or start the services specified therein.

Use MFC to build a dialog program with the following interface:


The role of each control I believe we can see that the interface knowledge is not introduced, directly on the key control code.

Where the initialization of the CListCtrl control can refer to the registry operation that blog post.

The code to implement the service enumeration is as follows:

VOID cmydlg::showservicelist (DWORD dwservicetype)//parameter is the service type to enumerate {m_servicelist.deleteallitems ();//Open Service Manager sc_handle HSCM = OpenSCManager (null, NULL, sc_manager_all_access), if (null = = HSCM) {AfxMessageBox ("Open scmanager error!"); return;} DWORD Servicecount = 0;dword dwsize = 0; Lpenum_service_status lpinfo;//First call bool BRet = EnumServicesStatus (Hscm,dwservicetype, service_state_all,null,0, &AMP;DWSIZE,&AMP;SERVICECOUNT,NULL);/* Due to the absence of a buffer for the receiving service list, it is necessary to invoke the return value of the failed failure when the ERROR_MORE_DATA description requires a larger buffer to hold the data */if (! BRet && GetLastError () = = Error_more_data) {//Allocation buffer Save Service List Lpinfo = (lpenum_service_status) (new byte[dwsize]); BRet = EnumServicesStatus (Hscm,dwservicetype, Service_state_all, (lpenum_service_status) Lpinfo,dwsize,&dwsize, &servicecount,null); if (!bret) {closeservicehandle (HSCM); return;} Gets the data one by one, added to the list control for (DWORD i = 0; i < Servicecount; ++i) {CString Str;m_servicelist.insertitem (i, lpinfo[i]. Lpservicename); M_servicelist.setitemtext (i, 1, lpinfo[i].lpdisplayname); switch (lpinfo[i). Servicestatus.dWcurrentstate) {Case Service_paused:{m_servicelist.setitemtext (I, 2, "pause"); Case Service_stopped:{m_servicelist.setitemtext (I, 2, "stop"); Case Service_running:{m_servicelist.setitemtext (I, 2, "Run"); Default:{m_servicelist.setitemtext (i, 2, "other");}}} Free space for the application delete lpinfo;} Close the service Manager handle Closeservicehandle (HSCM);}

Code to start the service:

void Cmydlg::onbtnstart () {//Select the index of the service position Pos = M_servicelist.getfirstselecteditemposition (); int nselect = -1;while (Pos) {nselect = M_servicelist.getnextselecteditem (Pos);} if ( -1 = = nselect) {AfxMessageBox ("Please select service to start"); return;} Gets the service name of the selected service char Szservicename[maxbyte] = {0};m_servicelist.getitemtext (nselect, 0, Szservicename, maxbyte); Sc_handle HSCM = OpenSCManager (null, NULL, sc_manager_all_access); if (null = = HSCM) {AfxMessageBox ("Open Scmanager eorror "); return;} Open the specified service sc_handle hcservice = OpenService (HSCM, Szservicename, service_all_access);//start service bool BRet = StartService ( Hcservice, 0, NULL), if (BRet = = TRUE) {m_servicelist.setitemtext (nselect, 2, "Run");} Else{afxmessagebox ("Failed to start");} Closeservicehandle (Hcservice); Closeservicehandle (HSCM);}

Code to stop the service:

void Cmydlg::onbtnstop () {//Select the index of the service position Pos = M_servicelist.getfirstselecteditemposition (); int nselect = -1;while ( POS) {nselect = M_servicelist.getnextselecteditem (POS);} if ( -1 = = nselect) {AfxMessageBox ("Please select service to stop"); return;} Gets the service name of the selected service char Szservicename[maxbyte] = {0};m_servicelist.getitemtext (nselect, 0, Szservicename, maxbyte);//SC_ HANDLE HSCM = OpenSCManager (null, NULL, sc_manager_all_access); if (null = = HSCM) {AfxMessageBox ("Open scmanager Eoor"); return;} Opens the specified service sc_handle hscservice = OpenService (HSCM, Szservicename, service_all_access); Service_status servicestatus;//Stop service bool BRet = ControlService (Hscservice, Service_control_stop, &servicestatus); if (BRet = = TRUE) {m_servicelist.setitemtext (nselect, 2, "Stop");} Else{afxmessagebox ("service stopped failing");} Closeservicehandle (Hscservice); Closeservicehandle (HSCM);}

Finally again family on this project source code for your reference, of course, I have to charge 5 points of the code to knock hard. Can be found on the resources I upload: service programming (blog)




Windows Services Programming

Related Article

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.