#include "SvcMgr.hpp" bool StartSQLServer() { SC_HANDLE hManager,hService; TServiceStatus ServiceStatus; bool RetVal; hManager=OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE); hService=OpenService(hManager,"MSSQLSERVER",SERVICE_ALL_ACCESS); //打开该Service if(hService<0) { ShowMessage("系统未找到MSSQLServer数据库服务,请先安装数据库,然后再继续!"); RetVal=false; } else { bool Continue; do { Continue=false; QueryServiceStatus(hService,ServiceStatus); //查看该Service的状态 switch(ServiceStatus.dwCurrentState) { case SERVICE_STOPPED://如果该Service已停止则启动它 if(!StartService(hService,0,NULL)) { int n = GetLastError(); AnsiString s = "启动失败,原因:" ; s+=IntToStr(n); ShowMessage(s); RetVal=false; } else { RetVal=true; } break; case SERVICE_CONTINUE_PENDING : case SERVICE_PAUSE_PENDING: case SERVICE_START_PENDING: case SERVICE_STOP_PENDING: Sleep(500); Continue=true; break; case SERVICE_PAUSED:// The service is paused. if(!ControlService(hService,SERVICE_CONTROL_CONTINUE,ServiceStatus)) { int n = GetLastError(); AnsiString s = "启动失败,原因:" ; s+=IntToStr(n); ShowMessage(s); RetVal=false; } else RetVal=true; break; case SERVICE_RUNNING: RetVal=true;// The service is running. } }while(Continue); } CloseServiceHandle(hService); CloseServiceHandle(hManager); return RetVal; }