我写了一个系统服务,我想在其中获取事件用户在HKEY_CURRENT_USER 下的一个注册表值。我写了如下代码。但是,它似乎只能获取系统级别的注册表值,无法获取事件用户的注册表值。请参阅下面的代码。哪里有问题?少了什么?
void GetUserRegistryFromSystemService()
{
#ifdef Q_OS_WIN
DWORD sessionId = WTSGetActiveConsoleSessionId();
qInfo() << "Session ID = " << sessionId;
wchar_t * ppUserName[100];
DWORD sizeOfUserName;
WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, ppUserName, &sizeOfUserName);
qInfo() << "Windows User Name = " << QString::fromWCharArray(*ppUserName);
std::wstring strValueOfBinDir = L"Unknown Value";
LONG regOpenResult = ERROR_SUCCESS;
HANDLE hUserToken = NULL;
HANDLE hFakeToken = NULL;
if (WTSQueryUserToken(sessionId, &hUserToken))
{
if (DuplicateTokenEx(hUserToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, 0, SecurityImpersonation, TokenPrimary, &hFakeToken) == TRUE)
{
qInfo() << "Before ImpersonateLoggedOnUser()......";
if (ImpersonateLoggedOnUser(hFakeToken))
{
HKEY hKey;
regOpenResult = RegOpenCurrentUser(KEY_READ, &hKey);
if (regOpenResult != ERROR_SUCCESS)
{
qCritical() << "Failed to call RegOpenCurrentUser(), Error is " << regOpenResult;
}
// Fails to get this hive, will get the default value "Unkown"
RegOpenKeyEx(HKEY_CURRENT_USER,
TEXT("Software\\Baidu\\BaiduYunGuanjia"),
0,
KEY_READ,
&hKey);
GetStringRegKey(hKey, TEXT("installDir"), strValueOfBinDir, TEXT("Unknown"));
// It can get the following hive successfully
// RegOpenKeyEx(HKEY_LOCAL_MACHINE,
// TEXT("Software\\GitForWindows"),
// 0,
// KEY_READ,
// &hKey);
// GetStringRegKey(hKey, TEXT("InstallPath"), strValueOfBinDir, TEXT("Unknown"));
RevertToSelf();
}
else
{
qCritical() << "Failed to ImpersonateLoggedOnUser...";
}
CloseHandle(hFakeToken);
}
else
{
qCritical() << "Failed to call DuplicateTokenEx...";
}
CloseHandle(hUserToken);
}
else
{
qCritical() << "Failed to get the user token of session " << sessionId;
}
qInfo() << "The value of Registry is " << QString::fromWCharArray( strValueOfBinDir.c_str() );
#endif
}
最佳答案
您应该在 RegOpenKeyEx
中使用从 RegOpenCurrentUser
接收的 HKEY
句柄而不是 HKEY_CURRENT_USER
:
regOpenResult = RegOpenCurrentUser(KEY_READ, &hKey);
if (regOpenResult != ERROR_SUCCESS)
{
qCritical() << "Failed to call RegOpenCurrentUser(), Error is " << regOpenResult;
}
HKEY hSubKey;
// Fails to get this hive, will get the default value "Unkown"
RegOpenKeyEx(hKey, TEXT("Software\\Baidu\\BaiduYunGuanjia"), 0, KEY_READ, &hSubKey);
关于c++ - 即使使用系统服务中的 RegOpenCurrentUser 也无法获取用户级注册表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650096/