Thursday, April 7, 2011

Accessing HKCU registry from within service app

Question:

I need to access HKEY_CURRENT_USER for the currently logged in user from my application which runs as a service. How can I do this?


Answer:

You need to use the ImpersonateLoggedOnUser() function which lets your calling thread impersonate the security context of a logged-on user. The user is represented by a token handle. The impersonation lasts until the thread exits or until it calls RevertToSelf().

Follow these steps:


Locate a process in the users' session, specifically, explorer.exe.

Use the process handle with OpenProcessToken() to get an access token to that process.

Call ImpersonateLoggedOnUser() with the process token within a worker thread so that your worker thread behaves as the impersonated (logged-on) user. Your worker thread should be able to modify the HKCU registry without problems.

No comments:

Post a Comment