DWORD user_pid;
HANDLE hprocess, htoken;
HKEY hkey_cur_user = NULL;
LONG status;
user_pid = get_user_process_id();
if (!user_pid) {
vd_printf("get_user_process_id failed");
return false;
}
hprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, user_pid);
if (!OpenProcessToken(hprocess, TOKEN_ALL_ACCESS, &htoken)) {
CloseHandle(hprocess);
return false;
}
ImpersonateLoggedOnUser(htoken);
status = RegOpenCurrentUser(KEY_READ, &hkey_cur_user);
if (status != ERROR_SUCCESS) {
CloseHandle(hprocess);
}
获取当前用户进程id
DWORD get_user_process_id()
{
PROCESSENTRY32 proc_entry;
DWORD explorer_pid = 0;
DWORD agent_session_id;
if (!ProcessIdToSessionId(GetCurrentProcessId(), &agent_session_id)) {
printf("ProcessIdToSessionId for current process failed %lu", GetLastError());
return 0;
}
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) {
printf("CreateToolhelp32Snapshot() failed %lu", GetLastError());
return 0;
}
ZeroMemory(&proc_entry, sizeof(proc_entry));
proc_entry.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(snap, &proc_entry)) {
printf("Process32First() failed %lu", GetLastError());
CloseHandle(snap);
return 0;
}
do {
if (_tcsicmp(proc_entry.szExeFile, TEXT("explorer.exe")) == 0) {
DWORD explorer_session_id;
if (!ProcessIdToSessionId(proc_entry.th32ProcessID, &explorer_session_id)) {
printf("ProcessIdToSessionId for explorer failed %lu", GetLastError());
break;
}
if (explorer_session_id == agent_session_id) {
explorer_pid = proc_entry.th32ProcessID;
break;
}
}
} while (Process32Next(snap, &proc_entry));
CloseHandle(snap);
if (explorer_pid == 0) {
printf("explorer.exe not found");
return 0;
}
return explorer_pid;
}
NT服务程序,要读取注册表中的一些信息,将信息写入HKey_Current_User下的SoftWare键下的一个自建的子目录下。形如:
HKEY_CURRENT_USER\Software\xxxxx
有一个单独的参数设置程序。可是发现在设置程序中设置的参数,在Windows系统服务中读不出来。后来发现其原因如下。
系统服务运行在不同的用户帐户下,
HKey_Current_User是HKey_Users结构中某些键的一个别名。系统服务的注册键是在HKey_Users\.Default下。注册表中其它的主键是共亨的,只的HKey_Current_User是根据不同的用户映射到不同的地方。
如果在想要给的系统服务一个真正的用户帐号,需要在服务面板上设置。
RootKey := HKEY_CURRENT_USER;
后来,我改在HKEY_LOCAL_MACHINE\Software\xxxxx 进行操作了。
OTHERS:
1. Get a token to an user for example via:
- LogonUser
- OpenProcessToken
- DuplcateToken
2. Use "LoadUserProfile" to load the user-profile.
Then you have the handle to the "HKEY_CURRENT_USER"
registry key in the "PROFILEINFO.Profile" entry
(with KEY_ALL_ACCESS).