Search code examples
c++registrycommandsystemediting

Changing a registry value with C++? (system command failed)


Well, I have been told time and time again that system command is bad, but I need to change a registry value and my forte is batch so I have a commmand in mind that does it:

system("REG ADD "HKCU\Control Panel\Desktop" /V Wallpaper /T REG_SZ /F /D "C:\background.bmp"");
system("REG ADD "HKCU\Control Panel\Desktop" /V WallpaperStyle /T REG_SZ /F /D 0");
system("REG ADD "HKCU\Control Panel\Desktop" /V TileWallpaper /T REG_SZ /F /D 2");
system("%SystemRoot%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");

However, using this makes Visual C++ 2010 Express highlight HKCU and the slash betweeen Panel and Desktop as an error and does not allow me to compile or debug my program. I don't want to use the system command so I was wondering how to use a C++ to preform the same registry command? I DON'T UNDERSTAND WIN32 REGISTRY API???

And is it ok to use the system command for this

system("%SystemRoot%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");

because I don't know if C++ can preform the same task without it, and if it can how???

Sorry, I know it's a big question but if possible could you please include code, I am just beginning and none of the other forums make any sense and I have been looking for atlease three hours (I am not stupid with computers either)!!!

Thanks in advance


Solution

  • Some extra work is needed to write string literals that contain special characters. For example, in your code, the " after ADD is the end of the string.

    You need to put a backspace before each special character (includes quotes and backspaces) to make sure they are put into the string instead of being processed by the compiler. This is called escaping.

    The result will look like this:

    system("REG ADD \"HKCU\\Control Panel\\Desktop\" /V Wallpaper /T REG_SZ /F /D \"C:\\background.bmp\"");
    

    Using the Registry API is a better option for your task, of course, but you also needed to know how to write string literals properly.