Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a key value of Registry and print it to the screen with the MessageBox()

Tags:

c++

winapi

I'm new to C++ and to WinCe developing.

I want to read a string from the registry and display with the MessageBox(). I have tried the following.

HKEY key;
if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\SiRFStar3HW"), 0, KEY_READ, &key) != ERROR_SUCCESS)
{
    MessageBox(NULL,L"Can't open the registry!",L"Error",MB_OK);
}
char value[5];
DWORD value_length=5;
DWORD type=REG_SZ;
RegQueryValueEx(key,(LPCTSTR)"Baud", NULL, &type, (LPBYTE)&value, &value_length);
wchar_t buffer[5];
_stprintf(buffer, _T("%i"), value);

::MessageBox(NULL,buffer,L"Value:",MB_OK);

::RegCloseKey(key);

So I know somethings wrong in here, but how can I solve?

like image 820
Luther Avatar asked May 20 '12 17:05

Luther


People also ask

How do I read registry values?

Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.

How do you locate keys and their values in the registry?

Regedit lets you search using the Find feature in the Windows Registry. To access it, you have to click on Edit menu and select Find. The Find box will let you search for items in the Windows Registry, and this includes Keys, Values, and Data. You can also set it to match whole strings only.

What is a registry key value?

Registry values are name/data pairs stored within keys. Registry values are referenced separately from registry keys. Each registry value stored in a registry key has a unique name whose letter case is not significant.


2 Answers

Navigating the Win32 API can be a tricky business. The registry APIs are some of the more complicated. Here's a short program to demonstrate how to read a registry string.

#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

wstring ReadRegValue(HKEY root, wstring key, wstring name)
{
    HKEY hKey;
    if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
        throw "Could not open registry key";

    DWORD type;
    DWORD cbData;
    if (RegQueryValueEx(hKey, name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    if (type != REG_SZ)
    {
        RegCloseKey(hKey);
        throw "Incorrect registry value type";
    }

    wstring value(cbData/sizeof(wchar_t), L'\0');
    if (RegQueryValueEx(hKey, name.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&value[0]), &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    RegCloseKey(hKey);

    size_t firstNull = value.find_first_of(L'\0');
    if (firstNull != string::npos)
        value.resize(firstNull);

    return value;
}

int wmain(int argc, wchar_t* argv[])
{
    wcout << ReadRegValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", L"CommonFilesDir");
    return 0;
}

Notes:

  1. I don't have CE so this is a plain Win32 app, compiled for Unicode. I took that route because CE doesn't do ANSI characters.
  2. I've taken advantage of a number of C++ features. Most significantly std::wstring. This makes string handling a cinch.
  3. I've used exceptions for error handling. You could replace that with some other mechanism, but it served my purpose of keeping the error handling issues in the background.
  4. Using exceptions makes closing the registry key slightly messy. A better solution would be to use an RAII class to wrap up the lifetime of the registry key. I've omitted that for simplicity, but in production code you would want to take that extra step.
  5. Usually, RegQueryValueEx returns REG_SZ data that is null-terminated. This code deals with that by truncating beyond the first null character. In case the value returned is not null-terminated, that truncation won't happen, but the value will still be fine.
  6. I've just printed to my console, but it would be trivial for you to call MessageBox. Like this: MessageBox(0, value.c_str(), L"Caption", MB_OK)
like image 153
David Heffernan Avatar answered Oct 24 '22 16:10

David Heffernan


Here is a complete source code to read a key value of Registry and print it to the screen:

//Create C++ Win32 Project in Visual Studio
//Project -> "project" Properties->Configuration Properties->C/C++->Advanced->Show Includes : YES(/ showIncludes)
//Project -> "project" Properties->Configuration Properties->General->Project Defaults->Use of MFC : Use MFC in a shared DLL
#include <iostream>
#include <afx.h>
using namespace std;

int ReadRegistryKeyAttributes(CString ConstantKeyPath)
{
    //Here ConstantKeyPath is considered as Registry Key Path to Read
    HKEY MyRegistryKey;
    if (RegOpenKeyEx(HKEY_CURRENT_USER, ConstantKeyPath, 0, KEY_READ, &MyRegistryKey) != ERROR_SUCCESS)
    {
        cout << "KeyOpen Failed" << endl;
        return -1;
    }


    DWORD type = REG_DWORD;
    DWORD cbData;
    unsigned long size = 1024;
    CString csVersionID;

    csVersionID = _T("VersionID"); //Here VersionID is considered as Name of the Key
    if (RegQueryValueEx(MyRegistryKey, csVersionID, NULL, &type, (LPBYTE)&cbData, &size) != ERROR_SUCCESS)
    {
        RegCloseKey(MyRegistryKey);
        cout << "VersionID Key Attribute Reading Failed" << endl;
        return -1; //Error
    }
    else
    {
        cout << "VersionID = " << cbData << endl; //Key value will be printed here.
    }
    return 1; //Success
}
int main()
{
    int iResult;
    CString KeyPath = _T("Software\\RCD_Technologies\\Rajib_Test");
    iResult = ReadRegistryKeyAttributes(KeyPath);
    if (iResult < 0)
    {
        cout << "ReadRegistryKeyAttributes operation Failed" << endl;
        return -1;
    }
    cout << "<--- ReadRegistryKeyAttribute Operation Successfull -->" << endl;
    getchar();
    return 0;
}

Hope this example will be helpful who are seeking this problem.

like image 41
RajibTheKing Avatar answered Oct 24 '22 16:10

RajibTheKing