Cant get "Description" from Win32_OperatingSystem class - c++

I try to get Description from Win32_OperatingSystem, the main problem that i takes empty string.
I dont understand why, when i try to take something else from Win32_OperatingSystem, with type string, i can get it.
Can there be situation when Description is empty? Or its just bug in my code...?
Code:
STDMETHODIMP CSystemInfo::GetOS(CString* SystemInfo )
{
HRESULT hres;
CString tmp;
hres = GetInfo( TEXT( "Win32_OperatingSystem" ), TEXT( "Description" ), &tmp );
if( FAILED( hres ) )
{
return E_FAIL;
}
SystemInfo->SetString( tmp.GetString() );
return S_OK;
}
STDMETHODIMP CSystemInfo::GetInfo( CString className, CString propertyName, CString* info )
{
HRESULT hres;
IWbemLocator* pLoc = NULL;
IWbemServices* pSvc = NULL;
IEnumWbemClassObject* pEnumerator = NULL;
bool initialized = true;
hres = CoInitialize( NULL );
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if( FAILED( hres ) && hres != RPC_E_TOO_LATE )
{
}
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, ( LPVOID* )&pLoc );
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = pLoc->ConnectServer(
bstr_t( L"ROOT\\CIMV2" ), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if( FAILED( hres ) )
{
return E_FAIL;
}
CString tmp = TEXT( "SELECT * FROM ");
tmp += className.GetString();
hres = pSvc->ExecQuery(
bstr_t( "WQL" ),
bstr_t(tmp.GetString()),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator );
if( FAILED( hres ) )
{
return E_FAIL;
}
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
while( pEnumerator )
{
HRESULT hr = pEnumerator->Next( WBEM_INFINITE, 1, &pclsObj, &uReturn );
if( uReturn == 0 )
{
break;
}
VARIANT vtProp;
hr = pclsObj->Get(propertyName.GetString(), 0, &vtProp, 0, 0 );
if( FAILED( hres ) )
{
return E_FAIL;
}
info->SetString( vtProp.bstrVal );
VariantClear( &vtProp );
pclsObj->Release();
}
CoUninitialize();
return S_OK;
}
Thats how i calling my function
HRESULT hr;
CoInitialize( NULL );
CSystemInfo* cSystem = NULL;
CLSID clsid;
hr = CLSIDFromProgID( L"Server.Inproc.1" , &clsid );
if( FAILED( hr ) )
{
std::cout << "Cant get CLSID " << std::endl;
}
hr = CoCreateInstance( clsid,NULL, CLSCTX_INPROC_SERVER, IID_ISystemInfo, ( void** )&cSystem );
if( FAILED( hr ) )
{
std::cout << "Cant Create Instance" << std::endl;
}
CString tmp;
hr = cSystem->GetOS( &tmp );
std::wcout << "OS Info: \t" ;
std::wcout << tmp.GetString() << std::endl;
Also i cant get description from Win32_DesktopMonitor.

You can check whether "Description" property is present or not by executing gwmi Win32_OperatingSystem command on Windows PowerShell. I cannot find the "Description" property of Win32_OperatingSystem on my pc.

Related

Task Scheduler API Error 80041318

