How to read and write the HKEY_CURRENT_USER registry in a Windows service program

Source: Internet
Author: User

In the service program you want to read and write to the contents of the registry HKEY_CURRENT_USER, and will not return a failure, but it is always invalid. The reasons are:

1. The service runs under System permissions, not any one user

2.hkey_current_user stores the current user's information ================> causes the data in the service to be read HKEY_CURRENT_USER the actual operation of the user who is not currently logged on.

So if I want to manipulate the key value within the HKEY_CURRENT_USER, I have to impersonate the current user to read it.

There are several ways to do this:

1. Create a user process to operate the registry, using the CreateProcessAsUser function to do

2. Let the current thread impersonate the security context of the currently logged-on user (lets the calling thread impersonate, the security context of a logged-on user). You can do this using the ImpersonateLoggedOnUser function.

The first method needs to use another program, feeling more troublesome.

The second method is shown below:

BOOL Gettokenbyname (HANDLE &htoken,lptstr lpname) {    if(!lpname)returnFALSE; HANDLE Hprocesssnap=NULL; BOOL BRet=FALSE; PROCESSENTRY32 pe32= {0}; Hprocesssnap= CreateToolhelp32Snapshot (th32cs_snapprocess,0); if(Hprocesssnap = =Invalid_handle_value)return(FALSE); Pe32.dwsize=sizeof(PROCESSENTRY32); if(Process32First (Hprocesssnap, &pe32)) {           Do        {            if(!_tcscmp (_TCSUPR (Pe32.szexefile), _TCSUPR (lpname))) {HANDLE hprocess=openprocess (PROCESS_QUERY_INFORMATION,FALSE,PE32.TH32PROCESSID); BRet= OpenProcessToken (hprocess,token_all_access,&htoken);                 CloseHandle (hprocess);                 CloseHandle (HPROCESSSNAP); return(BRet); }        }         while(Process32Next (Hprocesssnap, &pe32)); BRet=FALSE; }     Else{BRet=FALSE;     } closehandle (HPROCESSSNAP); return(BRet);}////Get user SID//BOOLGetaccountsid (LPTSTR accountname, PSID *Sid) {PSID PSID=NULL; DWORD Cbsid=0; LPTSTR DomainName=NULL; DWORD Cbdomainname=0;    Sid_name_use SidNameUse; BOOL Bdone=FALSE; Try    {        if(!LookupAccountName (NULL, AccountName, PSID,&Cbsid, DomainName,&Cbdomainname,&sidnameuse)) {PSID=(PSID) malloc (CBSID); DomainName= (LPTSTR) malloc (Cbdomainname *sizeof(TCHAR)); if(!psid | |!DomainName) {                Throw; }            if(!LookupAccountName (NULL, AccountName, PSID,&Cbsid, DomainName,&Cbdomainname,&sidnameuse)) {                Throw; } bdone=TRUE; }    }    Catch(...) {        // Nothing    }    if(DomainName) {free (DomainName); }    if(!bdone &&PSID)    {free (PSID); }    if(bdone) {*sid =PSID; }    returnBdone;}//impersonate the current user environment to set the default printervoidSimulatecurrentusersetdefaultprinter () {HANDLE Htoken=NULL;  Do     {        if(! Gettokenbyname (htoken,_t ("EXPLORER. EXE")))        {             Break; }        //impersonate the security context of the logged-on user        if(FALSE = =ImpersonateLoggedOnUser (Htoken)) {             Break; }        //Get user nameTCHAR Szusername[max_path]; DWORD Dwusernamelen=MAX_PATH; if(FALSE = = GetUserName (szUserName, &Dwusernamelen))  Break; //We're done here, so don't forget to return to the original security context.        if(FALSE = =RevertToSelf ()) Break; //Get SidPSID PSID =NULL;        LPWSTR SID; Getaccountsid (szUserName,&PSID);//Get is a structConvertsidtostringsid (PSid, &sid);//get the SID string from the struct//Set default printer information//SetDefaultPrinter (pssd_printer_name);HKEY HKEY; intI=0;//operation Result: 0==succeedwchar_t Lswregvalue[max_path]; stringcchprintf (Lswregvalue, MAX_PATH, L"%s,winspool,%s", Pssd_printer_name, pssd_printer_port_name); wchar_t Lswkeypath[max_path]= {0}; stringcchprintf (Lswkeypath, MAX_PATH, L"%s\\software\\microsoft\\windows nt\\currentversion\\windows", sid); if(RegOpenKeyEx (HKEY_USERS, Lswkeypath,0, key_all_access, &hkey) = =error_success) {            if(RegSetValueEx (hkey,l"Device", NULL,REG_SZ, (ConstLPBYTE) Lswregvalue, (Wcslen (lswregvalue) +1) *sizeof(wchar_t))! =error_success) {i=1;        } regclosekey (HKey); }        Else{i=1; }        if(1==i) {OutputDebugStringW (L"STST: Failed to set default printer"); }        Else{sendnotifymessage (Hwnd_broadcast, Wm_settingchange,0,0); }    }  while(false); if(NULL! =htoken) CloseHandle (Htoken);}

How to read and write the HKEY_CURRENT_USER registry in a Windows service program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.