1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/registry.cpp
3 // Purpose: implementation of registry classes and functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 // TODO: - parsing of registry key names
11 // - support of other (than REG_SZ/REG_DWORD) registry types
12 // - add high level functions (RegisterOleServer, ...)
13 ///////////////////////////////////////////////////////////////////////////////
15 // for compilers that support precompilation, includes "wx.h".
16 #include "wx/wxprec.h"
23 #include "wx/msw/wrapwin.h"
24 #include "wx/string.h"
30 #include "wx/wfstream.h"
34 #include "wx/msw/private.h"
40 #include <stdlib.h> // for _MAX_PATH
47 #define HKEY_DEFINED // already defined in windows.h
48 #include "wx/msw/registry.h"
50 // some registry functions don't like signed chars
51 typedef unsigned char *RegString
;
52 typedef BYTE
* RegBinary
;
54 // ----------------------------------------------------------------------------
56 // ----------------------------------------------------------------------------
58 // the standard key names, short names and handles all bundled together for
64 const wxChar
*szShortName
;
68 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
69 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
70 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
71 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
73 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
75 #ifdef HKEY_CURRENT_CONFIG
76 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
79 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
83 // the registry name separator (perhaps one day MS will change it to '/' ;-)
84 #define REG_SEPARATOR wxT('\\')
86 // useful for Windows programmers: makes somewhat more clear all these zeroes
87 // being passed to Windows APIs
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 // const_cast<> is not yet supported by all compilers
95 #define CONST_CAST ((wxRegKey *)this)->
97 // and neither is mutable which m_dwLastError should be
98 #define m_dwLastError CONST_CAST m_dwLastError
100 // ----------------------------------------------------------------------------
101 // non member functions
102 // ----------------------------------------------------------------------------
104 // removes the trailing backslash from the string if it has one
105 static inline void RemoveTrailingSeparator(wxString
& str
);
107 // returns true if given registry key exists
108 static bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
);
110 // combines value and key name (uses static buffer!)
111 static const wxChar
*GetFullName(const wxRegKey
*pKey
,
112 const wxChar
*szValue
= NULL
);
114 // ============================================================================
115 // implementation of wxRegKey class
116 // ============================================================================
118 // ----------------------------------------------------------------------------
119 // static functions and variables
120 // ----------------------------------------------------------------------------
122 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
124 // @@ should take a `StdKey key', but as it's often going to be used in loops
125 // it would require casts in user code.
126 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
128 // return empty string if key is invalid
129 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
131 return aStdKeys
[key
].szName
;
134 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
136 // return empty string if key is invalid
137 wxCHECK( key
< nStdKeys
, wxEmptyString
);
139 return aStdKeys
[key
].szShortName
;
142 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
144 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
148 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
149 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
150 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
151 hRootKey
= aStdKeys
[ui
].hkey
;
156 if ( ui
== nStdKeys
) {
157 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
159 hRootKey
= HKEY_CLASSES_ROOT
;
162 strKey
= strKey
.After(REG_SEPARATOR
);
163 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
164 strKey
.Truncate(strKey
.Len() - 1);
167 return (wxRegKey::StdKey
)(int)hRootKey
;
170 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
172 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
173 if ( (int) aStdKeys
[ui
].hkey
== (int) hkey
)
177 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
182 // ----------------------------------------------------------------------------
184 // ----------------------------------------------------------------------------
188 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
193 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
195 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
200 // parent is a predefined (and preopened) key
201 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
203 RemoveTrailingSeparator(m_strKey
);
204 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
209 // parent is a normal regkey
210 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
211 : m_strKey(keyParent
.m_strKey
)
213 // combine our name with parent's to get the full name
214 if ( !m_strKey
.empty() &&
215 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
216 m_strKey
+= REG_SEPARATOR
;
220 RemoveTrailingSeparator(m_strKey
);
222 m_hRootKey
= keyParent
.m_hRootKey
;
227 // dtor closes the key releasing system resource
228 wxRegKey::~wxRegKey()
233 // ----------------------------------------------------------------------------
234 // change the key name/hkey
235 // ----------------------------------------------------------------------------
237 // set the full key name
238 void wxRegKey::SetName(const wxString
& strKey
)
243 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
246 // the name is relative to the parent key
247 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
252 RemoveTrailingSeparator(m_strKey
);
253 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
256 // the name is relative to the parent key
257 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
261 // combine our name with parent's to get the full name
263 // NB: this method is called by wxRegConfig::SetPath() which is a performance
264 // critical function and so it preallocates space for our m_strKey to
265 // gain some speed - this is why we only use += here and not = which
266 // would just free the prealloc'd buffer and would have to realloc it the
269 m_strKey
+= keyParent
.m_strKey
;
270 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
271 m_strKey
+= REG_SEPARATOR
;
274 RemoveTrailingSeparator(m_strKey
);
276 m_hRootKey
= keyParent
.m_hRootKey
;
279 // hKey should be opened and will be closed in wxRegKey dtor
280 void wxRegKey::SetHkey(WXHKEY hKey
)
287 // ----------------------------------------------------------------------------
288 // info about the key
289 // ----------------------------------------------------------------------------
291 // returns true if the key exists
292 bool wxRegKey::Exists() const
294 // opened key has to exist, try to open it if not done yet
295 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
);
298 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
299 wxString
wxRegKey::GetName(bool bShortPrefix
) const
301 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
302 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
303 : aStdKeys
[key
].szName
;
304 if ( !m_strKey
.empty() )
305 str
<< _T("\\") << m_strKey
;
310 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
313 size_t *pnMaxValueLen
) const
315 // old gcc headers incorrectly prototype RegQueryInfoKey()
316 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
317 #define REG_PARAM (size_t *)
319 #define REG_PARAM (LPDWORD)
322 // it might be unexpected to some that this function doesn't open the key
323 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
325 m_dwLastError
= ::RegQueryInfoKey
329 NULL
, // (ptr to) size of class name buffer
332 pnSubKeys
, // [out] number of subkeys
334 pnMaxKeyLen
, // [out] max length of a subkey name
335 NULL
, // longest subkey class name
337 pnValues
, // [out] number of values
339 pnMaxValueLen
, // [out] max length of a value name
340 NULL
, // longest value data
341 NULL
, // security descriptor
342 NULL
// time of last modification
347 if ( m_dwLastError
!= ERROR_SUCCESS
) {
348 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
356 // ----------------------------------------------------------------------------
358 // ----------------------------------------------------------------------------
360 // opens key (it's not an error to call Open() on an already opened key)
361 bool wxRegKey::Open(AccessMode mode
)
365 if ( mode
<= m_mode
)
368 // we had been opened in read mode but now must be reopened in write
373 m_dwLastError
= ::RegOpenKeyEx
378 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
382 if ( m_dwLastError
!= ERROR_SUCCESS
)
384 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
389 m_hKey
= (WXHKEY
) tmpKey
;
395 // creates key, failing if it exists and !bOkIfExists
396 bool wxRegKey::Create(bool bOkIfExists
)
398 // check for existence only if asked (i.e. order is important!)
399 if ( !bOkIfExists
&& Exists() )
408 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
,
410 NULL
, // class string
417 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
419 if ( m_dwLastError
!= ERROR_SUCCESS
) {
420 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
426 m_hKey
= (WXHKEY
) tmpKey
;
431 // close the key, it's not an error to call it when not opened
432 bool wxRegKey::Close()
435 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
438 if ( m_dwLastError
!= ERROR_SUCCESS
) {
439 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
449 bool wxRegKey::RenameValue(const wxChar
*szValueOld
, const wxChar
*szValueNew
)
452 if ( HasValue(szValueNew
) ) {
453 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
459 !CopyValue(szValueOld
, *this, szValueNew
) ||
460 !DeleteValue(szValueOld
) ) {
461 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
462 szValueOld
, szValueNew
);
470 bool wxRegKey::CopyValue(const wxChar
*szValue
,
472 const wxChar
*szValueNew
)
475 // by default, use the same name
476 szValueNew
= szValue
;
479 switch ( GetValueType(szValue
) ) {
483 return QueryValue(szValue
, strVal
) &&
484 keyDst
.SetValue(szValueNew
, strVal
);
488 /* case Type_Dword_little_endian: == Type_Dword */
491 return QueryValue(szValue
, &dwVal
) &&
492 keyDst
.SetValue(szValueNew
, dwVal
);
498 return QueryValue(szValue
,buf
) &&
499 keyDst
.SetValue(szValueNew
,buf
);
502 // these types are unsupported because I am not sure about how
503 // exactly they should be copied and because they shouldn't
504 // occur among the application keys (supposedly created with
507 case Type_Expand_String
:
508 case Type_Dword_big_endian
:
510 case Type_Multi_String
:
511 case Type_Resource_list
:
512 case Type_Full_resource_descriptor
:
513 case Type_Resource_requirements_list
:
515 wxLogError(_("Can't copy values of unsupported type %d."),
516 GetValueType(szValue
));
521 bool wxRegKey::Rename(const wxChar
*szNewName
)
523 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
526 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
532 // do we stay in the same hive?
533 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
535 // construct the full new name of the key
539 // rename the key to the new name under the same parent
540 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
541 if ( !strKey
.empty() ) {
542 // don't add '\\' in the start if strFullNewName is empty
543 strKey
+= REG_SEPARATOR
;
548 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
551 // this is the full name already
552 keyDst
.SetName(szNewName
);
555 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
557 wxLogError(_("Registry key '%s' already exists."),
558 GetFullName(&keyDst
));
561 ok
= Copy(keyDst
) && DeleteSelf();
565 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
566 GetFullName(this), GetFullName(&keyDst
));
569 m_hRootKey
= keyDst
.m_hRootKey
;
570 m_strKey
= keyDst
.m_strKey
;
576 bool wxRegKey::Copy(const wxChar
*szNewName
)
578 // create the new key first
579 wxRegKey
keyDst(szNewName
);
580 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
584 // we created the dest key but copying to it failed - delete it
586 (void)keyDst
.DeleteSelf();
593 bool wxRegKey::Copy(wxRegKey
& keyDst
)
597 // copy all sub keys to the new location
600 bool bCont
= GetFirstKey(strKey
, lIndex
);
601 while ( ok
&& bCont
) {
602 wxRegKey
key(*this, strKey
);
604 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
605 ok
= key
.Copy((const wxChar
*) keyName
);
608 bCont
= GetNextKey(strKey
, lIndex
);
610 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
611 GetFullName(&key
), keyName
.c_str());
617 bCont
= GetFirstValue(strVal
, lIndex
);
618 while ( ok
&& bCont
) {
619 ok
= CopyValue(strVal
, keyDst
);
622 wxLogSysError(m_dwLastError
,
623 _("Failed to copy registry value '%s'"),
627 bCont
= GetNextValue(strVal
, lIndex
);
632 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
633 GetFullName(this), GetFullName(&keyDst
));
639 // ----------------------------------------------------------------------------
640 // delete keys/values
641 // ----------------------------------------------------------------------------
642 bool wxRegKey::DeleteSelf()
647 // it already doesn't exist - ok!
652 // prevent a buggy program from erasing one of the root registry keys or an
653 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
654 // key except HKCR (HKCR has some "deleteable" subkeys)
655 if ( m_strKey
.empty() ||
656 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
657 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
658 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
664 // we can't delete keys while enumerating because it confuses GetNextKey, so
665 // we first save the key names and then delete them all
666 wxArrayString astrSubkeys
;
670 bool bCont
= GetFirstKey(strKey
, lIndex
);
672 astrSubkeys
.Add(strKey
);
674 bCont
= GetNextKey(strKey
, lIndex
);
677 size_t nKeyCount
= astrSubkeys
.Count();
678 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
679 wxRegKey
key(*this, astrSubkeys
[nKey
]);
680 if ( !key
.DeleteSelf() )
684 // now delete this key itself
687 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
688 // deleting a key which doesn't exist is not considered an error
689 if ( m_dwLastError
!= ERROR_SUCCESS
&&
690 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
691 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
699 bool wxRegKey::DeleteKey(const wxChar
*szKey
)
704 wxRegKey
key(*this, szKey
);
705 return key
.DeleteSelf();
708 bool wxRegKey::DeleteValue(const wxChar
*szValue
)
713 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, WXSTRINGCAST szValue
);
715 // deleting a value which doesn't exist is not considered an error
716 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
717 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
719 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
720 szValue
, GetName().c_str());
727 // ----------------------------------------------------------------------------
728 // access to values and subkeys
729 // ----------------------------------------------------------------------------
731 // return true if value exists
732 bool wxRegKey::HasValue(const wxChar
*szValue
) const
734 // this function should be silent, so suppress possible messages from Open()
737 if ( !CONST_CAST
Open(Read
) )
740 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
741 WXSTRINGCAST szValue
,
744 return dwRet
== ERROR_SUCCESS
;
747 // returns true if this key has any values
748 bool wxRegKey::HasValues() const
750 // suppress possible messages from GetFirstValue()
753 // just call GetFirstValue with dummy parameters
756 return CONST_CAST
GetFirstValue(str
, l
);
759 // returns true if this key has any subkeys
760 bool wxRegKey::HasSubkeys() const
762 // suppress possible messages from GetFirstKey()
765 // just call GetFirstKey with dummy parameters
768 return CONST_CAST
GetFirstKey(str
, l
);
771 // returns true if given subkey exists
772 bool wxRegKey::HasSubKey(const wxChar
*szKey
) const
774 // this function should be silent, so suppress possible messages from Open()
777 if ( !CONST_CAST
Open(Read
) )
780 return KeyExists(m_hKey
, szKey
);
783 wxRegKey::ValueType
wxRegKey::GetValueType(const wxChar
*szValue
) const
785 if ( ! CONST_CAST
Open(Read
) )
789 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
790 &dwType
, NULL
, NULL
);
791 if ( m_dwLastError
!= ERROR_SUCCESS
) {
792 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
797 return (ValueType
)dwType
;
800 bool wxRegKey::SetValue(const wxChar
*szValue
, long lValue
)
802 if ( CONST_CAST
Open() ) {
803 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
804 (RegString
)&lValue
, sizeof(lValue
));
805 if ( m_dwLastError
== ERROR_SUCCESS
)
809 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
810 GetFullName(this, szValue
));
814 bool wxRegKey::QueryValue(const wxChar
*szValue
, long *plValue
) const
816 if ( CONST_CAST
Open(Read
) ) {
817 DWORD dwType
, dwSize
= sizeof(DWORD
);
818 RegString pBuf
= (RegString
)plValue
;
819 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
820 &dwType
, pBuf
, &dwSize
);
821 if ( m_dwLastError
!= ERROR_SUCCESS
) {
822 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
827 // check that we read the value of right type
828 wxASSERT_MSG( IsNumericValue(szValue
),
829 wxT("Type mismatch in wxRegKey::QueryValue().") );
838 bool wxRegKey::SetValue(const wxChar
*szValue
,const wxMemoryBuffer
& buffer
)
841 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
844 if ( CONST_CAST
Open() ) {
845 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_BINARY
,
846 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
847 if ( m_dwLastError
== ERROR_SUCCESS
)
851 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
852 GetFullName(this, szValue
));
857 bool wxRegKey::QueryValue(const wxChar
*szValue
, wxMemoryBuffer
& buffer
) const
859 if ( CONST_CAST
Open(Read
) ) {
860 // first get the type and size of the data
861 DWORD dwType
, dwSize
;
862 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
863 &dwType
, NULL
, &dwSize
);
865 if ( m_dwLastError
== ERROR_SUCCESS
) {
867 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
868 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
869 WXSTRINGCAST szValue
,
874 buffer
.UngetWriteBuf(dwSize
);
876 buffer
.SetDataLen(0);
881 if ( m_dwLastError
!= ERROR_SUCCESS
) {
882 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
893 bool wxRegKey::QueryValue(const wxChar
*szValue
,
895 bool WXUNUSED_IN_WINCE(raw
)) const
897 if ( CONST_CAST
Open(Read
) )
900 // first get the type and size of the data
901 DWORD dwType
=REG_NONE
, dwSize
=0;
902 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
903 &dwType
, NULL
, &dwSize
);
904 if ( m_dwLastError
== ERROR_SUCCESS
)
908 // must treat this case specially as GetWriteBuf() doesn't like
909 // being called with 0 size
914 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
915 WXSTRINGCAST szValue
,
918 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
921 // expand the var expansions in the string unless disabled
923 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
925 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
, NULL
, 0);
926 bool ok
= dwExpSize
!= 0;
929 wxString strExpValue
;
930 ok
= ::ExpandEnvironmentStrings(strValue
,
931 wxStringBuffer(strExpValue
, dwExpSize
),
934 strValue
= strExpValue
;
939 wxLogLastError(_T("ExpandEnvironmentStrings"));
946 if ( m_dwLastError
== ERROR_SUCCESS
)
948 // check that it was the right type
949 wxASSERT_MSG( !IsNumericValue(szValue
),
950 wxT("Type mismatch in wxRegKey::QueryValue().") );
957 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
958 GetFullName(this, szValue
));
962 bool wxRegKey::SetValue(const wxChar
*szValue
, const wxString
& strValue
)
964 if ( CONST_CAST
Open() ) {
965 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
966 (RegString
)strValue
.c_str(),
967 (strValue
.Len() + 1)*sizeof(wxChar
));
968 if ( m_dwLastError
== ERROR_SUCCESS
)
972 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
973 GetFullName(this, szValue
));
977 wxString
wxRegKey::QueryDefaultValue() const
980 QueryValue(NULL
, str
);
984 // ----------------------------------------------------------------------------
986 // NB: all these functions require an index variable which allows to have
987 // several concurrently running indexations on the same key
988 // ----------------------------------------------------------------------------
990 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
996 return GetNextValue(strValueName
, lIndex
);
999 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1001 wxASSERT( IsOpened() );
1003 // are we already at the end of enumeration?
1007 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1008 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1010 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1011 szValueName
, &dwValueLen
,
1014 NULL
, // [out] buffer for value
1015 NULL
); // [i/o] it's length
1017 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1018 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1019 m_dwLastError
= ERROR_SUCCESS
;
1023 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1030 strValueName
= szValueName
;
1035 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1041 return GetNextKey(strKeyName
, lIndex
);
1044 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1046 wxASSERT( IsOpened() );
1048 // are we already at the end of enumeration?
1052 wxChar szKeyName
[_MAX_PATH
+ 1];
1055 DWORD sizeName
= WXSIZEOF(szKeyName
);
1056 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1057 0, NULL
, NULL
, NULL
);
1059 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1062 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1063 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1064 m_dwLastError
= ERROR_SUCCESS
;
1068 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1075 strKeyName
= szKeyName
;
1079 // returns true if the value contains a number (else it's some string)
1080 bool wxRegKey::IsNumericValue(const wxChar
*szValue
) const
1082 ValueType type
= GetValueType(szValue
);
1085 /* case Type_Dword_little_endian: == Type_Dword */
1086 case Type_Dword_big_endian
:
1094 // ----------------------------------------------------------------------------
1095 // exporting registry keys to file
1096 // ----------------------------------------------------------------------------
1100 // helper functions for writing ASCII strings (even in Unicode build)
1101 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1107 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1109 // as we open the file in text mode, it is enough to write LF without CR
1110 return WriteAsciiChar(ostr
, '\n');
1113 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1115 return ostr
.Write(p
, strlen(p
)).IsOk();
1118 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1121 wxCharBuffer
name(s
.mb_str());
1122 ostr
.Write(name
, strlen(name
));
1124 ostr
.Write(s
, s
.length());
1130 #endif // wxUSE_STREAMS
1132 bool wxRegKey::Export(const wxString
& filename
) const
1134 #if wxUSE_FFILE && wxUSE_STREAMS
1135 if ( wxFile::Exists(filename
) )
1137 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1142 wxFFileOutputStream
ostr(filename
, _T("w"));
1144 return ostr
.Ok() && Export(ostr
);
1146 wxUnusedVar(filename
);
1152 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1154 // write out the header
1155 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1158 return DoExport(ostr
);
1160 #endif // wxUSE_STREAMS
1164 FormatAsHex(const void *data
,
1166 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1168 wxString
value(_T("hex"));
1170 // binary values use just "hex:" prefix while the other ones must indicate
1172 if ( type
!= wxRegKey::Type_Binary
)
1173 value
<< _T('(') << type
<< _T(')');
1176 // write all the rest as comma-separated bytes
1177 value
.reserve(3*size
+ 10);
1178 const char * const p
= wx_static_cast(const char *, data
);
1179 for ( size_t n
= 0; n
< size
; n
++ )
1181 // TODO: line wrapping: although not required by regedit, this makes
1182 // the generated files easier to read and compare with the files
1183 // produced by regedit
1187 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1194 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1196 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1199 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1202 const ValueType type
= GetValueType(name
);
1208 if ( !QueryValue(name
, value
) )
1211 // quotes and backslashes must be quoted, linefeeds are not
1212 // allowed in string values
1213 rhs
.reserve(value
.length() + 2);
1216 // there can be no NULs here
1217 bool useHex
= false;
1218 for ( const wxChar
*p
= value
.c_str(); *p
&& !useHex
; p
++ )
1223 // we can only represent this string in hex
1229 // escape special symbol
1239 rhs
= FormatAsHex(value
, Type_String
);
1246 /* case Type_Dword_little_endian: == Type_Dword */
1249 if ( !QueryValue(name
, &value
) )
1252 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1256 case Type_Expand_String
:
1257 case Type_Multi_String
:
1260 if ( !QueryRawValue(name
, value
) )
1263 rhs
= FormatAsHex(value
, type
);
1270 if ( !QueryValue(name
, buf
) )
1273 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1277 // no idea how those appear in REGEDIT4 files
1279 case Type_Dword_big_endian
:
1281 case Type_Resource_list
:
1282 case Type_Full_resource_descriptor
:
1283 case Type_Resource_requirements_list
:
1285 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1293 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1295 // first examine the value type: if it's unsupported, simply skip it
1296 // instead of aborting the entire export process because we failed to
1297 // export a single value
1298 wxString value
= FormatValue(name
);
1299 if ( value
.empty() )
1301 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1302 name
.c_str(), GetName().c_str());
1306 // we do have the text representation of the value, now write everything
1309 // special case: unnamed/default value is represented as just "@"
1312 if ( !WriteAsciiChar(ostr
, '@') )
1315 else // normal, named, value
1317 if ( !WriteAsciiChar(ostr
, '"') ||
1318 !WriteAsciiString(ostr
, name
) ||
1319 !WriteAsciiChar(ostr
, '"') )
1323 if ( !WriteAsciiChar(ostr
, '=') )
1326 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1329 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1331 // write out this key name
1332 if ( !WriteAsciiChar(ostr
, '[') )
1335 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1338 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1341 // dump all our values
1344 wxRegKey
& self
= wx_const_cast(wxRegKey
&, *this);
1345 bool cont
= self
.GetFirstValue(name
, dummy
);
1348 if ( !DoExportValue(ostr
, name
) )
1351 cont
= GetNextValue(name
, dummy
);
1354 // always terminate values by blank line, even if there were no values
1355 if ( !WriteAsciiEOL(ostr
) )
1358 // recurse to subkeys
1359 cont
= self
.GetFirstKey(name
, dummy
);
1362 wxRegKey
subkey(*this, name
);
1363 if ( !subkey
.DoExport(ostr
) )
1366 cont
= GetNextKey(name
, dummy
);
1372 #endif // wxUSE_STREAMS
1374 // ============================================================================
1375 // implementation of global private functions
1376 // ============================================================================
1378 bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
)
1380 // don't close this key itself for the case of empty szKey!
1381 if ( wxIsEmpty(szKey
) )
1390 KEY_READ
, // we might not have enough rights for rw access
1392 ) == ERROR_SUCCESS
)
1394 ::RegCloseKey(hkeyDummy
);
1402 const wxChar
*GetFullName(const wxRegKey
*pKey
, const wxChar
*szValue
)
1404 static wxString s_str
;
1405 s_str
= pKey
->GetName();
1406 if ( !wxIsEmpty(szValue
) )
1407 s_str
<< wxT("\\") << szValue
;
1409 return s_str
.c_str();
1412 void RemoveTrailingSeparator(wxString
& str
)
1414 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1415 str
.Truncate(str
.Len() - 1);