Hi I am having an issue with the Task Scheduler API in my QT C++ program. I used the example code for a logon trigger here.
The first error I got was CoInitializeSecurity failed: RPC_E_TOO_LATE which means
CoInitializeSecurity has already been called. according to here. So I commented out the coinitializesecurity call and it fixed that.
However now I am getting the 80041318 error when trying to do the very last RegisterTaskDefinition step. I read here this means a value incorrectly formatted or out of range and also possibly an incorrect argument to pLogonTrigger. I tried commenting out the start boundary and end boundary code for the pLogonTrigger which didn't help. I also changed the changing the pLogonTrigger UserId and the userId parameter to the RegisterTaskDefinition function to my account as L"Josh". The only arguments to pLogonTrigger that are left are specified via put_Id and put_UserId.
Should I include any code if that would help and if so which code? The code is pretty much identical to the example code except for the pLogonTrigger modifications, the userId mods, and the commenting out of the cointializesecurity.
*Edited Code Added
void Replicator::taskCreate()
{
/*QProcess *taskProcess = new QProcess(this);
QString program = "schtasks.exe";
QStringList arguments;
arguments << "/create" << "/XML" << "rep.xml" << "/tn" << "task";
taskProcess->start(program, arguments);*/
// ------------------------------------------------------
// Initialize COM.
QString code;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if( FAILED(hr) )
{
//updateStatus("\nCoInitializeEx failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
switch (hr)
{
case S_OK:
code = "S_OK";
break;
case S_FALSE:
code = "S_FALSE";
break;
case RPC_E_CHANGED_MODE:
code = "RPC_E_CHANGED_MODE";
break;
}
updateStatus("CoInitializeEx failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')) + code);
return;
}
// Set general COM security levels.
/* hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
0,
NULL);
if( FAILED(hr) )
{
switch (hr)
{
case S_OK:
code = "S_OK";
break;
case RPC_E_TOO_LATE:
code = "RPC_E_TOO_LATE";
break;
case RPC_E_NO_GOOD_SECURITY_PACKAGES:
code = "RPC_E_NO_GOOD_SECURITY_PACKAGES";
break;
//case E_OUTOFMEMORY:
// code = "E_OUTOFMEMORY";
// break;
}
updateStatus("CoInitializeSecurity failed: " + code);
CoUninitialize();
return;
}*/
// ------------------------------------------------------
// Create a name for the task.
LPCWSTR wszTaskName = L"Jerp";
// Get the windows directory and set the path to notepad.exe.
wstring wstrExecutablePath = _wgetenv( L"WINDIR");
wstrExecutablePath += L"\\SYSTEM32\\NOTEPAD.EXE";
// ------------------------------------------------------
// Create an instance of the Task Service.
ITaskService *pService = NULL;
hr = CoCreateInstance( CLSID_TaskScheduler,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITaskService,
(void**)&pService );
if (FAILED(hr))
{
updateStatus("Failed to create an instance of ITaskService: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
CoUninitialize();
return;
}
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(),
_variant_t(), _variant_t());
if( FAILED(hr) )
{
updateStatus("ITaskService::Connect failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pService->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Get the pointer to the root task folder. This folder will hold the
// new task that is registered.
ITaskFolder *pRootFolder = NULL;
hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
if( FAILED(hr) )
{
updateStatus("Cannot get Root Folder pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pService->Release();
CoUninitialize();
return;
}
// If the same task exists, remove it.
pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );
// Create the task builder object to create the task.
ITaskDefinition *pTask = NULL;
hr = pService->NewTask( 0, &pTask );
pService->Release(); // COM clean up. Pointer is no longer used.
if (FAILED(hr))
{
updateStatus("Failed to create a task definition: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Get the registration info for setting the identification.
IRegistrationInfo *pRegInfo= NULL;
hr = pTask->get_RegistrationInfo( &pRegInfo );
if( FAILED(hr) )
{
updateStatus("Cannot get identification pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
//hr = pRegInfo->put_Author(L"Author Name");
BSTR authorName = SysAllocString(L"Josh");
hr = pRegInfo->put_Author(authorName);
pRegInfo->Release();
if( FAILED(hr) )
{
updateStatus("Cannot put identification info: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Create the settings for the task
/*ITaskSettings *pSettings = NULL;
hr = pTask->get_Settings( &pSettings );
if( FAILED(hr) )
{
updateStatus("Cannot get settings pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Set setting values for the task.
hr = pSettings->put_StartWhenAvailable(VARIANT_TRUE);
pSettings->Release();
if( FAILED(hr) )
{
updateStatus("Cannot put setting info: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}*/
// ------------------------------------------------------
// Get the trigger collection to insert the logon trigger.
ITriggerCollection *pTriggerCollection = NULL;
hr = pTask->get_Triggers( &pTriggerCollection );
if( FAILED(hr) )
{
updateStatus("Cannot get trigger collection: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Add the logon trigger to the task.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create( TASK_TRIGGER_LOGON, &pTrigger );
pTriggerCollection->Release();
if( FAILED(hr) )
{
updateStatus("Cannot create the trigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
ILogonTrigger *pLogonTrigger = NULL;
hr = pTrigger->QueryInterface(
IID_ILogonTrigger, (void**) &pLogonTrigger );
pTrigger->Release();
if( FAILED(hr) )
{
updateStatus("QueryInterface call failed for ILogonTrigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
hr = pLogonTrigger->put_Id( _bstr_t( L"Trigger1" ) );
if( FAILED(hr) )
updateStatus("Cannot put the trigger ID: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
// Set the task to start at a certain time. The time
// format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone).
// For example, the start boundary below
// is January 1st 2005 at 12:05
/*hr = pLogonTrigger->put_StartBoundary( _bstr_t(L"2005-01-01T12:05:00") );
if( FAILED(hr) )
updateStatus("Cannot put the start boundary: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
hr = pLogonTrigger->put_EndBoundary( _bstr_t(L"2025-05-02T08:00:00") );
if( FAILED(hr) )
updateStatus("Cannot put the end boundary: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));*/
// Define the user. The task will execute when the user logs on.
// The specified user must be a user on this computer.
//hr = pLogonTrigger->put_UserId( _bstr_t( L"DOMAIN\\UserName" ) );
//hr = pLogonTrigger->put_UserId( _bstr_t( L"JOSHDESKTOP10\\Josh" ) );
hr = pLogonTrigger->put_UserId( _bstr_t( L"Josh" ) );
pLogonTrigger->Release();
if( FAILED(hr) )
{
updateStatus("Cannot add user ID to logon trigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Add an Action to the task. This task will execute notepad.exe.
IActionCollection *pActionCollection = NULL;
// Get the task action collection pointer.
hr = pTask->get_Actions( &pActionCollection );
if( FAILED(hr) )
{
updateStatus("Cannot get Task collection pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Create the action, specifying that it is an executable action.
IAction *pAction = NULL;
hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
pActionCollection->Release();
if( FAILED(hr) )
{
updateStatus("Cannot create the action: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
IExecAction *pExecAction = NULL;
// QI for the executable task pointer.
hr = pAction->QueryInterface(
IID_IExecAction, (void**) &pExecAction );
pAction->Release();
if( FAILED(hr) )
{
updateStatus("QueryInterface call failed for IExecAction: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Set the path of the executable to notepad.exe.
hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );
pExecAction->Release();
if( FAILED(hr) )
{
updateStatus("Cannot set path of executable: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
/*hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
//_variant_t(L"Builtin\\Administrators"),
_variant_t(L"Josh"),
_variant_t(),
TASK_LOGON_PASSWORD,
_variant_t(L""),
&pRegisteredTask);*/
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
//_variant_t(L"Builtin\\Administrators"),
_variant_t(),
_variant_t(),
TASK_LOGON_GROUP,
_variant_t(L""),
&pRegisteredTask);
if( FAILED(hr) )
{
switch (hr)
{
case E_ACCESSDENIED:
code = "E_ACCESSDENIED";
break;
case E_OUTOFMEMORY:
code = "E_OUTOFMEMORY";
break;
case SCHED_S_BATCH_LOGON_PROBLEM:
code = "SCHED_S_BATCH_LOGON_PROBLEM";
break;
case SCHED_S_SOME_TRIGGERS_FAILED:
code = "SCHED_S_SOME_TRIGGERS_FAILED";
break;
}
updateStatus("Error saving the Task : " + QString("%1").arg(hr,8,16,QLatin1Char('0')) + code);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
updateStatus(" Success! Task successfully registered. " );
// Clean up
pRootFolder->Release();
pTask->Release();
pRegisteredTask->Release();
CoUninitialize();
}
Finally solved this problem after lots of troubleshooting... the answer is simple: set UserId to the appropriate user, in my case "Josh", you can use the Win32 API getusername function if you need to
hr = pLogonTrigger->put_UserId( _bstr_t( L"Josh" ) );
and then for RegisterTaskDefinition do this:
VARIANT varPassword;
varPassword.vt = VT_EMPTY;
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(L"Builtin\\Administrators"),
varPassword,
TASK_LOGON_GROUP,
_variant_t(L""),
&pRegisteredTask);
So the userID parameter for RegisterTaskDefinition needs to be _variant_t(L"Builtin\Administrators") and the logonType needs to be TASK_LOGON_GROUP
So the main point is the two UserId values aren't necessarily the same.

Get all processes for Current User

I need to get all processes for current user. Currently I have a function implemented using WMI that gets all active processes by All Users. I need to somehow get all processes by Current User.
If you go to Task Manager in Windows, Details tab, you will see all processes by All Users. But say you are in Visual Studio and you go to Debug/Attach To Process, this shows all processes by Current User. That's the list that I need.
Here is my solution of All Processes by All Users:
CComPtr<IEnumWbemClassObject> pEnumerator;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_Process"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
Either a WMI or Win32 solution will be good enough. Thank you!!
OK, there is now short way. But here is the working solution if anyone is interested:
std::wstring GetProcessUserName(DWORD dwProcessId)
{
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);
if (processHandle != NULL)
{
HANDLE tokenHandle;
if (OpenProcessToken(processHandle, TOKEN_READ, &tokenHandle))
{
TOKEN_USER tokenUser;
ZeroMemory(&tokenUser, sizeof(TOKEN_USER));
DWORD tokenUserLength = 0;
PTOKEN_USER pTokenUser;
GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS::TokenUser, NULL,
0, &tokenUserLength);
pTokenUser = (PTOKEN_USER) new BYTE[tokenUserLength];
if (GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS::TokenUser, pTokenUser, tokenUserLength, &tokenUserLength))
{
TCHAR szUserName[_MAX_PATH];
DWORD dwUserNameLength = _MAX_PATH;
TCHAR szDomainName[_MAX_PATH];
DWORD dwDomainNameLength = _MAX_PATH;
SID_NAME_USE sidNameUse;
LookupAccountSid(NULL, pTokenUser->User.Sid, szUserName, &dwUserNameLength, szDomainName, &dwDomainNameLength, &sidNameUse);
delete pTokenUser;
return std::wstring(szUserName);
}
}
}
return std::wstring();
}
std::unordered_map<std::wstring, std::vector<DWORD>> GetAllRunningProcessesForCurrentUser()
{
std::unordered_map<std::wstring, std::vector<DWORD>> processHash;
HRESULT hres;
// Initialize COM. ------------------------------------------
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
return processHash;
}
do {
// Obtain the initial locator to WMI -------------------------
CComPtr<IWbemLocator> pLoc;
hres = pLoc.CoCreateInstance(CLSID_WbemLocator);
if (FAILED(hres))
{
break;
}
// Connect to WMI through the IWbemLocator::ConnectServer method
// Connect to the root\cimv2 namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
CComPtr<IWbemServices> pSvc;
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if (FAILED(hres))
{
break;
}
// Set security levels on the proxy -------------------------
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
break;
}
// Use the IWbemServices pointer to make requests of WMI ----
CComPtr<IEnumWbemClassObject> pEnumerator;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_Process"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
break;
}
// Get the data from the query in step 6 -------------------
CComPtr<IWbemClassObject> pclsObj;
while (pEnumerator)
{
ULONG uReturn = 0;
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (0 == uReturn)
{
break;
}
VARIANT vtProp;
VARIANT vtProp2;
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
hr = pclsObj->Get(L"ProcessId", 0, &vtProp2, NULL, NULL);
auto userName = GetProcessUserName(vtProp2.intVal);
TCHAR szActiveUserName[_MAX_PATH];
DWORD dwActiveUserNameLength = _MAX_PATH;
GetUserName(szActiveUserName, &dwActiveUserNameLength);
if (_tcscmp(userName.c_str(), szActiveUserName) == 0)
{
processHash[vtProp.bstrVal].push_back(vtProp2.intVal);
}
VariantClear(&vtProp2);
VariantClear(&vtProp);
pclsObj.Release();
}
} while (false);
CoUninitialize();
return processHash;
}

Not able to get UniqueId of CPU using WMI classes c++

In an application, it needs to retrieve, a system specific UniqueId. SO that I have tried to retrive the UniqueId of the CPU. and I am using WMI class property to retrieve that.
But on trying to retrieve the 'UniqueId' property of win32_processor class, it returns VT_NULL in the variant in which the output is expected. But in the same time it is providing valid outputs for other properties like, deciveId, processorId etc. but those are not unique and can't fulfil my purpose.
Any one know why this happens? plz help me....
below is the code that i used... please have a look, and say whether there is any problem in that....
what modification can i do to make it work...
if(CoInitializeSecurity( NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
0
) != S_OK)
return;
IWbemLocator * pIWbemLocator = NULL;
IWbemServices * pWbemServices = NULL;
IEnumWbemClassObject * pEnumObject = NULL;
BSTR bstrNamespace = (L"root\\cimv2");
if(CoCreateInstance (
CLSID_WbemAdministrativeLocator,
NULL ,
CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER ,
IID_IUnknown ,
( void ** ) & pIWbemLocator
) != S_OK)
return;
if(pIWbemLocator->ConnectServer(
bstrNamespace, // Namespace
NULL, // Userid
NULL, // PW
NULL, // Locale
0, // flags
NULL, // Authority
NULL, // Context
&pWbemServices
) != S_OK)
return;
HRESULT hRes;
BSTR strQuery = (L"Select * from Win32_Processor");
BSTR strQL = (L"WQL");
hRes = pWbemServices->ExecQuery(strQL, strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
if(hRes != S_OK)
{
MessageBox("Could not execute Query");
return;
}
ULONG uCount = 1, uReturned;
IWbemClassObject * pClassObject = NULL;
hRes = pEnumObject->Reset();
if(hRes != S_OK)
{
MessageBox("Could not Enumerate");
return;
}
hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
if(hRes != S_OK)
{
MessageBox("Could not Enumerate");
return;
}
VARIANT v;
BSTR strClassProp = SysAllocString(L"UniqueId");
hRes = pClassObject->Get(strClassProp, 0, &v, 0, 0);// here the v is VT_NULL but works if the vlaue of strClassProp is processerId, deviceId
if(hRes != S_OK)
{
MessageBox("Could not Get Value");
return;
}
SysFreeString(strClassProp);
_bstr_t bstrPath = &v; //it causes exception if the v is VT_NULL in other cases its working
char* strPath = new char [1024];
_stprintf(strPath, ("%s"),(char*)bstrPath);
if (SUCCEEDED(hRes))
MessageBox(strPath);
Expects expert advice and help....
Thanks in Advance....

WMI call from C++ results in HRESULT=0x80041003

I'm not sure why am I getting this strange result. Can someone please shed some light on this?
I'm using WMI calls from a C++ program to export the 'Application' part of the Windows Event Log.
This is done from a local service and the code works fine under Windows 7. The problem happens when I run it on Windows XP. For some weird reason the ExecMethod() of the WMI interface returns HRESULT=0x80041003, which is Access denied.
But if I put the exact same code into a simple user process and run it from there, everything works great. How could that be, the code fails to run from a more privileged local service but works from a simple user process?
PS. I'd appreciate any ideas because I've been working on this for several days to no avail....
PS2. I enabled the following privileges (like if I need to do this for the local service) and that still didn't help:
SE_SECURITY_NAME
SE_BACKUP_NAME
EDIT: I guess adding a sample code wouldn't hurt. (Sorry for the long chunk, but this darn WMI/COM isn't a beauty either....) I marked the spot where I get an error below:
// Initialize COM. ------------------------------------------
hr = CoInitializeEx(0, COINIT_MULTITHREADED);
if(SUCCEEDED(hr))
{
// Set general COM security levels --------------------------
// Note: If you are using Windows 2000, you need to specify -
// the default authentication credentials for a user by using
// a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
// parameter of CoInitializeSecurity ------------------------
hr = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if(SUCCEEDED(hr))
{
// Obtain the initial locator to WMI -------------------------
IWbemLocator *pLoc = NULL;
hr = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *) &pLoc);
if(SUCCEEDED(hr))
{
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
// Connect to the root\cimv2 namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
hr = pLoc->ConnectServer(
_bstr_t(L"\\\\.\\ROOT\\CIMV2"), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if(SUCCEEDED(hr))
{
// Set security levels on the proxy -------------------------
hr = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if(SUCCEEDED(hr))
{
// Use the IWbemServices pointer to make requests of WMI ----
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("Select * from Win32_NTEventLogFile Where LogFileName='Application'"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if(SUCCEEDED(hr))
{
IWbemClassObject *pclsObj = NULL;
int nCnt = -1;
//Go through all results
while (pEnumerator)
{
ULONG uReturn = 0;
hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
//Go to next iteration
nCnt++;
// Get a reference to the Win32_Printer class so we can find
// the RenamePrinter method. This lets us create an object
// representing the input parameter block to be passed to the
// method when we call it.
IWbemClassObject *pNTEventLogFile = NULL;
IWbemClassObject *params = NULL;
IWbemClassObject *paramsInst = NULL;
hr = pSvc->GetObject( _bstr_t( L"Win32_NTEventLogFile" ), 0, NULL,
&pNTEventLogFile, NULL );
if(SUCCEEDED(hr))
{
hr = pNTEventLogFile->GetMethod( _bstr_t( "BackupEventLog" ), 0, &params,
NULL );
if(SUCCEEDED(hr))
{
hr = params->SpawnInstance( 0, &paramsInst );
if(SUCCEEDED(hr))
{
// Now that we've got an instance representing the input
// parameters, we can fill in the parameter values
_bstr_t paramValue( L"C:\\Users\\UserName\\Documents\\application.evt" );
VARIANT paramVt;
paramVt.vt = VT_BSTR;
paramVt.bstrVal = paramValue;
hr = paramsInst->Put( L"ArchiveFileName", 0, &paramVt, NULL );
if(SUCCEEDED(hr))
{
// Get the "this" pointer to our object instance so that we
// can call the RenamePrinter method on it
CIMTYPE type;
LONG flavor;
VARIANT var;
hr = pclsObj->Get( L"__PATH", 0, &var, &type, &flavor );
if(SUCCEEDED(hr))
{
// Execute the RenamePrinter method on our object instance
IWbemClassObject *results = NULL;
hr = pSvc->ExecMethod( var.bstrVal, _bstr_t( L"BackupEventLog" ), 0,
NULL, paramsInst, &results, NULL );
**///////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// THIS IS WHERE hr = 0x80041003 or wbemErrAccessDenied
//////////////////////////////////////////////// only when this code is run from a local service
//////////////////////////////////////////////// on a Windows XP machine, but if I run the exact same
//////////////////////////////////////////////// code from a user process on XP machine, it works!
//////////////////////////////////////////////// Note that this works fine on Windows Vista/7 in any configuration.
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////**
if(SUCCEEDED(hr))
{
//Get result code from the BackupEventLog method
VARIANT vtProp;
hr = results->Get(L"ReturnValue", 0, &vtProp, 0, 0);
if(SUCCEEDED(hr))
{
if(vtProp.vt == VT_I4)
{
//Check
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa384808(v=vs.85).aspx
//0 = Success
//8 = Privilege missing
//21 = Invalid parameter
//80 = Archive file name already exists. This value is returned starting with Windows Vista.
int nResV = vtProp.intVal;
//_tprintf(_T("result2 : %d\n"), nResV);
}
else
{
//Error
}
//Free
VariantClear(&vtProp);
}
else
{
//Error
}
}
else
{
//Error
}
//Free
if(results)
{
results->Release();
results = NULL;
}
//Clear
VariantClear(&var);
}
else
{
//Error
}
//Clear
VariantClear(&paramVt);
}
else
{
//Error
}
}
else
{
//Error
}
}
else
{
//Error
}
}
else
{
//Error
}
//Free
if(pNTEventLogFile)
{
pNTEventLogFile->Release();
pNTEventLogFile = NULL;
}
if(params)
{
params->Release();
params = NULL;
}
if(paramsInst)
{
paramsInst->Release();
paramsInst = NULL;
}
if(pclsObj)
{
pclsObj->Release();
pclsObj = NULL;
}
}
//Free
if(pclsObj)
{
pclsObj->Release();
pclsObj = NULL;
}
}
else
{
//Error
}
//Free
if(pEnumerator)
{
pEnumerator->Release();
pEnumerator = NULL;
}
}
else
{
//Error
}
}
else
{
//Error
}
//Free
if(pSvc)
{
pSvc->Release();
pSvc = NULL;
}
}
else
{
//Error
}
//Free
if(pLoc)
{
pLoc->Release();
pLoc = NULL;
}
}
else
{
//Error
}
//Uninit
CoUninitialize();
}
else
{
//Error
}
I think I got it... For anyone else who doesn't want to waste 3 days looking for an answer here it is: on Windows XP replace RPC_C_IMP_LEVEL_IMPERSONATE with RPC_C_IMP_LEVEL_DELEGATE in the calls to CoInitializeSecurity() and CoSetProxyBlanket(). I don't know what exactly it does, but it makes the code above work! Yay!!!

How can I find out the current color depth of a machine running vista/w7?

I want to check the current color depth of the OS to warn users if they try to run my application with a "wrong" color depth (using c++ & Qt).
I guess there's a win api call to get this information, but I couldn't find anything.
On Windows you could use GetDeviceCaps with the BITSPIXEL flag but you'll need a screen DC first (GetDC could fetch you one).
HDC dc = GetDC(NULL);
int bitsPerPixel = GetDeviceCaps(dc, BITSPIXEL);
ReleaseDC(NULL, dc);
You can do it using WMI.
int bitDepth = -1;
hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
if ( SUCCEEDED( hr ) )
{
// hr = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL );
if ( SUCCEEDED( hr ) )
{
IWbemLocator* pLoc = NULL;
hr = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**)&pLoc );
if ( SUCCEEDED( hr ) )
{
IWbemServices* pSvc = NULL;
hr = pLoc->ConnectServer( BSTR( L"ROOT\\CIMV2" ), NULL, NULL, 0, NULL, 0, 0, &pSvc );
if ( SUCCEEDED( hr ) )
{
hr = CoSetProxyBlanket( pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );
if ( SUCCEEDED( hr ) )
{
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_DisplayConfiguration", WBEM_FLAG_FORWARD_ONLY/* | WBEM_FLAG_RETURN_IMMEDIATELY*/, NULL, &pEnumerator );
if ( SUCCEEDED( hr ) )
{
IWbemClassObject* pDisplayObject = NULL;
ULONG numReturned = 0;
hr = pEnumerator->Next( WBEM_INFINITE, 1, &pDisplayObject, &numReturned );
if ( numReturned != 0 )
{
VARIANT vtProp;
pDisplayObject->Get( L"BitsPerPel", 0, &vtProp, 0, 0 );
bitDepth = vtProp.uintVal;
}
}
pEnumerator->Release();
}
}
pSvc->Release();
}
pLoc->Release();
}
}
// bitDepth wshould now contain the bitDepth or -1 if it failed for some reason.
You should be able to get the bits per pixel value using
HDC hdc = GetDC(NULL);
int colour_depth = GetDeviceCaps(hdc,BITSPIXEL);
ReleaseDC(NULL,hdc);
Call GetDeviceCaps() to retrieve BITSPIXEL
It's not a "per-machine" property actually, you need a HDC.