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/string.h"
29 #include "wx/wfstream.h"
32 #include "wx/msw/wrapwin.h"
35 #include "wx/msw/private.h"
41 #include <stdlib.h> // for _MAX_PATH
48 #define HKEY_DEFINED // already defined in windows.h
49 #include "wx/msw/registry.h"
51 // some registry functions don't like signed chars
52 typedef unsigned char *RegString
;
53 typedef BYTE
* RegBinary
;
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // the standard key names, short names and handles all bundled together for
65 const wxChar
*szShortName
;
69 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
70 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
71 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
72 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
74 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
76 #ifdef HKEY_CURRENT_CONFIG
77 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
80 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
84 // the registry name separator (perhaps one day MS will change it to '/' ;-)
85 #define REG_SEPARATOR wxT('\\')
87 // useful for Windows programmers: makes somewhat more clear all these zeroes
88 // being passed to Windows APIs
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 // const_cast<> is not yet supported by all compilers
96 #define CONST_CAST ((wxRegKey *)this)->
98 // and neither is mutable which m_dwLastError should be
99 #define m_dwLastError CONST_CAST m_dwLastError
101 // ----------------------------------------------------------------------------
102 // non member functions
103 // ----------------------------------------------------------------------------
105 // removes the trailing backslash from the string if it has one
106 static inline void RemoveTrailingSeparator(wxString
& str
);
108 // returns true if given registry key exists
109 static bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
);
111 // combines value and key name (uses static buffer!)
112 static const wxChar
*GetFullName(const wxRegKey
*pKey
,
113 const wxChar
*szValue
= NULL
);
115 // ============================================================================
116 // implementation of wxRegKey class
117 // ============================================================================
119 // ----------------------------------------------------------------------------
120 // static functions and variables
121 // ----------------------------------------------------------------------------
123 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
125 // @@ should take a `StdKey key', but as it's often going to be used in loops
126 // it would require casts in user code.
127 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
129 // return empty string if key is invalid
130 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
132 return aStdKeys
[key
].szName
;
135 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
137 // return empty string if key is invalid
138 wxCHECK( key
< nStdKeys
, wxEmptyString
);
140 return aStdKeys
[key
].szShortName
;
143 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
145 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
149 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
150 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
151 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
152 hRootKey
= aStdKeys
[ui
].hkey
;
157 if ( ui
== nStdKeys
) {
158 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
160 hRootKey
= HKEY_CLASSES_ROOT
;
163 strKey
= strKey
.After(REG_SEPARATOR
);
164 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
165 strKey
.Truncate(strKey
.Len() - 1);
168 return (wxRegKey::StdKey
)(int)hRootKey
;
171 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
173 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
174 if ( (int) aStdKeys
[ui
].hkey
== (int) hkey
)
178 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
183 // ----------------------------------------------------------------------------
185 // ----------------------------------------------------------------------------
189 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
194 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
196 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
201 // parent is a predefined (and preopened) key
202 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
204 RemoveTrailingSeparator(m_strKey
);
205 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
210 // parent is a normal regkey
211 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
212 : m_strKey(keyParent
.m_strKey
)
214 // combine our name with parent's to get the full name
215 if ( !m_strKey
.empty() &&
216 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
217 m_strKey
+= REG_SEPARATOR
;
221 RemoveTrailingSeparator(m_strKey
);
223 m_hRootKey
= keyParent
.m_hRootKey
;
228 // dtor closes the key releasing system resource
229 wxRegKey::~wxRegKey()
234 // ----------------------------------------------------------------------------
235 // change the key name/hkey
236 // ----------------------------------------------------------------------------
238 // set the full key name
239 void wxRegKey::SetName(const wxString
& strKey
)
244 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
247 // the name is relative to the parent key
248 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
253 RemoveTrailingSeparator(m_strKey
);
254 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
257 // the name is relative to the parent key
258 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
262 // combine our name with parent's to get the full name
264 // NB: this method is called by wxRegConfig::SetPath() which is a performance
265 // critical function and so it preallocates space for our m_strKey to
266 // gain some speed - this is why we only use += here and not = which
267 // would just free the prealloc'd buffer and would have to realloc it the
270 m_strKey
+= keyParent
.m_strKey
;
271 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
272 m_strKey
+= REG_SEPARATOR
;
275 RemoveTrailingSeparator(m_strKey
);
277 m_hRootKey
= keyParent
.m_hRootKey
;
280 // hKey should be opened and will be closed in wxRegKey dtor
281 void wxRegKey::SetHkey(WXHKEY hKey
)
288 // ----------------------------------------------------------------------------
289 // info about the key
290 // ----------------------------------------------------------------------------
292 // returns true if the key exists
293 bool wxRegKey::Exists() const
295 // opened key has to exist, try to open it if not done yet
296 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
);
299 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
300 wxString
wxRegKey::GetName(bool bShortPrefix
) const
302 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
303 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
304 : aStdKeys
[key
].szName
;
305 if ( !m_strKey
.empty() )
306 str
<< _T("\\") << m_strKey
;
311 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
314 size_t *pnMaxValueLen
) const
316 // old gcc headers incorrectly prototype RegQueryInfoKey()
317 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
318 #define REG_PARAM (size_t *)
320 #define REG_PARAM (LPDWORD)
323 // it might be unexpected to some that this function doesn't open the key
324 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
326 m_dwLastError
= ::RegQueryInfoKey
330 NULL
, // (ptr to) size of class name buffer
333 pnSubKeys
, // [out] number of subkeys
335 pnMaxKeyLen
, // [out] max length of a subkey name
336 NULL
, // longest subkey class name
338 pnValues
, // [out] number of values
340 pnMaxValueLen
, // [out] max length of a value name
341 NULL
, // longest value data
342 NULL
, // security descriptor
343 NULL
// time of last modification
348 if ( m_dwLastError
!= ERROR_SUCCESS
) {
349 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
357 // ----------------------------------------------------------------------------
359 // ----------------------------------------------------------------------------
361 // opens key (it's not an error to call Open() on an already opened key)
362 bool wxRegKey::Open(AccessMode mode
)
366 if ( mode
<= m_mode
)
369 // we had been opened in read mode but now must be reopened in write
374 m_dwLastError
= ::RegOpenKeyEx
379 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
383 if ( m_dwLastError
!= ERROR_SUCCESS
)
385 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
390 m_hKey
= (WXHKEY
) tmpKey
;
396 // creates key, failing if it exists and !bOkIfExists
397 bool wxRegKey::Create(bool bOkIfExists
)
399 // check for existence only if asked (i.e. order is important!)
400 if ( !bOkIfExists
&& Exists() )
409 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
,
411 NULL
, // class string
418 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
420 if ( m_dwLastError
!= ERROR_SUCCESS
) {
421 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
427 m_hKey
= (WXHKEY
) tmpKey
;
432 // close the key, it's not an error to call it when not opened
433 bool wxRegKey::Close()
436 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
439 if ( m_dwLastError
!= ERROR_SUCCESS
) {
440 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
450 bool wxRegKey::RenameValue(const wxChar
*szValueOld
, const wxChar
*szValueNew
)
453 if ( HasValue(szValueNew
) ) {
454 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
460 !CopyValue(szValueOld
, *this, szValueNew
) ||
461 !DeleteValue(szValueOld
) ) {
462 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
463 szValueOld
, szValueNew
);
471 bool wxRegKey::CopyValue(const wxChar
*szValue
,
473 const wxChar
*szValueNew
)
476 // by default, use the same name
477 szValueNew
= szValue
;
480 switch ( GetValueType(szValue
) ) {
484 return QueryValue(szValue
, strVal
) &&
485 keyDst
.SetValue(szValueNew
, strVal
);
489 /* case Type_Dword_little_endian: == Type_Dword */
492 return QueryValue(szValue
, &dwVal
) &&
493 keyDst
.SetValue(szValueNew
, dwVal
);
499 return QueryValue(szValue
,buf
) &&
500 keyDst
.SetValue(szValueNew
,buf
);
503 // these types are unsupported because I am not sure about how
504 // exactly they should be copied and because they shouldn't
505 // occur among the application keys (supposedly created with
508 case Type_Expand_String
:
509 case Type_Dword_big_endian
:
511 case Type_Multi_String
:
512 case Type_Resource_list
:
513 case Type_Full_resource_descriptor
:
514 case Type_Resource_requirements_list
:
516 wxLogError(_("Can't copy values of unsupported type %d."),
517 GetValueType(szValue
));
522 bool wxRegKey::Rename(const wxChar
*szNewName
)
524 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
527 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
533 // do we stay in the same hive?
534 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
536 // construct the full new name of the key
540 // rename the key to the new name under the same parent
541 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
542 if ( !strKey
.empty() ) {
543 // don't add '\\' in the start if strFullNewName is empty
544 strKey
+= REG_SEPARATOR
;
549 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
552 // this is the full name already
553 keyDst
.SetName(szNewName
);
556 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
558 wxLogError(_("Registry key '%s' already exists."),
559 GetFullName(&keyDst
));
562 ok
= Copy(keyDst
) && DeleteSelf();
566 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
567 GetFullName(this), GetFullName(&keyDst
));
570 m_hRootKey
= keyDst
.m_hRootKey
;
571 m_strKey
= keyDst
.m_strKey
;
577 bool wxRegKey::Copy(const wxChar
*szNewName
)
579 // create the new key first
580 wxRegKey
keyDst(szNewName
);
581 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
585 // we created the dest key but copying to it failed - delete it
587 (void)keyDst
.DeleteSelf();
594 bool wxRegKey::Copy(wxRegKey
& keyDst
)
598 // copy all sub keys to the new location
601 bool bCont
= GetFirstKey(strKey
, lIndex
);
602 while ( ok
&& bCont
) {
603 wxRegKey
key(*this, strKey
);
605 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
606 ok
= key
.Copy((const wxChar
*) keyName
);
609 bCont
= GetNextKey(strKey
, lIndex
);
611 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
612 GetFullName(&key
), keyName
.c_str());
618 bCont
= GetFirstValue(strVal
, lIndex
);
619 while ( ok
&& bCont
) {
620 ok
= CopyValue(strVal
, keyDst
);
623 wxLogSysError(m_dwLastError
,
624 _("Failed to copy registry value '%s'"),
628 bCont
= GetNextValue(strVal
, lIndex
);
633 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
634 GetFullName(this), GetFullName(&keyDst
));
640 // ----------------------------------------------------------------------------
641 // delete keys/values
642 // ----------------------------------------------------------------------------
643 bool wxRegKey::DeleteSelf()
648 // it already doesn't exist - ok!
653 // prevent a buggy program from erasing one of the root registry keys or an
654 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
655 // key except HKCR (HKCR has some "deleteable" subkeys)
656 if ( m_strKey
.empty() ||
657 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
658 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
659 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
665 // we can't delete keys while enumerating because it confuses GetNextKey, so
666 // we first save the key names and then delete them all
667 wxArrayString astrSubkeys
;
671 bool bCont
= GetFirstKey(strKey
, lIndex
);
673 astrSubkeys
.Add(strKey
);
675 bCont
= GetNextKey(strKey
, lIndex
);
678 size_t nKeyCount
= astrSubkeys
.Count();
679 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
680 wxRegKey
key(*this, astrSubkeys
[nKey
]);
681 if ( !key
.DeleteSelf() )
685 // now delete this key itself
688 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
689 // deleting a key which doesn't exist is not considered an error
690 if ( m_dwLastError
!= ERROR_SUCCESS
&&
691 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
692 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
700 bool wxRegKey::DeleteKey(const wxChar
*szKey
)
705 wxRegKey
key(*this, szKey
);
706 return key
.DeleteSelf();
709 bool wxRegKey::DeleteValue(const wxChar
*szValue
)
714 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, WXSTRINGCAST szValue
);
716 // deleting a value which doesn't exist is not considered an error
717 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
718 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
720 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
721 szValue
, GetName().c_str());
728 // ----------------------------------------------------------------------------
729 // access to values and subkeys
730 // ----------------------------------------------------------------------------
732 // return true if value exists
733 bool wxRegKey::HasValue(const wxChar
*szValue
) const
735 // this function should be silent, so suppress possible messages from Open()
738 if ( !CONST_CAST
Open(Read
) )
741 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
742 WXSTRINGCAST szValue
,
745 return dwRet
== ERROR_SUCCESS
;
748 // returns true if this key has any values
749 bool wxRegKey::HasValues() const
751 // suppress possible messages from GetFirstValue()
754 // just call GetFirstValue with dummy parameters
757 return CONST_CAST
GetFirstValue(str
, l
);
760 // returns true if this key has any subkeys
761 bool wxRegKey::HasSubkeys() const
763 // suppress possible messages from GetFirstKey()
766 // just call GetFirstKey with dummy parameters
769 return CONST_CAST
GetFirstKey(str
, l
);
772 // returns true if given subkey exists
773 bool wxRegKey::HasSubKey(const wxChar
*szKey
) const
775 // this function should be silent, so suppress possible messages from Open()
778 if ( !CONST_CAST
Open(Read
) )
781 return KeyExists(m_hKey
, szKey
);
784 wxRegKey::ValueType
wxRegKey::GetValueType(const wxChar
*szValue
) const
786 if ( ! CONST_CAST
Open(Read
) )
790 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
791 &dwType
, NULL
, NULL
);
792 if ( m_dwLastError
!= ERROR_SUCCESS
) {
793 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
798 return (ValueType
)dwType
;
801 bool wxRegKey::SetValue(const wxChar
*szValue
, long lValue
)
803 if ( CONST_CAST
Open() ) {
804 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
805 (RegString
)&lValue
, sizeof(lValue
));
806 if ( m_dwLastError
== ERROR_SUCCESS
)
810 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
811 GetFullName(this, szValue
));
815 bool wxRegKey::QueryValue(const wxChar
*szValue
, long *plValue
) const
817 if ( CONST_CAST
Open(Read
) ) {
818 DWORD dwType
, dwSize
= sizeof(DWORD
);
819 RegString pBuf
= (RegString
)plValue
;
820 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
821 &dwType
, pBuf
, &dwSize
);
822 if ( m_dwLastError
!= ERROR_SUCCESS
) {
823 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
828 // check that we read the value of right type
829 wxASSERT_MSG( IsNumericValue(szValue
),
830 wxT("Type mismatch in wxRegKey::QueryValue().") );
839 bool wxRegKey::SetValue(const wxChar
*szValue
,const wxMemoryBuffer
& buffer
)
842 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
845 if ( CONST_CAST
Open() ) {
846 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_BINARY
,
847 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
848 if ( m_dwLastError
== ERROR_SUCCESS
)
852 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
853 GetFullName(this, szValue
));
858 bool wxRegKey::QueryValue(const wxChar
*szValue
, wxMemoryBuffer
& buffer
) const
860 if ( CONST_CAST
Open(Read
) ) {
861 // first get the type and size of the data
862 DWORD dwType
, dwSize
;
863 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
864 &dwType
, NULL
, &dwSize
);
866 if ( m_dwLastError
== ERROR_SUCCESS
) {
868 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
869 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
870 WXSTRINGCAST szValue
,
875 buffer
.UngetWriteBuf(dwSize
);
877 buffer
.SetDataLen(0);
882 if ( m_dwLastError
!= ERROR_SUCCESS
) {
883 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
894 bool wxRegKey::QueryValue(const wxChar
*szValue
,
896 bool WXUNUSED_IN_WINCE(raw
)) const
898 if ( CONST_CAST
Open(Read
) )
901 // first get the type and size of the data
902 DWORD dwType
=REG_NONE
, dwSize
=0;
903 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
904 &dwType
, NULL
, &dwSize
);
905 if ( m_dwLastError
== ERROR_SUCCESS
)
909 // must treat this case specially as GetWriteBuf() doesn't like
910 // being called with 0 size
915 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
916 WXSTRINGCAST szValue
,
919 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
922 // expand the var expansions in the string unless disabled
924 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
926 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
, NULL
, 0);
927 bool ok
= dwExpSize
!= 0;
930 wxString strExpValue
;
931 ok
= ::ExpandEnvironmentStrings(strValue
,
932 wxStringBuffer(strExpValue
, dwExpSize
),
935 strValue
= strExpValue
;
940 wxLogLastError(_T("ExpandEnvironmentStrings"));
947 if ( m_dwLastError
== ERROR_SUCCESS
)
949 // check that it was the right type
950 wxASSERT_MSG( !IsNumericValue(szValue
),
951 wxT("Type mismatch in wxRegKey::QueryValue().") );
958 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
959 GetFullName(this, szValue
));
963 bool wxRegKey::SetValue(const wxChar
*szValue
, const wxString
& strValue
)
965 if ( CONST_CAST
Open() ) {
966 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
967 (RegString
)strValue
.c_str(),
968 (strValue
.Len() + 1)*sizeof(wxChar
));
969 if ( m_dwLastError
== ERROR_SUCCESS
)
973 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
974 GetFullName(this, szValue
));
978 wxString
wxRegKey::QueryDefaultValue() const
981 QueryValue(NULL
, str
);
985 // ----------------------------------------------------------------------------
987 // NB: all these functions require an index variable which allows to have
988 // several concurrently running indexations on the same key
989 // ----------------------------------------------------------------------------
991 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
997 return GetNextValue(strValueName
, lIndex
);
1000 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1002 wxASSERT( IsOpened() );
1004 // are we already at the end of enumeration?
1008 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1009 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1011 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1012 szValueName
, &dwValueLen
,
1015 NULL
, // [out] buffer for value
1016 NULL
); // [i/o] it's length
1018 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1019 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1020 m_dwLastError
= ERROR_SUCCESS
;
1024 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1031 strValueName
= szValueName
;
1036 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1042 return GetNextKey(strKeyName
, lIndex
);
1045 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1047 wxASSERT( IsOpened() );
1049 // are we already at the end of enumeration?
1053 wxChar szKeyName
[_MAX_PATH
+ 1];
1056 DWORD sizeName
= WXSIZEOF(szKeyName
);
1057 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1058 0, NULL
, NULL
, NULL
);
1060 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1063 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1064 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1065 m_dwLastError
= ERROR_SUCCESS
;
1069 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1076 strKeyName
= szKeyName
;
1080 // returns true if the value contains a number (else it's some string)
1081 bool wxRegKey::IsNumericValue(const wxChar
*szValue
) const
1083 ValueType type
= GetValueType(szValue
);
1086 /* case Type_Dword_little_endian: == Type_Dword */
1087 case Type_Dword_big_endian
:
1095 // ----------------------------------------------------------------------------
1096 // exporting registry keys to file
1097 // ----------------------------------------------------------------------------
1101 // helper functions for writing ASCII strings (even in Unicode build)
1102 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1108 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1110 // as we open the file in text mode, it is enough to write LF without CR
1111 return WriteAsciiChar(ostr
, '\n');
1114 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1116 return ostr
.Write(p
, strlen(p
)).IsOk();
1119 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1122 wxCharBuffer
name(s
.mb_str());
1123 ostr
.Write(name
, strlen(name
));
1125 ostr
.Write(s
, s
.length());
1131 #endif // wxUSE_STREAMS
1133 bool wxRegKey::Export(const wxString
& filename
) const
1135 #if wxUSE_FFILE && wxUSE_STREAMS
1136 if ( wxFile::Exists(filename
) )
1138 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1143 wxFFileOutputStream
ostr(filename
, _T("w"));
1145 return ostr
.Ok() && Export(ostr
);
1147 wxUnusedVar(filename
);
1153 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1155 // write out the header
1156 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1159 return DoExport(ostr
);
1161 #endif // wxUSE_STREAMS
1165 FormatAsHex(const void *data
,
1167 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1169 wxString
value(_T("hex"));
1171 // binary values use just "hex:" prefix while the other ones must indicate
1173 if ( type
!= wxRegKey::Type_Binary
)
1174 value
<< _T('(') << type
<< _T(')');
1177 // write all the rest as comma-separated bytes
1178 value
.reserve(3*size
+ 10);
1179 const char * const p
= wx_static_cast(const char *, data
);
1180 for ( size_t n
= 0; n
< size
; n
++ )
1182 // TODO: line wrapping: although not required by regedit, this makes
1183 // the generated files easier to read and compare with the files
1184 // produced by regedit
1188 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1195 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1197 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1200 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1203 const ValueType type
= GetValueType(name
);
1209 if ( !QueryValue(name
, value
) )
1212 // quotes and backslashes must be quoted, linefeeds are not
1213 // allowed in string values
1214 rhs
.reserve(value
.length() + 2);
1217 // there can be no NULs here
1218 bool useHex
= false;
1219 for ( const wxChar
*p
= value
.c_str(); *p
&& !useHex
; p
++ )
1224 // we can only represent this string in hex
1230 // escape special symbol
1240 rhs
= FormatAsHex(value
, Type_String
);
1247 /* case Type_Dword_little_endian: == Type_Dword */
1250 if ( !QueryValue(name
, &value
) )
1253 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1257 case Type_Expand_String
:
1258 case Type_Multi_String
:
1261 if ( !QueryRawValue(name
, value
) )
1264 rhs
= FormatAsHex(value
, type
);
1271 if ( !QueryValue(name
, buf
) )
1274 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1278 // no idea how those appear in REGEDIT4 files
1280 case Type_Dword_big_endian
:
1282 case Type_Resource_list
:
1283 case Type_Full_resource_descriptor
:
1284 case Type_Resource_requirements_list
:
1286 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1294 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1296 // first examine the value type: if it's unsupported, simply skip it
1297 // instead of aborting the entire export process because we failed to
1298 // export a single value
1299 wxString value
= FormatValue(name
);
1300 if ( value
.empty() )
1302 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1303 name
.c_str(), GetName().c_str());
1307 // we do have the text representation of the value, now write everything
1310 // special case: unnamed/default value is represented as just "@"
1313 if ( !WriteAsciiChar(ostr
, '@') )
1316 else // normal, named, value
1318 if ( !WriteAsciiChar(ostr
, '"') ||
1319 !WriteAsciiString(ostr
, name
) ||
1320 !WriteAsciiChar(ostr
, '"') )
1324 if ( !WriteAsciiChar(ostr
, '=') )
1327 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1330 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1332 // write out this key name
1333 if ( !WriteAsciiChar(ostr
, '[') )
1336 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1339 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1342 // dump all our values
1345 wxRegKey
& self
= wx_const_cast(wxRegKey
&, *this);
1346 bool cont
= self
.GetFirstValue(name
, dummy
);
1349 if ( !DoExportValue(ostr
, name
) )
1352 cont
= GetNextValue(name
, dummy
);
1355 // always terminate values by blank line, even if there were no values
1356 if ( !WriteAsciiEOL(ostr
) )
1359 // recurse to subkeys
1360 cont
= self
.GetFirstKey(name
, dummy
);
1363 wxRegKey
subkey(*this, name
);
1364 if ( !subkey
.DoExport(ostr
) )
1367 cont
= GetNextKey(name
, dummy
);
1373 #endif // wxUSE_STREAMS
1375 // ============================================================================
1376 // implementation of global private functions
1377 // ============================================================================
1379 bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
)
1381 // don't close this key itself for the case of empty szKey!
1382 if ( wxIsEmpty(szKey
) )
1391 KEY_READ
, // we might not have enough rights for rw access
1393 ) == ERROR_SUCCESS
)
1395 ::RegCloseKey(hkeyDummy
);
1403 const wxChar
*GetFullName(const wxRegKey
*pKey
, const wxChar
*szValue
)
1405 static wxString s_str
;
1406 s_str
= pKey
->GetName();
1407 if ( !wxIsEmpty(szValue
) )
1408 s_str
<< wxT("\\") << szValue
;
1410 return s_str
.c_str();
1413 void RemoveTrailingSeparator(wxString
& str
)
1415 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1416 str
.Truncate(str
.Len() - 1);