1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
16 #pragma implementation "registry.h"
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 // other wxWidgets headers
27 #include "wx/string.h"
31 #include "wx/wfstream.h"
34 #include "wx/msw/wrapwin.h"
37 #include "wx/msw/private.h"
43 #include <stdlib.h> // for _MAX_PATH
50 #define HKEY_DEFINED // already defined in windows.h
51 #include "wx/msw/registry.h"
53 // some registry functions don't like signed chars
54 typedef unsigned char *RegString
;
55 typedef BYTE
* RegBinary
;
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
61 // the standard key names, short names and handles all bundled together for
67 const wxChar
*szShortName
;
71 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
72 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
73 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
74 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
76 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
78 #ifdef HKEY_CURRENT_CONFIG
79 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
82 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
86 // the registry name separator (perhaps one day MS will change it to '/' ;-)
87 #define REG_SEPARATOR wxT('\\')
89 // useful for Windows programmers: makes somewhat more clear all these zeroes
90 // being passed to Windows APIs
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 // const_cast<> is not yet supported by all compilers
98 #define CONST_CAST ((wxRegKey *)this)->
100 // and neither is mutable which m_dwLastError should be
101 #define m_dwLastError CONST_CAST m_dwLastError
103 // ----------------------------------------------------------------------------
104 // non member functions
105 // ----------------------------------------------------------------------------
107 // removes the trailing backslash from the string if it has one
108 static inline void RemoveTrailingSeparator(wxString
& str
);
110 // returns true if given registry key exists
111 static bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
);
113 // combines value and key name (uses static buffer!)
114 static const wxChar
*GetFullName(const wxRegKey
*pKey
,
115 const wxChar
*szValue
= NULL
);
117 // ============================================================================
118 // implementation of wxRegKey class
119 // ============================================================================
121 // ----------------------------------------------------------------------------
122 // static functions and variables
123 // ----------------------------------------------------------------------------
125 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
127 // @@ should take a `StdKey key', but as it's often going to be used in loops
128 // it would require casts in user code.
129 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
131 // return empty string if key is invalid
132 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
134 return aStdKeys
[key
].szName
;
137 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
139 // return empty string if key is invalid
140 wxCHECK( key
< nStdKeys
, wxEmptyString
);
142 return aStdKeys
[key
].szShortName
;
145 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
147 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
151 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
152 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
153 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
154 hRootKey
= aStdKeys
[ui
].hkey
;
159 if ( ui
== nStdKeys
) {
160 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
162 hRootKey
= HKEY_CLASSES_ROOT
;
165 strKey
= strKey
.After(REG_SEPARATOR
);
166 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
167 strKey
.Truncate(strKey
.Len() - 1);
170 return (wxRegKey::StdKey
)(int)hRootKey
;
173 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
175 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
176 if ( (int) aStdKeys
[ui
].hkey
== (int) hkey
)
180 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
185 // ----------------------------------------------------------------------------
187 // ----------------------------------------------------------------------------
191 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
196 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
198 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
203 // parent is a predefined (and preopened) key
204 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
206 RemoveTrailingSeparator(m_strKey
);
207 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
212 // parent is a normal regkey
213 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
214 : m_strKey(keyParent
.m_strKey
)
216 // combine our name with parent's to get the full name
217 if ( !m_strKey
.empty() &&
218 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
219 m_strKey
+= REG_SEPARATOR
;
223 RemoveTrailingSeparator(m_strKey
);
225 m_hRootKey
= keyParent
.m_hRootKey
;
230 // dtor closes the key releasing system resource
231 wxRegKey::~wxRegKey()
236 // ----------------------------------------------------------------------------
237 // change the key name/hkey
238 // ----------------------------------------------------------------------------
240 // set the full key name
241 void wxRegKey::SetName(const wxString
& strKey
)
246 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
249 // the name is relative to the parent key
250 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
255 RemoveTrailingSeparator(m_strKey
);
256 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
259 // the name is relative to the parent key
260 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
264 // combine our name with parent's to get the full name
266 // NB: this method is called by wxRegConfig::SetPath() which is a performance
267 // critical function and so it preallocates space for our m_strKey to
268 // gain some speed - this is why we only use += here and not = which
269 // would just free the prealloc'd buffer and would have to realloc it the
272 m_strKey
+= keyParent
.m_strKey
;
273 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
274 m_strKey
+= REG_SEPARATOR
;
277 RemoveTrailingSeparator(m_strKey
);
279 m_hRootKey
= keyParent
.m_hRootKey
;
282 // hKey should be opened and will be closed in wxRegKey dtor
283 void wxRegKey::SetHkey(WXHKEY hKey
)
290 // ----------------------------------------------------------------------------
291 // info about the key
292 // ----------------------------------------------------------------------------
294 // returns true if the key exists
295 bool wxRegKey::Exists() const
297 // opened key has to exist, try to open it if not done yet
298 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
);
301 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
302 wxString
wxRegKey::GetName(bool bShortPrefix
) const
304 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
305 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
306 : aStdKeys
[key
].szName
;
307 if ( !m_strKey
.empty() )
308 str
<< _T("\\") << m_strKey
;
313 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
316 size_t *pnMaxValueLen
) const
318 // old gcc headers incorrectly prototype RegQueryInfoKey()
319 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
320 #define REG_PARAM (size_t *)
322 #define REG_PARAM (LPDWORD)
325 // it might be unexpected to some that this function doesn't open the key
326 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
328 m_dwLastError
= ::RegQueryInfoKey
332 NULL
, // (ptr to) size of class name buffer
335 pnSubKeys
, // [out] number of subkeys
337 pnMaxKeyLen
, // [out] max length of a subkey name
338 NULL
, // longest subkey class name
340 pnValues
, // [out] number of values
342 pnMaxValueLen
, // [out] max length of a value name
343 NULL
, // longest value data
344 NULL
, // security descriptor
345 NULL
// time of last modification
350 if ( m_dwLastError
!= ERROR_SUCCESS
) {
351 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
359 // ----------------------------------------------------------------------------
361 // ----------------------------------------------------------------------------
363 // opens key (it's not an error to call Open() on an already opened key)
364 bool wxRegKey::Open(AccessMode mode
)
368 if ( mode
<= m_mode
)
371 // we had been opened in read mode but now must be reopened in write
376 m_dwLastError
= ::RegOpenKeyEx
381 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
385 if ( m_dwLastError
!= ERROR_SUCCESS
)
387 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
392 m_hKey
= (WXHKEY
) tmpKey
;
398 // creates key, failing if it exists and !bOkIfExists
399 bool wxRegKey::Create(bool bOkIfExists
)
401 // check for existence only if asked (i.e. order is important!)
402 if ( !bOkIfExists
&& Exists() )
411 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
,
413 NULL
, // class string
420 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
422 if ( m_dwLastError
!= ERROR_SUCCESS
) {
423 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
429 m_hKey
= (WXHKEY
) tmpKey
;
434 // close the key, it's not an error to call it when not opened
435 bool wxRegKey::Close()
438 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
441 if ( m_dwLastError
!= ERROR_SUCCESS
) {
442 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
452 bool wxRegKey::RenameValue(const wxChar
*szValueOld
, const wxChar
*szValueNew
)
455 if ( HasValue(szValueNew
) ) {
456 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
462 !CopyValue(szValueOld
, *this, szValueNew
) ||
463 !DeleteValue(szValueOld
) ) {
464 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
465 szValueOld
, szValueNew
);
473 bool wxRegKey::CopyValue(const wxChar
*szValue
,
475 const wxChar
*szValueNew
)
478 // by default, use the same name
479 szValueNew
= szValue
;
482 switch ( GetValueType(szValue
) ) {
486 return QueryValue(szValue
, strVal
) &&
487 keyDst
.SetValue(szValueNew
, strVal
);
491 /* case Type_Dword_little_endian: == Type_Dword */
494 return QueryValue(szValue
, &dwVal
) &&
495 keyDst
.SetValue(szValueNew
, dwVal
);
501 return QueryValue(szValue
,buf
) &&
502 keyDst
.SetValue(szValueNew
,buf
);
505 // these types are unsupported because I am not sure about how
506 // exactly they should be copied and because they shouldn't
507 // occur among the application keys (supposedly created with
510 case Type_Expand_String
:
511 case Type_Dword_big_endian
:
513 case Type_Multi_String
:
514 case Type_Resource_list
:
515 case Type_Full_resource_descriptor
:
516 case Type_Resource_requirements_list
:
518 wxLogError(_("Can't copy values of unsupported type %d."),
519 GetValueType(szValue
));
524 bool wxRegKey::Rename(const wxChar
*szNewName
)
526 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
529 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
535 // do we stay in the same hive?
536 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
538 // construct the full new name of the key
542 // rename the key to the new name under the same parent
543 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
544 if ( !strKey
.empty() ) {
545 // don't add '\\' in the start if strFullNewName is empty
546 strKey
+= REG_SEPARATOR
;
551 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
554 // this is the full name already
555 keyDst
.SetName(szNewName
);
558 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
560 wxLogError(_("Registry key '%s' already exists."),
561 GetFullName(&keyDst
));
564 ok
= Copy(keyDst
) && DeleteSelf();
568 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
569 GetFullName(this), GetFullName(&keyDst
));
572 m_hRootKey
= keyDst
.m_hRootKey
;
573 m_strKey
= keyDst
.m_strKey
;
579 bool wxRegKey::Copy(const wxChar
*szNewName
)
581 // create the new key first
582 wxRegKey
keyDst(szNewName
);
583 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
587 // we created the dest key but copying to it failed - delete it
589 (void)keyDst
.DeleteSelf();
596 bool wxRegKey::Copy(wxRegKey
& keyDst
)
600 // copy all sub keys to the new location
603 bool bCont
= GetFirstKey(strKey
, lIndex
);
604 while ( ok
&& bCont
) {
605 wxRegKey
key(*this, strKey
);
607 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
608 ok
= key
.Copy((const wxChar
*) keyName
);
611 bCont
= GetNextKey(strKey
, lIndex
);
613 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
614 GetFullName(&key
), keyName
.c_str());
620 bCont
= GetFirstValue(strVal
, lIndex
);
621 while ( ok
&& bCont
) {
622 ok
= CopyValue(strVal
, keyDst
);
625 wxLogSysError(m_dwLastError
,
626 _("Failed to copy registry value '%s'"),
630 bCont
= GetNextValue(strVal
, lIndex
);
635 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
636 GetFullName(this), GetFullName(&keyDst
));
642 // ----------------------------------------------------------------------------
643 // delete keys/values
644 // ----------------------------------------------------------------------------
645 bool wxRegKey::DeleteSelf()
650 // it already doesn't exist - ok!
655 // prevent a buggy program from erasing one of the root registry keys or an
656 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
657 // key except HKCR (HKCR has some "deleteable" subkeys)
658 if ( m_strKey
.empty() ||
659 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
660 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
661 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
667 // we can't delete keys while enumerating because it confuses GetNextKey, so
668 // we first save the key names and then delete them all
669 wxArrayString astrSubkeys
;
673 bool bCont
= GetFirstKey(strKey
, lIndex
);
675 astrSubkeys
.Add(strKey
);
677 bCont
= GetNextKey(strKey
, lIndex
);
680 size_t nKeyCount
= astrSubkeys
.Count();
681 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
682 wxRegKey
key(*this, astrSubkeys
[nKey
]);
683 if ( !key
.DeleteSelf() )
687 // now delete this key itself
690 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
691 // deleting a key which doesn't exist is not considered an error
692 if ( m_dwLastError
!= ERROR_SUCCESS
&&
693 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
694 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
702 bool wxRegKey::DeleteKey(const wxChar
*szKey
)
707 wxRegKey
key(*this, szKey
);
708 return key
.DeleteSelf();
711 bool wxRegKey::DeleteValue(const wxChar
*szValue
)
716 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, WXSTRINGCAST szValue
);
718 // deleting a value which doesn't exist is not considered an error
719 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
720 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
722 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
723 szValue
, GetName().c_str());
730 // ----------------------------------------------------------------------------
731 // access to values and subkeys
732 // ----------------------------------------------------------------------------
734 // return true if value exists
735 bool wxRegKey::HasValue(const wxChar
*szValue
) const
737 // this function should be silent, so suppress possible messages from Open()
740 if ( !CONST_CAST
Open(Read
) )
743 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
744 WXSTRINGCAST szValue
,
747 return dwRet
== ERROR_SUCCESS
;
750 // returns true if this key has any values
751 bool wxRegKey::HasValues() const
753 // suppress possible messages from GetFirstValue()
756 // just call GetFirstValue with dummy parameters
759 return CONST_CAST
GetFirstValue(str
, l
);
762 // returns true if this key has any subkeys
763 bool wxRegKey::HasSubkeys() const
765 // suppress possible messages from GetFirstKey()
768 // just call GetFirstKey with dummy parameters
771 return CONST_CAST
GetFirstKey(str
, l
);
774 // returns true if given subkey exists
775 bool wxRegKey::HasSubKey(const wxChar
*szKey
) const
777 // this function should be silent, so suppress possible messages from Open()
780 if ( !CONST_CAST
Open(Read
) )
783 return KeyExists(m_hKey
, szKey
);
786 wxRegKey::ValueType
wxRegKey::GetValueType(const wxChar
*szValue
) const
788 if ( ! CONST_CAST
Open(Read
) )
792 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
793 &dwType
, NULL
, NULL
);
794 if ( m_dwLastError
!= ERROR_SUCCESS
) {
795 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
800 return (ValueType
)dwType
;
803 bool wxRegKey::SetValue(const wxChar
*szValue
, long lValue
)
805 if ( CONST_CAST
Open() ) {
806 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
807 (RegString
)&lValue
, sizeof(lValue
));
808 if ( m_dwLastError
== ERROR_SUCCESS
)
812 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
813 GetFullName(this, szValue
));
817 bool wxRegKey::QueryValue(const wxChar
*szValue
, long *plValue
) const
819 if ( CONST_CAST
Open(Read
) ) {
820 DWORD dwType
, dwSize
= sizeof(DWORD
);
821 RegString pBuf
= (RegString
)plValue
;
822 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
823 &dwType
, pBuf
, &dwSize
);
824 if ( m_dwLastError
!= ERROR_SUCCESS
) {
825 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
830 // check that we read the value of right type
831 wxASSERT_MSG( IsNumericValue(szValue
),
832 wxT("Type mismatch in wxRegKey::QueryValue().") );
841 bool wxRegKey::SetValue(const wxChar
*szValue
,const wxMemoryBuffer
& buffer
)
844 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
847 if ( CONST_CAST
Open() ) {
848 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_BINARY
,
849 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
850 if ( m_dwLastError
== ERROR_SUCCESS
)
854 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
855 GetFullName(this, szValue
));
860 bool wxRegKey::QueryValue(const wxChar
*szValue
, wxMemoryBuffer
& buffer
) const
862 if ( CONST_CAST
Open(Read
) ) {
863 // first get the type and size of the data
864 DWORD dwType
, dwSize
;
865 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
866 &dwType
, NULL
, &dwSize
);
868 if ( m_dwLastError
== ERROR_SUCCESS
) {
870 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
871 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
872 WXSTRINGCAST szValue
,
877 buffer
.UngetWriteBuf(dwSize
);
879 buffer
.SetDataLen(0);
884 if ( m_dwLastError
!= ERROR_SUCCESS
) {
885 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
896 bool wxRegKey::QueryValue(const wxChar
*szValue
,
898 bool WXUNUSED_IN_WINCE(raw
)) const
900 if ( CONST_CAST
Open(Read
) )
903 // first get the type and size of the data
904 DWORD dwType
, dwSize
;
905 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
906 &dwType
, NULL
, &dwSize
);
907 if ( m_dwLastError
== ERROR_SUCCESS
)
911 // must treat this case specially as GetWriteBuf() doesn't like
912 // being called with 0 size
917 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
918 WXSTRINGCAST szValue
,
921 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
924 // expand the var expansions in the string unless disabled
926 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
928 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
, NULL
, 0);
929 bool ok
= dwExpSize
!= 0;
932 wxString strExpValue
;
933 ok
= ::ExpandEnvironmentStrings(strValue
,
934 wxStringBuffer(strExpValue
, dwExpSize
),
937 strValue
= strExpValue
;
942 wxLogLastError(_T("ExpandEnvironmentStrings"));
949 if ( m_dwLastError
== ERROR_SUCCESS
)
951 // check that it was the right type
952 wxASSERT_MSG( !IsNumericValue(szValue
),
953 wxT("Type mismatch in wxRegKey::QueryValue().") );
960 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
961 GetFullName(this, szValue
));
965 bool wxRegKey::SetValue(const wxChar
*szValue
, const wxString
& strValue
)
967 if ( CONST_CAST
Open() ) {
968 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
969 (RegString
)strValue
.c_str(),
970 (strValue
.Len() + 1)*sizeof(wxChar
));
971 if ( m_dwLastError
== ERROR_SUCCESS
)
975 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
976 GetFullName(this, szValue
));
980 wxString
wxRegKey::QueryDefaultValue() const
983 QueryValue(NULL
, str
);
987 // ----------------------------------------------------------------------------
989 // NB: all these functions require an index variable which allows to have
990 // several concurrently running indexations on the same key
991 // ----------------------------------------------------------------------------
993 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
999 return GetNextValue(strValueName
, lIndex
);
1002 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1004 wxASSERT( IsOpened() );
1006 // are we already at the end of enumeration?
1010 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1011 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1013 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1014 szValueName
, &dwValueLen
,
1017 NULL
, // [out] buffer for value
1018 NULL
); // [i/o] it's length
1020 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1021 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1022 m_dwLastError
= ERROR_SUCCESS
;
1026 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1033 strValueName
= szValueName
;
1038 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1044 return GetNextKey(strKeyName
, lIndex
);
1047 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1049 wxASSERT( IsOpened() );
1051 // are we already at the end of enumeration?
1055 wxChar szKeyName
[_MAX_PATH
+ 1];
1058 DWORD sizeName
= WXSIZEOF(szKeyName
);
1059 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1060 0, NULL
, NULL
, NULL
);
1062 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1065 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1066 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1067 m_dwLastError
= ERROR_SUCCESS
;
1071 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1078 strKeyName
= szKeyName
;
1082 // returns true if the value contains a number (else it's some string)
1083 bool wxRegKey::IsNumericValue(const wxChar
*szValue
) const
1085 ValueType type
= GetValueType(szValue
);
1088 /* case Type_Dword_little_endian: == Type_Dword */
1089 case Type_Dword_big_endian
:
1097 // ----------------------------------------------------------------------------
1098 // exporting registry keys to file
1099 // ----------------------------------------------------------------------------
1103 // helper functions for writing ASCII strings (even in Unicode build)
1104 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1110 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1112 // as we open the file in text mode, it is enough to write LF without CR
1113 return WriteAsciiChar(ostr
, '\n');
1116 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1118 return ostr
.Write(p
, strlen(p
)).IsOk();
1121 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1124 wxCharBuffer
name(s
.mb_str());
1125 ostr
.Write(name
, strlen(name
));
1127 ostr
.Write(s
, s
.length());
1133 #endif // wxUSE_STREAMS
1135 bool wxRegKey::Export(const wxString
& filename
) const
1137 #if wxUSE_FFILE && wxUSE_STREAMS
1138 if ( wxFile::Exists(filename
) )
1140 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1145 wxFFileOutputStream
ostr(filename
, _T("w"));
1147 return ostr
.Ok() && Export(ostr
);
1149 wxUnusedVar(filename
);
1155 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1157 // write out the header
1158 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1161 return DoExport(ostr
);
1163 #endif // wxUSE_STREAMS
1167 FormatAsHex(const void *data
,
1169 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1171 wxString
value(_T("hex"));
1173 // binary values use just "hex:" prefix while the other ones must indicate
1175 if ( type
!= wxRegKey::Type_Binary
)
1176 value
<< _T('(') << type
<< _T(')');
1179 // write all the rest as comma-separated bytes
1180 value
.reserve(3*size
+ 10);
1181 const char * const p
= wx_static_cast(const char *, data
);
1182 for ( size_t n
= 0; n
< size
; n
++ )
1184 // TODO: line wrapping: although not required by regedit, this makes
1185 // the generated files easier to read and compare with the files
1186 // produced by regedit
1190 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1197 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1199 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1202 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1205 const ValueType type
= GetValueType(name
);
1211 if ( !QueryValue(name
, value
) )
1214 // quotes and backslashes must be quoted, linefeeds are not
1215 // allowed in string values
1216 rhs
.reserve(value
.length() + 2);
1219 // there can be no NULs here
1220 bool useHex
= false;
1221 for ( const wxChar
*p
= value
.c_str(); *p
&& !useHex
; p
++ )
1226 // we can only represent this string in hex
1232 // escape special symbol
1242 rhs
= FormatAsHex(value
, Type_String
);
1249 /* case Type_Dword_little_endian: == Type_Dword */
1252 if ( !QueryValue(name
, &value
) )
1255 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1259 case Type_Expand_String
:
1260 case Type_Multi_String
:
1263 if ( !QueryRawValue(name
, value
) )
1266 rhs
= FormatAsHex(value
, type
);
1273 if ( !QueryValue(name
, buf
) )
1276 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1280 // no idea how those appear in REGEDIT4 files
1282 case Type_Dword_big_endian
:
1284 case Type_Resource_list
:
1285 case Type_Full_resource_descriptor
:
1286 case Type_Resource_requirements_list
:
1288 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1296 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1298 // first examine the value type: if it's unsupported, simply skip it
1299 // instead of aborting the entire export process because we failed to
1300 // export a single value
1301 wxString value
= FormatValue(name
);
1302 if ( value
.empty() )
1304 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1305 name
.c_str(), GetName().c_str());
1309 // we do have the text representation of the value, now write everything
1312 // special case: unnamed/default value is represented as just "@"
1315 if ( !WriteAsciiChar(ostr
, '@') )
1318 else // normal, named, value
1320 if ( !WriteAsciiChar(ostr
, '"') ||
1321 !WriteAsciiString(ostr
, name
) ||
1322 !WriteAsciiChar(ostr
, '"') )
1326 if ( !WriteAsciiChar(ostr
, '=') )
1329 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1332 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1334 // write out this key name
1335 if ( !WriteAsciiChar(ostr
, '[') )
1338 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1341 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1344 // dump all our values
1347 wxRegKey
& self
= wx_const_cast(wxRegKey
&, *this);
1348 bool cont
= self
.GetFirstValue(name
, dummy
);
1351 if ( !DoExportValue(ostr
, name
) )
1354 cont
= GetNextValue(name
, dummy
);
1357 // always terminate values by blank line, even if there were no values
1358 if ( !WriteAsciiEOL(ostr
) )
1361 // recurse to subkeys
1362 cont
= self
.GetFirstKey(name
, dummy
);
1365 wxRegKey
subkey(*this, name
);
1366 if ( !subkey
.DoExport(ostr
) )
1369 cont
= GetNextKey(name
, dummy
);
1375 #endif // wxUSE_STREAMS
1377 // ============================================================================
1378 // implementation of global private functions
1379 // ============================================================================
1381 bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
)
1383 // don't close this key itself for the case of empty szKey!
1384 if ( wxIsEmpty(szKey
) )
1393 KEY_READ
, // we might not have enough rights for rw access
1395 ) == ERROR_SUCCESS
)
1397 ::RegCloseKey(hkeyDummy
);
1405 const wxChar
*GetFullName(const wxRegKey
*pKey
, const wxChar
*szValue
)
1407 static wxString s_str
;
1408 s_str
= pKey
->GetName();
1409 if ( !wxIsEmpty(szValue
) )
1410 s_str
<< wxT("\\") << szValue
;
1412 return s_str
.c_str();
1415 void RemoveTrailingSeparator(wxString
& str
)
1417 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1418 str
.Truncate(str
.Len() - 1);