WMI访问系统服务

书接上文
VC WMI应用获取SMBios中的信息

WMI访问系统服务

WMI是可以查询以及启动、停止系统中的服务程序的

于是我又为补充了几个函数

HRESULT CWMI::ExcuteServiceCtrl(UINT uControlCode)
{
	HRESULT hr = E_FAIL;
	CComPtr<IWbemLocator> pLoc = NULL;
	CComPtr<IWbemServices> pSvc = NULL;

	do {
		hr = InitialCom();
		CHECKHR(hr);

		hr = SetComSecLevels();
		CHECKHR(hr);

		hr = ObtainLocator2WMI(pLoc);
		CHECKHR(hr);

		hr = Connect2WMI(pLoc, pSvc);
		CHECKHR(hr);

		hr = SetProxySecLevels(pSvc);
		CHECKHR(hr);

		hr = ServiceCtrl(pSvc,uControlCode);
		CHECKHR(hr);

	} while (0);

	return hr;
}


HRESULT CSynQuery::ServiceCtrl(CComPtr<IWbemServices> pSvc,UINT uControlCode)
{
	HRESULT hr = WBEM_S_FALSE;

	do {
		CComPtr<IEnumWbemClassObject> pEnumerator = NULL;
		hr = pSvc->ExecQuery( 
			CComBSTR("WQL"),
			CComBSTR(m_wszWQLQuery.c_str()),
			WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
			NULL,
			&pEnumerator );

		CHECKWMIHR(hr);
		CComPtr<IWbemClassObject> pClass = NULL;
		//GetObject
		hr = pSvc->GetObject(CComBSTR("Win32_Service"), 0, NULL, &pClass, NULL);
		CHECKWMIHR(hr);
		//GetMethod
		CComBSTR comBstrMethodName;
		if(uControlCode == 0)
		{
			comBstrMethodName = CComBSTR("StopService");
			hr = pClass->GetMethod(CComBSTR("StopService"), 0, NULL, NULL);
		}
		else if(uControlCode == 1)
		{	comBstrMethodName = CComBSTR("StartService");
			hr = pClass->GetMethod(CComBSTR("StartService"), 0, NULL, NULL);
		}
		else
		{

		}
		CHECKWMIHR(hr);
		ULONG uReturn = 0;
		while (pEnumerator)
		{
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pClass, &uReturn);
			if(0 == uReturn)
			{
				break;
			}
			// Get the context for non-static method
			CIMTYPE pType;
			LONG pFlavor;
			VARIANT var;
			pClass->Get(L"__PATH", 0, &var, &pType, &pFlavor);

			// Execute Method
			CComPtr<IWbemClassObject> pOutParams = NULL;
			if(uControlCode == 0)
				hr = pSvc->ExecMethod(var.bstrVal, CComBSTR("StopService"), 0, NULL, NULL, &pOutParams, NULL);
			else if(uControlCode == 1)
				hr = pSvc->ExecMethod(var.bstrVal, CComBSTR("StartService"), 0, NULL, NULL, &pOutParams, NULL);
			else
			{

			}
			CHECKWMIHR(hr);
			VARIANT varReturnValue;
			hr = pOutParams->Get(CComBSTR("ReturnValue"), 0, &varReturnValue, NULL, 0);
			CHECKWMIHR(hr);
			if (varReturnValue.lVal == 0)
			{
				wprintf(L"execute method:%s  success.\n" ,comBstrMethodName);
			}

			
		}

		
	} while (0);

	return hr;  

}


停止无线网卡服务

void DisableWireless()
{
	CSynQuery tSynQuery(L"ROOT\\CIMV2",L"SELECT * FROM Win32_Service WHERE Name = \'Wlansvc\'");
	tSynQuery.ExcuteServiceCtrl(0);
}


PS:在win7以后的系统,要求你的应用程序拥有管理员权限才能成功执行~



你可能感兴趣的:(WMI访问系统服务)