對於編程高手來說,這個題目有點無聊,不過在某些情況下還是相當有用的。像我刪除卸載了一個軟體,結果什麼都刪除了,結果服務還在那兒,很不雅觀,找遍註冊表都找不到,只好自己動手寫了個小程式來刪除服務。
首先做好介面,如下:
這要用到Windows的服務管理函數組,首先要開啟服務管理員,這要在標頭檔中包含winsvc.h
把SC_HANDLE sh;定義加入對話方塊類中。
在OnInitDialog成員函數中加入如下代碼,以初始化服務管理。
sh=OpenSCManager(0,SERVICES_ACTIVE_DATABASE,SC_MANAGER_ALL_ACCESS); if(!sh) { MessageBox("faile to Open SCManager"); return FALSE; }
在OnClose成員函數中加入
CloseServiceHandle(sh);
然後處理兩個按鈕事件
void CdelsDlg::ListServices(){ // TODO: Add your control notification handler code here DWORD eh=0,d1,nret,i; BOOL ret; SCV.ResetContent(); ret=EnumServicesStatus(sh,SERVICE_WIN32|SERVICE_DRIVER, SERVICE_INACTIVE,ess,sizeof(ess),&d1,&nret,&eh); if(!ret) { char temp[32]; sprintf(temp,"%d",GetLastError()); MessageBox(temp); MessageBox("failed to enum services"); return; } for(i=0;i<nret;i++) { SCV.AddString(ess[i].lpDisplayName); }}
void CdelsDlg::DelService(){ // TODO: Add your control notification handler code here int i,ret; char temp[256]; i=SCV.GetCurSel(); sprintf(temp,"Do you realy want to remove the service\r\n" "%d:\t%s\r\n%s",i,ess[i].lpServiceName,ess[i].lpDisplayName); ret=MessageBox(temp,"Alert!",MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2); if(ret==IDYES) { SC_HANDLE ds; ds=OpenService(sh,ess[i].lpServiceName,SC_MANAGER_ALL_ACCESS); if(!ds) { MessageBox("Failed to Open Service"); return; } if(DeleteService(ds)) { MessageBox("Success to remove the service"); } else { sprintf(temp,"Failed to remove the service\r\nERROR CODE:\t%d", GetLastError()); MessageBox(temp); } CloseServiceHandle(ds); }}
前者枚舉不活動的服務,並把它加入列表框,後者直接刪除對應服務