Saturday 4 October 2008

By 'eck, they don't half make it difficult sometimes...

Progress has been slow, between two many DIY jobs and to much work at work, Lizard 0.3 is proving a bit hard to get out. One of the reasons is that I'm not much of a c++ programmer, or rather I'm not use to unravelling c++ documentation/examples on the internet.

What follows will probably be of little interest to anyone except those from c# (or VB, or Delphi etc) background who are trying to find their feet with c++ and COM.

I wanted to read the location of the Lizard meta-data folder from the registry (it's been hard-coded up till now). I quickly found I needed the CRegKey.Open and CRegKey.QueryStringValue methods, but wanted to see some examples to see how they really worked. After spending way too much time reading 163 different variations on a theme, I wrote my own based on this article from the Geak Technologies web site (thanks chaps, who ever you are). The problem I have with c++ examples and tutorials is they hardly ever show all the #includes you need or which libraries you need to add to the linker, and of course, it being c++, always disagree with what sort of string to use. Always use CString! std::string is superior! Real programmers use... etc etc. Some forums had posters getting quite angry that someone suggested the 'wrong' sort of strings for this or that, but I'm guessing from the multitude of opinions that there isn't just one (or even two or three) right way.
My extensions use CComBSTR a lot, this will probably make a lot of people purple with rage, but they seem to be the easiest if you want to interact with COM objects and are using ATL.
Any way, for any one who got here because they searched for 'c++ Registry Access, Key, Path'
here is some code:

#include "stdafx.h"
#include


using namespace ATL;

#include "RegistryAccess.h"

CComBSTR GetRegistryKeyValue(CComBSTR regKey, CComBSTR valueName)
{
CRegKey key;
CComBSTR value="";
long nError = key.Open(HKEY_CURRENT_USER, regKey.m_str, KEY_READ);
if(nError == ERROR_SUCCESS)
{
DWORD dwBufferSize = MAX_PATH;
LPTSTR v = new TCHAR[MAX_PATH];
key.QueryStringValue(valueName.m_str, v , &dwBufferSize );
value.Append(v,dwBufferSize);
}
return value;
}

If you're writing an ATL based project then #include might well already be in your 'stdafx.h' but I wanted to include it here because it defines CComBSTR and CRegKey. This code works but really didn't warrant two hours of my life.

Yeah, I know I should get a good book and learn this stuff properly, know what the relationship between a LPCTSTR and a *PCH is, and memorise every typedef in every .h file in the c++ sdk, but that is for another day.

Let the flaming begin!

No comments: