Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to give argument to write registry?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

and pass the input parameter into the registry value.

>Solution :

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 null terminator to be written.

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

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

  if (argc < 2) return 0;

  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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading