下面给出将服务设置为自动启动,并将服务启动起来的相关代码:
BOOL ChangeServiceStartTypeAndStart( CString strSvrName ) { SC_HANDLE schSCManager; SC_HANDLE schService; // Get a handle to the SCM database. CString strErrInfo; schSCManager = OpenSCManager( NULL, // local computer NULL, // ServicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == schSCManager) { strErrInfo.Format(_T("OpenSCManager failed (%d)\n"), GetLastError()); AfxMessageBox(strErrInfo); return FALSE; } // Get a handle to the service. schService = OpenService( schSCManager, // SCM database (LPCTSTR)strSvrName, // name of service SERVICE_CHANGE_CONFIG|SERVICE_START); // need change config access if (schService == NULL) { strErrInfo.Format(_T("OpenService failed (%d)\n"), GetLastError()); AfxMessageBox(strErrInfo); CloseServiceHandle(schSCManager); return FALSE; } // Change the service start type.(set to auto start type) BOOL bRet = ChangeServiceConfig( schService, // handle of service SERVICE_NO_CHANGE, // service type: no change SERVICE_AUTO_START, // service start type -- 将服务的启动类型设置为自动启动 SERVICE_NO_CHANGE, // error control: no change NULL, // binary path: no change NULL, // load order group: no change NULL, // tag ID: no change NULL, // dependencies: no change NULL, // account name: no change NULL, // password: no change NULL); if ( !bRet ) // display name: no change { strErrInfo.Format(_T("ChangeServiceConfig failed (%d)\n"), GetLastError()); AfxMessageBox(strErrInfo); CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return FALSE; } else { strErrInfo.Format(_T("Service disabled successfully.\n")); } // Start the service -- 启动该服务 bRet = StartService( schService, // handle to service 0, // number of arguments NULL); // Attempt to start the service. if ( !bRet ) // no arguments { strErrInfo.Format(_T("StartService failed (%d)\n"), GetLastError()); AfxMessageBox(strErrInfo); } else { printf("Service start pending...\n"); } // Close service handles CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return bRet; }