Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a value from the registry C++

Tags:

c++

registry

I want to get the path of where an application is installed. In the registry, there is an entry which gives the path of my application, see this screenshot: http://i56.tinypic.com/2ly1l6s.jpg

I want to read the path where my application is located. In other words, I want the C:\Projects\MyApplication\MyApplication.exe part. Here is what I am trying to do:

HKEY hKey;
wchar_t mydata[2048];
DWORD dataLength = sizeof(mydata);
DWORD dwType = REG_SZ;
LPVOID messagecaliss;
LONG regOpenCriss = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", 0, KEY_QUERY_VALUE, &hKey);
GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, GetLastError(), NULL,(LPTSTR) &messagecaliss, 0, NULL );
if (regOpenCriss == ERROR_SUCCESS) {
RegQueryValueEx(HKEY_CURRENT_USER, "TestApplication", 0, &dwType, (BYTE*)mydata, &dataLength);
wprintf(L"%s\n", mydata);
system("PAUSE");
}
else
    MessageBox(NULL,(LPCTSTR)messagecaliss,"ERROR",MB_OK|MB_ICONINFORMATION);

This doesn't work, junk characters are printed. Thank you very much.

like image 810
jack excell Avatar asked Jun 12 '11 21:06

jack excell


3 Answers

you're using non-UNICODE version o RegQueryValueEx and you're diplaying it with wide-char version of printf. Use either printf or change to wprintf( L"%S" ,mydata )

Note : RegQueryValueEx(HKEY_CURRENT_USER ,... ) must be RegQueryValueEx( hKey ,... )

like image 137
engf-010 Avatar answered Sep 25 '22 18:09

engf-010


I got results after:

  1. I surround the strings with _T()
  2. I call RegQueryValueEx with hKey as the first parameter

You should store the result of RegQueryValueEx in a variable and check it. Handle the failure case...

like image 44
Andrei Avatar answered Sep 25 '22 18:09

Andrei


This doesn't work

How do you know that without checking the return value of RegQueryValueEx?

junk characters are printed

No. It's not junk. You didn't ask for a wide character string, so you cannot expect to get one. Compile with Unicode enabled and call RegQueryValueEx with L"TestApplication" or _T("TestApplication") or TEXT("TestApplication"). RegQueryValueEx is just a typedef for RegQueryValueExA or RegQueryValueExW, depending on whether Unicode is defined during compile time or not.

Thank you very much

You're welcome.

like image 44
Johann Gerell Avatar answered Sep 25 '22 18:09

Johann Gerell