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 #ifndef HKEY_PERFORMANCE_DATA
55 #define HKEY_PERFORMANCE_DATA ((HKEY)0x80000004)
58 #ifndef HKEY_CURRENT_CONFIG
59 #define HKEY_CURRENT_CONFIG ((HKEY)0x80000005)
63 #define HKEY_DYN_DATA ((HKEY)0x80000006)
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
70 // the standard key names, short names and handles all bundled together for
76 const wxChar
*szShortName
;
80 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
81 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
82 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
83 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
84 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
85 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
86 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
89 // the registry name separator (perhaps one day MS will change it to '/' ;-)
90 #define REG_SEPARATOR wxT('\\')
92 // useful for Windows programmers: makes somewhat more clear all these zeroes
93 // being passed to Windows APIs
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
100 // const_cast<> is not yet supported by all compilers
101 #define CONST_CAST ((wxRegKey *)this)->
103 // and neither is mutable which m_dwLastError should be
104 #define m_dwLastError CONST_CAST m_dwLastError
106 // ----------------------------------------------------------------------------
107 // non member functions
108 // ----------------------------------------------------------------------------
110 // removes the trailing backslash from the string if it has one
111 static inline void RemoveTrailingSeparator(wxString
& str
);
113 // returns true if given registry key exists
114 static bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
);
116 // combines value and key name (uses static buffer!)
117 static const wxChar
*GetFullName(const wxRegKey
*pKey
,
118 const wxChar
*szValue
= NULL
);
120 // ============================================================================
121 // implementation of wxRegKey class
122 // ============================================================================
124 // ----------------------------------------------------------------------------
125 // static functions and variables
126 // ----------------------------------------------------------------------------
128 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
130 // @@ should take a `StdKey key', but as it's often going to be used in loops
131 // it would require casts in user code.
132 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
134 // return empty string if key is invalid
135 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
137 return aStdKeys
[key
].szName
;
140 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
142 // return empty string if key is invalid
143 wxCHECK( key
< nStdKeys
, wxEmptyString
);
145 return aStdKeys
[key
].szShortName
;
148 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
150 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
153 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
154 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
155 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
160 if ( ui
== nStdKeys
) {
161 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
166 strKey
= strKey
.After(REG_SEPARATOR
);
167 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
168 strKey
.Truncate(strKey
.Len() - 1);
174 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
176 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
177 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
181 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
186 // ----------------------------------------------------------------------------
188 // ----------------------------------------------------------------------------
192 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
197 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
199 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
204 // parent is a predefined (and preopened) key
205 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
207 RemoveTrailingSeparator(m_strKey
);
208 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
213 // parent is a normal regkey
214 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
215 : m_strKey(keyParent
.m_strKey
)
217 // combine our name with parent's to get the full name
218 if ( !m_strKey
.empty() &&
219 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
220 m_strKey
+= REG_SEPARATOR
;
224 RemoveTrailingSeparator(m_strKey
);
226 m_hRootKey
= keyParent
.m_hRootKey
;
231 // dtor closes the key releasing system resource
232 wxRegKey::~wxRegKey()
237 // ----------------------------------------------------------------------------
238 // change the key name/hkey
239 // ----------------------------------------------------------------------------
241 // set the full key name
242 void wxRegKey::SetName(const wxString
& strKey
)
247 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
250 // the name is relative to the parent key
251 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
256 RemoveTrailingSeparator(m_strKey
);
257 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
260 // the name is relative to the parent key
261 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
265 // combine our name with parent's to get the full name
267 // NB: this method is called by wxRegConfig::SetPath() which is a performance
268 // critical function and so it preallocates space for our m_strKey to
269 // gain some speed - this is why we only use += here and not = which
270 // would just free the prealloc'd buffer and would have to realloc it the
273 m_strKey
+= keyParent
.m_strKey
;
274 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
275 m_strKey
+= REG_SEPARATOR
;
278 RemoveTrailingSeparator(m_strKey
);
280 m_hRootKey
= keyParent
.m_hRootKey
;
283 // hKey should be opened and will be closed in wxRegKey dtor
284 void wxRegKey::SetHkey(WXHKEY hKey
)
291 // ----------------------------------------------------------------------------
292 // info about the key
293 // ----------------------------------------------------------------------------
295 // returns true if the key exists
296 bool wxRegKey::Exists() const
298 // opened key has to exist, try to open it if not done yet
299 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
);
302 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
303 wxString
wxRegKey::GetName(bool bShortPrefix
) const
305 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
306 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
307 : aStdKeys
[key
].szName
;
308 if ( !m_strKey
.empty() )
309 str
<< _T("\\") << m_strKey
;
314 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
317 size_t *pnMaxValueLen
) const
319 // old gcc headers incorrectly prototype RegQueryInfoKey()
320 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
321 #define REG_PARAM (size_t *)
323 #define REG_PARAM (LPDWORD)
326 // it might be unexpected to some that this function doesn't open the key
327 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
329 m_dwLastError
= ::RegQueryInfoKey
333 NULL
, // (ptr to) size of class name buffer
336 pnSubKeys
, // [out] number of subkeys
338 pnMaxKeyLen
, // [out] max length of a subkey name
339 NULL
, // longest subkey class name
341 pnValues
, // [out] number of values
343 pnMaxValueLen
, // [out] max length of a value name
344 NULL
, // longest value data
345 NULL
, // security descriptor
346 NULL
// time of last modification
351 if ( m_dwLastError
!= ERROR_SUCCESS
) {
352 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
360 // ----------------------------------------------------------------------------
362 // ----------------------------------------------------------------------------
364 // opens key (it's not an error to call Open() on an already opened key)
365 bool wxRegKey::Open(AccessMode mode
)
369 if ( mode
<= m_mode
)
372 // we had been opened in read mode but now must be reopened in write
377 m_dwLastError
= ::RegOpenKeyEx
382 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
386 if ( m_dwLastError
!= ERROR_SUCCESS
)
388 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
393 m_hKey
= (WXHKEY
) tmpKey
;
399 // creates key, failing if it exists and !bOkIfExists
400 bool wxRegKey::Create(bool bOkIfExists
)
402 // check for existence only if asked (i.e. order is important!)
403 if ( !bOkIfExists
&& Exists() )
412 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
,
414 NULL
, // class string
421 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
423 if ( m_dwLastError
!= ERROR_SUCCESS
) {
424 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
430 m_hKey
= (WXHKEY
) tmpKey
;
435 // close the key, it's not an error to call it when not opened
436 bool wxRegKey::Close()
439 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
442 if ( m_dwLastError
!= ERROR_SUCCESS
) {
443 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
453 bool wxRegKey::RenameValue(const wxChar
*szValueOld
, const wxChar
*szValueNew
)
456 if ( HasValue(szValueNew
) ) {
457 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
463 !CopyValue(szValueOld
, *this, szValueNew
) ||
464 !DeleteValue(szValueOld
) ) {
465 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
466 szValueOld
, szValueNew
);
474 bool wxRegKey::CopyValue(const wxChar
*szValue
,
476 const wxChar
*szValueNew
)
479 // by default, use the same name
480 szValueNew
= szValue
;
483 switch ( GetValueType(szValue
) ) {
487 return QueryValue(szValue
, strVal
) &&
488 keyDst
.SetValue(szValueNew
, strVal
);
492 /* case Type_Dword_little_endian: == Type_Dword */
495 return QueryValue(szValue
, &dwVal
) &&
496 keyDst
.SetValue(szValueNew
, dwVal
);
502 return QueryValue(szValue
,buf
) &&
503 keyDst
.SetValue(szValueNew
,buf
);
506 // these types are unsupported because I am not sure about how
507 // exactly they should be copied and because they shouldn't
508 // occur among the application keys (supposedly created with
511 case Type_Expand_String
:
512 case Type_Dword_big_endian
:
514 case Type_Multi_String
:
515 case Type_Resource_list
:
516 case Type_Full_resource_descriptor
:
517 case Type_Resource_requirements_list
:
519 wxLogError(_("Can't copy values of unsupported type %d."),
520 GetValueType(szValue
));
525 bool wxRegKey::Rename(const wxChar
*szNewName
)
527 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
530 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
536 // do we stay in the same hive?
537 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
539 // construct the full new name of the key
543 // rename the key to the new name under the same parent
544 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
545 if ( !strKey
.empty() ) {
546 // don't add '\\' in the start if strFullNewName is empty
547 strKey
+= REG_SEPARATOR
;
552 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
555 // this is the full name already
556 keyDst
.SetName(szNewName
);
559 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
561 wxLogError(_("Registry key '%s' already exists."),
562 GetFullName(&keyDst
));
565 ok
= Copy(keyDst
) && DeleteSelf();
569 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
570 GetFullName(this), GetFullName(&keyDst
));
573 m_hRootKey
= keyDst
.m_hRootKey
;
574 m_strKey
= keyDst
.m_strKey
;
580 bool wxRegKey::Copy(const wxChar
*szNewName
)
582 // create the new key first
583 wxRegKey
keyDst(szNewName
);
584 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
588 // we created the dest key but copying to it failed - delete it
590 (void)keyDst
.DeleteSelf();
597 bool wxRegKey::Copy(wxRegKey
& keyDst
)
601 // copy all sub keys to the new location
604 bool bCont
= GetFirstKey(strKey
, lIndex
);
605 while ( ok
&& bCont
) {
606 wxRegKey
key(*this, strKey
);
608 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
609 ok
= key
.Copy((const wxChar
*) keyName
);
612 bCont
= GetNextKey(strKey
, lIndex
);
614 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
615 GetFullName(&key
), keyName
.c_str());
621 bCont
= GetFirstValue(strVal
, lIndex
);
622 while ( ok
&& bCont
) {
623 ok
= CopyValue(strVal
, keyDst
);
626 wxLogSysError(m_dwLastError
,
627 _("Failed to copy registry value '%s'"),
631 bCont
= GetNextValue(strVal
, lIndex
);
636 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
637 GetFullName(this), GetFullName(&keyDst
));
643 // ----------------------------------------------------------------------------
644 // delete keys/values
645 // ----------------------------------------------------------------------------
646 bool wxRegKey::DeleteSelf()
651 // it already doesn't exist - ok!
656 // prevent a buggy program from erasing one of the root registry keys or an
657 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
658 // key except HKCR (HKCR has some "deleteable" subkeys)
659 if ( m_strKey
.empty() ||
660 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
661 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
662 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
668 // we can't delete keys while enumerating because it confuses GetNextKey, so
669 // we first save the key names and then delete them all
670 wxArrayString astrSubkeys
;
674 bool bCont
= GetFirstKey(strKey
, lIndex
);
676 astrSubkeys
.Add(strKey
);
678 bCont
= GetNextKey(strKey
, lIndex
);
681 size_t nKeyCount
= astrSubkeys
.Count();
682 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
683 wxRegKey
key(*this, astrSubkeys
[nKey
]);
684 if ( !key
.DeleteSelf() )
688 // now delete this key itself
691 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
692 // deleting a key which doesn't exist is not considered an error
693 if ( m_dwLastError
!= ERROR_SUCCESS
&&
694 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
695 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
703 bool wxRegKey::DeleteKey(const wxChar
*szKey
)
708 wxRegKey
key(*this, szKey
);
709 return key
.DeleteSelf();
712 bool wxRegKey::DeleteValue(const wxChar
*szValue
)
717 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, WXSTRINGCAST szValue
);
719 // deleting a value which doesn't exist is not considered an error
720 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
721 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
723 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
724 szValue
, GetName().c_str());
731 // ----------------------------------------------------------------------------
732 // access to values and subkeys
733 // ----------------------------------------------------------------------------
735 // return true if value exists
736 bool wxRegKey::HasValue(const wxChar
*szValue
) const
738 // this function should be silent, so suppress possible messages from Open()
741 if ( !CONST_CAST
Open(Read
) )
744 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
745 WXSTRINGCAST szValue
,
748 return dwRet
== ERROR_SUCCESS
;
751 // returns true if this key has any values
752 bool wxRegKey::HasValues() const
754 // suppress possible messages from GetFirstValue()
757 // just call GetFirstValue with dummy parameters
760 return CONST_CAST
GetFirstValue(str
, l
);
763 // returns true if this key has any subkeys
764 bool wxRegKey::HasSubkeys() const
766 // suppress possible messages from GetFirstKey()
769 // just call GetFirstKey with dummy parameters
772 return CONST_CAST
GetFirstKey(str
, l
);
775 // returns true if given subkey exists
776 bool wxRegKey::HasSubKey(const wxChar
*szKey
) const
778 // this function should be silent, so suppress possible messages from Open()
781 if ( !CONST_CAST
Open(Read
) )
784 return KeyExists(m_hKey
, szKey
);
787 wxRegKey::ValueType
wxRegKey::GetValueType(const wxChar
*szValue
) const
789 if ( ! CONST_CAST
Open(Read
) )
793 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
794 &dwType
, NULL
, NULL
);
795 if ( m_dwLastError
!= ERROR_SUCCESS
) {
796 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
801 return (ValueType
)dwType
;
804 bool wxRegKey::SetValue(const wxChar
*szValue
, long lValue
)
806 if ( CONST_CAST
Open() ) {
807 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
808 (RegString
)&lValue
, sizeof(lValue
));
809 if ( m_dwLastError
== ERROR_SUCCESS
)
813 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
814 GetFullName(this, szValue
));
818 bool wxRegKey::QueryValue(const wxChar
*szValue
, long *plValue
) const
820 if ( CONST_CAST
Open(Read
) ) {
821 DWORD dwType
, dwSize
= sizeof(DWORD
);
822 RegString pBuf
= (RegString
)plValue
;
823 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
824 &dwType
, pBuf
, &dwSize
);
825 if ( m_dwLastError
!= ERROR_SUCCESS
) {
826 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
831 // check that we read the value of right type
832 wxASSERT_MSG( IsNumericValue(szValue
),
833 wxT("Type mismatch in wxRegKey::QueryValue().") );
842 bool wxRegKey::SetValue(const wxChar
*szValue
,const wxMemoryBuffer
& buffer
)
845 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
848 if ( CONST_CAST
Open() ) {
849 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_BINARY
,
850 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
851 if ( m_dwLastError
== ERROR_SUCCESS
)
855 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
856 GetFullName(this, szValue
));
861 bool wxRegKey::QueryValue(const wxChar
*szValue
, wxMemoryBuffer
& buffer
) const
863 if ( CONST_CAST
Open(Read
) ) {
864 // first get the type and size of the data
865 DWORD dwType
, dwSize
;
866 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
867 &dwType
, NULL
, &dwSize
);
869 if ( m_dwLastError
== ERROR_SUCCESS
) {
871 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
872 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
873 WXSTRINGCAST szValue
,
878 buffer
.UngetWriteBuf(dwSize
);
880 buffer
.SetDataLen(0);
885 if ( m_dwLastError
!= ERROR_SUCCESS
) {
886 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
897 bool wxRegKey::QueryValue(const wxChar
*szValue
,
899 bool WXUNUSED_IN_WINCE(raw
)) const
901 if ( CONST_CAST
Open(Read
) )
904 // first get the type and size of the data
905 DWORD dwType
=REG_NONE
, dwSize
=0;
906 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
907 &dwType
, NULL
, &dwSize
);
908 if ( m_dwLastError
== ERROR_SUCCESS
)
912 // must treat this case specially as GetWriteBuf() doesn't like
913 // being called with 0 size
918 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
919 WXSTRINGCAST szValue
,
922 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
925 // expand the var expansions in the string unless disabled
927 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
929 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
, NULL
, 0);
930 bool ok
= dwExpSize
!= 0;
933 wxString strExpValue
;
934 ok
= ::ExpandEnvironmentStrings(strValue
,
935 wxStringBuffer(strExpValue
, dwExpSize
),
938 strValue
= strExpValue
;
943 wxLogLastError(_T("ExpandEnvironmentStrings"));
950 if ( m_dwLastError
== ERROR_SUCCESS
)
952 // check that it was the right type
953 wxASSERT_MSG( !IsNumericValue(szValue
),
954 wxT("Type mismatch in wxRegKey::QueryValue().") );
961 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
962 GetFullName(this, szValue
));
966 bool wxRegKey::SetValue(const wxChar
*szValue
, const wxString
& strValue
)
968 if ( CONST_CAST
Open() ) {
969 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
970 (RegString
)strValue
.c_str(),
971 (strValue
.Len() + 1)*sizeof(wxChar
));
972 if ( m_dwLastError
== ERROR_SUCCESS
)
976 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
977 GetFullName(this, szValue
));
981 wxString
wxRegKey::QueryDefaultValue() const
984 QueryValue(NULL
, str
);
988 // ----------------------------------------------------------------------------
990 // NB: all these functions require an index variable which allows to have
991 // several concurrently running indexations on the same key
992 // ----------------------------------------------------------------------------
994 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1000 return GetNextValue(strValueName
, lIndex
);
1003 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1005 wxASSERT( IsOpened() );
1007 // are we already at the end of enumeration?
1011 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1012 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1014 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1015 szValueName
, &dwValueLen
,
1018 NULL
, // [out] buffer for value
1019 NULL
); // [i/o] it's length
1021 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1022 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1023 m_dwLastError
= ERROR_SUCCESS
;
1027 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1034 strValueName
= szValueName
;
1039 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1045 return GetNextKey(strKeyName
, lIndex
);
1048 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1050 wxASSERT( IsOpened() );
1052 // are we already at the end of enumeration?
1056 wxChar szKeyName
[_MAX_PATH
+ 1];
1059 DWORD sizeName
= WXSIZEOF(szKeyName
);
1060 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1061 0, NULL
, NULL
, NULL
);
1063 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1066 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1067 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1068 m_dwLastError
= ERROR_SUCCESS
;
1072 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1079 strKeyName
= szKeyName
;
1083 // returns true if the value contains a number (else it's some string)
1084 bool wxRegKey::IsNumericValue(const wxChar
*szValue
) const
1086 ValueType type
= GetValueType(szValue
);
1089 /* case Type_Dword_little_endian: == Type_Dword */
1090 case Type_Dword_big_endian
:
1098 // ----------------------------------------------------------------------------
1099 // exporting registry keys to file
1100 // ----------------------------------------------------------------------------
1104 // helper functions for writing ASCII strings (even in Unicode build)
1105 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1111 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1113 // as we open the file in text mode, it is enough to write LF without CR
1114 return WriteAsciiChar(ostr
, '\n');
1117 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1119 return ostr
.Write(p
, strlen(p
)).IsOk();
1122 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1125 wxCharBuffer
name(s
.mb_str());
1126 ostr
.Write(name
, strlen(name
));
1128 ostr
.Write(s
, s
.length());
1134 #endif // wxUSE_STREAMS
1136 bool wxRegKey::Export(const wxString
& filename
) const
1138 #if wxUSE_FFILE && wxUSE_STREAMS
1139 if ( wxFile::Exists(filename
) )
1141 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1146 wxFFileOutputStream
ostr(filename
, _T("w"));
1148 return ostr
.Ok() && Export(ostr
);
1150 wxUnusedVar(filename
);
1156 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1158 // write out the header
1159 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1162 return DoExport(ostr
);
1164 #endif // wxUSE_STREAMS
1168 FormatAsHex(const void *data
,
1170 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1172 wxString
value(_T("hex"));
1174 // binary values use just "hex:" prefix while the other ones must indicate
1176 if ( type
!= wxRegKey::Type_Binary
)
1177 value
<< _T('(') << type
<< _T(')');
1180 // write all the rest as comma-separated bytes
1181 value
.reserve(3*size
+ 10);
1182 const char * const p
= wx_static_cast(const char *, data
);
1183 for ( size_t n
= 0; n
< size
; n
++ )
1185 // TODO: line wrapping: although not required by regedit, this makes
1186 // the generated files easier to read and compare with the files
1187 // produced by regedit
1191 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1198 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1200 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1203 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1206 const ValueType type
= GetValueType(name
);
1212 if ( !QueryValue(name
, value
) )
1215 // quotes and backslashes must be quoted, linefeeds are not
1216 // allowed in string values
1217 rhs
.reserve(value
.length() + 2);
1220 // there can be no NULs here
1221 bool useHex
= false;
1222 for ( const wxChar
*p
= value
.c_str(); *p
&& !useHex
; p
++ )
1227 // we can only represent this string in hex
1233 // escape special symbol
1243 rhs
= FormatAsHex(value
, Type_String
);
1250 /* case Type_Dword_little_endian: == Type_Dword */
1253 if ( !QueryValue(name
, &value
) )
1256 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1260 case Type_Expand_String
:
1261 case Type_Multi_String
:
1264 if ( !QueryRawValue(name
, value
) )
1267 rhs
= FormatAsHex(value
, type
);
1274 if ( !QueryValue(name
, buf
) )
1277 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1281 // no idea how those appear in REGEDIT4 files
1283 case Type_Dword_big_endian
:
1285 case Type_Resource_list
:
1286 case Type_Full_resource_descriptor
:
1287 case Type_Resource_requirements_list
:
1289 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1297 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1299 // first examine the value type: if it's unsupported, simply skip it
1300 // instead of aborting the entire export process because we failed to
1301 // export a single value
1302 wxString value
= FormatValue(name
);
1303 if ( value
.empty() )
1305 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1306 name
.c_str(), GetName().c_str());
1310 // we do have the text representation of the value, now write everything
1313 // special case: unnamed/default value is represented as just "@"
1316 if ( !WriteAsciiChar(ostr
, '@') )
1319 else // normal, named, value
1321 if ( !WriteAsciiChar(ostr
, '"') ||
1322 !WriteAsciiString(ostr
, name
) ||
1323 !WriteAsciiChar(ostr
, '"') )
1327 if ( !WriteAsciiChar(ostr
, '=') )
1330 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1333 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1335 // write out this key name
1336 if ( !WriteAsciiChar(ostr
, '[') )
1339 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1342 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1345 // dump all our values
1348 wxRegKey
& self
= wx_const_cast(wxRegKey
&, *this);
1349 bool cont
= self
.GetFirstValue(name
, dummy
);
1352 if ( !DoExportValue(ostr
, name
) )
1355 cont
= GetNextValue(name
, dummy
);
1358 // always terminate values by blank line, even if there were no values
1359 if ( !WriteAsciiEOL(ostr
) )
1362 // recurse to subkeys
1363 cont
= self
.GetFirstKey(name
, dummy
);
1366 wxRegKey
subkey(*this, name
);
1367 if ( !subkey
.DoExport(ostr
) )
1370 cont
= GetNextKey(name
, dummy
);
1376 #endif // wxUSE_STREAMS
1378 // ============================================================================
1379 // implementation of global private functions
1380 // ============================================================================
1382 bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
)
1384 // don't close this key itself for the case of empty szKey!
1385 if ( wxIsEmpty(szKey
) )
1394 KEY_READ
, // we might not have enough rights for rw access
1396 ) == ERROR_SUCCESS
)
1398 ::RegCloseKey(hkeyDummy
);
1406 const wxChar
*GetFullName(const wxRegKey
*pKey
, const wxChar
*szValue
)
1408 static wxString s_str
;
1409 s_str
= pKey
->GetName();
1410 if ( !wxIsEmpty(szValue
) )
1411 s_str
<< wxT("\\") << szValue
;
1413 return s_str
.c_str();
1416 void RemoveTrailingSeparator(wxString
& str
)
1418 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1419 str
.Truncate(str
.Len() - 1);