Home > Software design >  How to give argument to write registry?
How to give argument to write registry?

Time:10-21

I wrote the code below to edit a registry value:

#include <windows.h>
#include <string.h>

int main(int argc, char* argv[]) {
  HKEY hkey = NULL;

  const char* evtwvr = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Event Viewer";
  const char* exepath = "file://C:\\Users\\MrUser\\Desktop\\temp.exe;

  LONG rgdt = RegOpenKeyEx(HKEY_LOCAL_MACHINE, (LPCSTR)evtwvr, 0 , KEY_WRITE, &hkey);
  if (rgdt == ERROR_SUCCESS) {
    RegSetValueEx(hkey, (LPCSTR)"MicrosoftRedirectionUrl", 0, REG_SZ, (unsigned char*)exepath, strlen(exepath));
    RegCloseKey(hkey);
  }

  return 0;
}

It simple edits the registry key and writes the exe path as a value.

But I want to do it like this:

myprogram.exe C:\Users\User\MrUser\temp.exe

and pass the input parameter into the registry value.

CodePudding user response:

Simply replace exepath with argv[1] instead.

Also, your LPCSTR casts are unnecessary. And you need to add 1 to strlen() because REG_SZ requires the string's null terminator to be written.

#include <windows.h>
#include <string.h>

int main(int argc, char* argv[]) {

  if (argc < 2) return 1;

  const char* evtwvr = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Event Viewer";

  HKEY hkey = NULL;
  LONG rgdt = RegOpenKeyExA(HKEY_LOCAL_MACHINE, evtwvr, 0, KEY_SET_VALUE, &hkey);
  if (rgdt == ERROR_SUCCESS) {
    RegSetValueExA(hkey, "MicrosoftRedirectionUrl", 0, REG_SZ, (LPBYTE)argv[1], strlen(argv[1]) 1);
    RegCloseKey(hkey);
  }

  return 0;
}

That being said, since you want to use a command line parameter to edit the Registry, you could just use Windows built-in reg command instead, eg:

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Event Viewer" /v MicrosoftRedirectionUrl /t REG_SZ /d "C:\Users\User\MrUser\temp.exe" /f
  • Related