C++學(xué)習(xí)筆記-后臺(tái)服務(wù)程序開(kāi)發(fā)模式(四)
轉(zhuǎn)自http://www.7880.com/Info/Article-5a934180.html
5.停止和刪除已安裝的服務(wù)程序
//停止和刪除已安裝的服務(wù)程序 void removeService() { SC_HANDLE schService; SC_HANDLE schSCManager; //打開(kāi)服務(wù)管理數(shù)據(jù)庫(kù) schSCManager=OpenSCManager( NULL, //本地計(jì)算機(jī) NULL, //默認(rèn)的數(shù)據(jù)庫(kù) SC_MANAGER_ALL_ACCESS //要求所有的訪問(wèn)權(quán) ); if(schSCManager) { //獲取服務(wù)程序句柄 schService=OpenService( schSCManager, //服務(wù)管理數(shù)據(jù)庫(kù)句柄 TEXT(SZSERVICENAME), //服務(wù)名 SERVICE_ALL_ACCESS //響應(yīng)所有的訪問(wèn)請(qǐng)求 ); if(schService) { //試圖停止服務(wù) if(ControlService( schService, //服務(wù)程序句柄 SERVICE_CONTROL_STOP, //停止服務(wù)請(qǐng)求碼 &ssStatus //接收最后的服務(wù)狀態(tài)信息 )) { _tprintf(TEXT("Stopping %s."),TEXT(SZAPPNAME)); Sleep(1000); //等待服務(wù)停止 // while(QueryServiceStatus(schService,&ssStatus)) { if(SERVICE_STOP_PENDING==ssStatus.dwCurrentState) { _tprintf(TEXT(".")); Sleep(1000); } else break; } if(SERVICE_STOPPED==ssStatus.dwCurrentState) _tprintf(TEXT("\n %s stopped. \n"),TEXT(SZAPPNAME)); else _tprintf(TEXT("\n %s failed to stopp. \n"),TEXT(SZAPPNAME)); } //刪除已安裝的服務(wù)程序安裝 if(DeleteService(schService)) _tprintf(TEXT("%s removed. \n"),TEXT(SZAPPNAME)); else _tprintf(TEXT("DeleteService failed - %s. \n"), GetLastError()); CloseServiceHandle(schService); } else _tprintf(TEXT("OpenService failed - %s \n"),GetLastError()); CloseServiceHandle(schSCManager); } else _tprintf(TEXT("OpenSCManager failed - %s \n"),GetLastError()); } |
在編譯程序的時(shí)候,我們會(huì)發(fā)覺(jué)ServiceStop();ServicePause();ServiceContinue();等三個(gè)函數(shù)沒(méi)有具體實(shí)現(xiàn),這對(duì)于理解此文的人來(lái)說(shuō)應(yīng)該不難編寫(xiě),在此我可以給點(diǎn)文檔內(nèi)的參考:聲明 SetTheServiceStatus()函數(shù),
//
// SetTheServiceStatus - This just wraps up SetServiceStatus.
//
void SetTheServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
DWORD dwCheckPoint, DWORD dwWaitHint)
{
SERVICE_STATUS ss; // Current status of the service.
//
// Disable control requests until the service is started.
//
if (dwCurrentState == SERVICE_START_PENDING)
ss.dwControlsAccepted = 0;
else
ss.dwControlsAccepted =
SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN;
// Other flags include SERVICE_ACCEPT_PAUSE_CONTINUE
// and SERVICE_ACCEPT_SHUTDOWN.
// Initialize ss structure.
ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ss.dwServiceSpecificExitCode = 0;
ss.dwCurrentState = dwCurrentState;
ss.dwWin32ExitCode = dwWin32ExitCode;
ss.dwCheckPoint = dwCheckPoint;
ss.dwWaitHint = dwWaitHint;
// Send status of the service to the Service Controller.
if (!SetServiceStatus(ssh, &ss))
ErrorStopService(TEXT("SetServiceStatus"));
}
然后用如下的方式來(lái)調(diào)用函數(shù)來(lái)實(shí)現(xiàn)源程序中缺少的功能 :
SetTheServiceStatus(SERVICE_STOPPED, GetLastError(), 0, 0);// Stop the service
posted on 2011-06-17 15:13 厚積薄發(fā) 閱讀(203) 評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi): Windows編程