我需要在我的C ++应用程序中获取Windows“print spooler”服务的状态。
答案 0 :(得分:7)
我找不到任何使用WinApi和C ++的好例子。我尝试并编译了以下内容,它适用于Borland。希望这有助于某人。
int getServiceStatus(char* name)
{
SC_HANDLE theService,scm;
SERVICE_STATUS m_SERVICE_STATUS;
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwBytesNeeded;
scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
if (!scm) {
ShowErr();
return 0;
}
theService = OpenService(scm, name, SERVICE_ALL_ACCESS);
if (!theService) {
CloseServiceHandle(scm);
ShowErr();
return 0;
}
int result = QueryServiceStatusEx(theService, SC_STATUS_PROCESS_INFO, (LPBYTE)
&ssStatus, sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded);
CloseServiceHandle(theService);
CloseServiceHandle(scm);
if (result == 0) return 0; // fail query status
return ssStatus.dwCurrentState;
}
答案 1 :(得分:7)
@shikarssj提供的功能完美运行,加载服务时只需要管理员权限。
这是一个不要求完全许可的版本:
#include <Windows.h>
int GetServiceStatus( const char* name )
{
SC_HANDLE theService, scm;
SERVICE_STATUS m_SERVICE_STATUS;
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwBytesNeeded;
scm = OpenSCManager( nullptr, nullptr, SC_MANAGER_ENUMERATE_SERVICE );
if( !scm ) {
return 0;
}
theService = OpenService( scm, name, SERVICE_QUERY_STATUS );
if( !theService ) {
CloseServiceHandle( scm );
return 0;
}
auto result = QueryServiceStatusEx( theService, SC_STATUS_PROCESS_INFO,
reinterpret_cast<LPBYTE>( &ssStatus ), sizeof( SERVICE_STATUS_PROCESS ),
&dwBytesNeeded );
CloseServiceHandle( theService );
CloseServiceHandle( scm );
if( result == 0 ) {
return 0;
}
return ssStatus.dwCurrentState;
}
答案 2 :(得分:4)
使用QueryServiceStatus或QueryServiceStatusEx。网上有很多关于如何使用它们的例子。