MarinB MarinB - 2 years ago 160
C++ Question

Add application to startup via registry c++

I have a bit of a problem when I try to add my software to startup globally for all users. I have found a few examples here but they do not work for me.

Here is the sample code I found:

GetModuleFileName(NULL, szPath, MAX_PATH);

MessageBox(NULL, szPath, "application path", 0);

HKEY key;
RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &key);
RegSetValueEx(key, "potato", 0, REG_SZ, (LPBYTE)szPath, sizeof(szPath));

But it does not work.

Answer Source

If UAC is enabled and your app is not running with elevated rights, access to HKLM\Software is virtualized (see Registry Virtualization):

Prior to Windows Vista, applications were typically run by administrators. As a result, applications could freely access system files and registry keys. If these applications were run by a standard user, they would fail due to insufficient access rights. Windows Vista and later versions of Windows improve application compatibility for these applications by automatically redirecting these operations. For example, registry operations to the global store (HKEY_LOCAL_MACHINE\Software) are redirected to a per-user location within the user's profile known as the virtual store (HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software).


If the caller does not have write access to a key and attempts to write a value to it or create a subkey, the value is written to the virtual store.

For example, if a limited user attempts to write a value to the following key: HKEY_LOCAL_MACHINE\Software\AppKey1, virtualization redirects the write operation to HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software\AppKey1.


If the caller reads from a key that is virtualized, the registry presents a merged view of both the virtualized values (from the virtual store) and the non-virtual values (from the global store) to the caller.

For example, suppose HKEY_LOCAL_MACHINE\Software\AppKey1 contains two values V1 and V2 and that a limited user writes a value V3 to the key. When the user attempts to read values from this key, the merged view includes values V1 and V2 from the global store and value V3 from the virtual store.

This is backed by your claim that the Registry functions are returning 0 for success, but you are not seeing the values appear in the Registry. So, check if you are actually writing to this key (despite what the documentation says about virtualization being disabled for HKLM\Software\Microsoft\Windows):

HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Or even this key:

HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run

Always make sure your app is running with elevated permissions when accessing HKLM.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download