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
);
147 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
148 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
149 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
154 if ( ui
== nStdKeys
) {
155 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
160 strKey
= strKey
.After(REG_SEPARATOR
);
161 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
162 strKey
.Truncate(strKey
.Len() - 1);
168 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
170 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
171 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
175 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
180 // ----------------------------------------------------------------------------
182 // ----------------------------------------------------------------------------
186 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
191 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
193 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
198 // parent is a predefined (and preopened) key
199 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
201 RemoveTrailingSeparator(m_strKey
);
202 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
207 // parent is a normal regkey
208 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
209 : m_strKey(keyParent
.m_strKey
)
211 // combine our name with parent's to get the full name
212 if ( !m_strKey
.empty() &&
213 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
214 m_strKey
+= REG_SEPARATOR
;
218 RemoveTrailingSeparator(m_strKey
);
220 m_hRootKey
= keyParent
.m_hRootKey
;
225 // dtor closes the key releasing system resource
226 wxRegKey::~wxRegKey()
231 // ----------------------------------------------------------------------------
232 // change the key name/hkey
233 // ----------------------------------------------------------------------------
235 // set the full key name
236 void wxRegKey::SetName(const wxString
& strKey
)
241 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
244 // the name is relative to the parent key
245 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
250 RemoveTrailingSeparator(m_strKey
);
251 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
254 // the name is relative to the parent key
255 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
259 // combine our name with parent's to get the full name
261 // NB: this method is called by wxRegConfig::SetPath() which is a performance
262 // critical function and so it preallocates space for our m_strKey to
263 // gain some speed - this is why we only use += here and not = which
264 // would just free the prealloc'd buffer and would have to realloc it the
267 m_strKey
+= keyParent
.m_strKey
;
268 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
269 m_strKey
+= REG_SEPARATOR
;
272 RemoveTrailingSeparator(m_strKey
);
274 m_hRootKey
= keyParent
.m_hRootKey
;
277 // hKey should be opened and will be closed in wxRegKey dtor
278 void wxRegKey::SetHkey(WXHKEY hKey
)
285 // ----------------------------------------------------------------------------
286 // info about the key
287 // ----------------------------------------------------------------------------
289 // returns true if the key exists
290 bool wxRegKey::Exists() const
292 // opened key has to exist, try to open it if not done yet
293 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
);
296 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
297 wxString
wxRegKey::GetName(bool bShortPrefix
) const
299 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
300 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
301 : aStdKeys
[key
].szName
;
302 if ( !m_strKey
.empty() )
303 str
<< _T("\\") << m_strKey
;
308 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
311 size_t *pnMaxValueLen
) const
313 // old gcc headers incorrectly prototype RegQueryInfoKey()
314 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
315 #define REG_PARAM (size_t *)
317 #define REG_PARAM (LPDWORD)
320 // it might be unexpected to some that this function doesn't open the key
321 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
323 m_dwLastError
= ::RegQueryInfoKey
327 NULL
, // (ptr to) size of class name buffer
330 pnSubKeys
, // [out] number of subkeys
332 pnMaxKeyLen
, // [out] max length of a subkey name
333 NULL
, // longest subkey class name
335 pnValues
, // [out] number of values
337 pnMaxValueLen
, // [out] max length of a value name
338 NULL
, // longest value data
339 NULL
, // security descriptor
340 NULL
// time of last modification
345 if ( m_dwLastError
!= ERROR_SUCCESS
) {
346 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
354 // ----------------------------------------------------------------------------
356 // ----------------------------------------------------------------------------
358 // opens key (it's not an error to call Open() on an already opened key)
359 bool wxRegKey::Open(AccessMode mode
)
363 if ( mode
<= m_mode
)
366 // we had been opened in read mode but now must be reopened in write
371 m_dwLastError
= ::RegOpenKeyEx
376 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
380 if ( m_dwLastError
!= ERROR_SUCCESS
)
382 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
387 m_hKey
= (WXHKEY
) tmpKey
;
393 // creates key, failing if it exists and !bOkIfExists
394 bool wxRegKey::Create(bool bOkIfExists
)
396 // check for existence only if asked (i.e. order is important!)
397 if ( !bOkIfExists
&& Exists() )
406 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
,
408 NULL
, // class string
415 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
417 if ( m_dwLastError
!= ERROR_SUCCESS
) {
418 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
424 m_hKey
= (WXHKEY
) tmpKey
;
429 // close the key, it's not an error to call it when not opened
430 bool wxRegKey::Close()
433 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
436 if ( m_dwLastError
!= ERROR_SUCCESS
) {
437 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
447 bool wxRegKey::RenameValue(const wxChar
*szValueOld
, const wxChar
*szValueNew
)
450 if ( HasValue(szValueNew
) ) {
451 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
457 !CopyValue(szValueOld
, *this, szValueNew
) ||
458 !DeleteValue(szValueOld
) ) {
459 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
460 szValueOld
, szValueNew
);
468 bool wxRegKey::CopyValue(const wxChar
*szValue
,
470 const wxChar
*szValueNew
)
473 // by default, use the same name
474 szValueNew
= szValue
;
477 switch ( GetValueType(szValue
) ) {
481 return QueryValue(szValue
, strVal
) &&
482 keyDst
.SetValue(szValueNew
, strVal
);
486 /* case Type_Dword_little_endian: == Type_Dword */
489 return QueryValue(szValue
, &dwVal
) &&
490 keyDst
.SetValue(szValueNew
, dwVal
);
496 return QueryValue(szValue
,buf
) &&
497 keyDst
.SetValue(szValueNew
,buf
);
500 // these types are unsupported because I am not sure about how
501 // exactly they should be copied and because they shouldn't
502 // occur among the application keys (supposedly created with
505 case Type_Expand_String
:
506 case Type_Dword_big_endian
:
508 case Type_Multi_String
:
509 case Type_Resource_list
:
510 case Type_Full_resource_descriptor
:
511 case Type_Resource_requirements_list
:
513 wxLogError(_("Can't copy values of unsupported type %d."),
514 GetValueType(szValue
));
519 bool wxRegKey::Rename(const wxChar
*szNewName
)
521 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
524 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
530 // do we stay in the same hive?
531 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
533 // construct the full new name of the key
537 // rename the key to the new name under the same parent
538 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
539 if ( !strKey
.empty() ) {
540 // don't add '\\' in the start if strFullNewName is empty
541 strKey
+= REG_SEPARATOR
;
546 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
549 // this is the full name already
550 keyDst
.SetName(szNewName
);
553 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
555 wxLogError(_("Registry key '%s' already exists."),
556 GetFullName(&keyDst
));
559 ok
= Copy(keyDst
) && DeleteSelf();
563 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
564 GetFullName(this), GetFullName(&keyDst
));
567 m_hRootKey
= keyDst
.m_hRootKey
;
568 m_strKey
= keyDst
.m_strKey
;
574 bool wxRegKey::Copy(const wxChar
*szNewName
)
576 // create the new key first
577 wxRegKey
keyDst(szNewName
);
578 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
582 // we created the dest key but copying to it failed - delete it
584 (void)keyDst
.DeleteSelf();
591 bool wxRegKey::Copy(wxRegKey
& keyDst
)
595 // copy all sub keys to the new location
598 bool bCont
= GetFirstKey(strKey
, lIndex
);
599 while ( ok
&& bCont
) {
600 wxRegKey
key(*this, strKey
);
602 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
603 ok
= key
.Copy((const wxChar
*) keyName
);
606 bCont
= GetNextKey(strKey
, lIndex
);
608 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
609 GetFullName(&key
), keyName
.c_str());
615 bCont
= GetFirstValue(strVal
, lIndex
);
616 while ( ok
&& bCont
) {
617 ok
= CopyValue(strVal
, keyDst
);
620 wxLogSysError(m_dwLastError
,
621 _("Failed to copy registry value '%s'"),
625 bCont
= GetNextValue(strVal
, lIndex
);
630 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
631 GetFullName(this), GetFullName(&keyDst
));
637 // ----------------------------------------------------------------------------
638 // delete keys/values
639 // ----------------------------------------------------------------------------
640 bool wxRegKey::DeleteSelf()
645 // it already doesn't exist - ok!
650 // prevent a buggy program from erasing one of the root registry keys or an
651 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
652 // key except HKCR (HKCR has some "deleteable" subkeys)
653 if ( m_strKey
.empty() ||
654 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
655 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
656 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
662 // we can't delete keys while enumerating because it confuses GetNextKey, so
663 // we first save the key names and then delete them all
664 wxArrayString astrSubkeys
;
668 bool bCont
= GetFirstKey(strKey
, lIndex
);
670 astrSubkeys
.Add(strKey
);
672 bCont
= GetNextKey(strKey
, lIndex
);
675 size_t nKeyCount
= astrSubkeys
.Count();
676 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
677 wxRegKey
key(*this, astrSubkeys
[nKey
]);
678 if ( !key
.DeleteSelf() )
682 // now delete this key itself
685 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
686 // deleting a key which doesn't exist is not considered an error
687 if ( m_dwLastError
!= ERROR_SUCCESS
&&
688 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
689 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
697 bool wxRegKey::DeleteKey(const wxChar
*szKey
)
702 wxRegKey
key(*this, szKey
);
703 return key
.DeleteSelf();
706 bool wxRegKey::DeleteValue(const wxChar
*szValue
)
711 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, WXSTRINGCAST szValue
);
713 // deleting a value which doesn't exist is not considered an error
714 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
715 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
717 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
718 szValue
, GetName().c_str());
725 // ----------------------------------------------------------------------------
726 // access to values and subkeys
727 // ----------------------------------------------------------------------------
729 // return true if value exists
730 bool wxRegKey::HasValue(const wxChar
*szValue
) const
732 // this function should be silent, so suppress possible messages from Open()
735 if ( !CONST_CAST
Open(Read
) )
738 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
739 WXSTRINGCAST szValue
,
742 return dwRet
== ERROR_SUCCESS
;
745 // returns true if this key has any values
746 bool wxRegKey::HasValues() const
748 // suppress possible messages from GetFirstValue()
751 // just call GetFirstValue with dummy parameters
754 return CONST_CAST
GetFirstValue(str
, l
);
757 // returns true if this key has any subkeys
758 bool wxRegKey::HasSubkeys() const
760 // suppress possible messages from GetFirstKey()
763 // just call GetFirstKey with dummy parameters
766 return CONST_CAST
GetFirstKey(str
, l
);
769 // returns true if given subkey exists
770 bool wxRegKey::HasSubKey(const wxChar
*szKey
) const
772 // this function should be silent, so suppress possible messages from Open()
775 if ( !CONST_CAST
Open(Read
) )
778 return KeyExists(m_hKey
, szKey
);
781 wxRegKey::ValueType
wxRegKey::GetValueType(const wxChar
*szValue
) const
783 if ( ! CONST_CAST
Open(Read
) )
787 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
788 &dwType
, NULL
, NULL
);
789 if ( m_dwLastError
!= ERROR_SUCCESS
) {
790 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
795 return (ValueType
)dwType
;
798 bool wxRegKey::SetValue(const wxChar
*szValue
, long lValue
)
800 if ( CONST_CAST
Open() ) {
801 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
802 (RegString
)&lValue
, sizeof(lValue
));
803 if ( m_dwLastError
== ERROR_SUCCESS
)
807 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
808 GetFullName(this, szValue
));
812 bool wxRegKey::QueryValue(const wxChar
*szValue
, long *plValue
) const
814 if ( CONST_CAST
Open(Read
) ) {
815 DWORD dwType
, dwSize
= sizeof(DWORD
);
816 RegString pBuf
= (RegString
)plValue
;
817 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
818 &dwType
, pBuf
, &dwSize
);
819 if ( m_dwLastError
!= ERROR_SUCCESS
) {
820 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
825 // check that we read the value of right type
826 wxASSERT_MSG( IsNumericValue(szValue
),
827 wxT("Type mismatch in wxRegKey::QueryValue().") );
836 bool wxRegKey::SetValue(const wxChar
*szValue
,const wxMemoryBuffer
& buffer
)
839 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
842 if ( CONST_CAST
Open() ) {
843 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_BINARY
,
844 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
845 if ( m_dwLastError
== ERROR_SUCCESS
)
849 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
850 GetFullName(this, szValue
));
855 bool wxRegKey::QueryValue(const wxChar
*szValue
, wxMemoryBuffer
& buffer
) const
857 if ( CONST_CAST
Open(Read
) ) {
858 // first get the type and size of the data
859 DWORD dwType
, dwSize
;
860 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
861 &dwType
, NULL
, &dwSize
);
863 if ( m_dwLastError
== ERROR_SUCCESS
) {
865 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
866 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
867 WXSTRINGCAST szValue
,
872 buffer
.UngetWriteBuf(dwSize
);
874 buffer
.SetDataLen(0);
879 if ( m_dwLastError
!= ERROR_SUCCESS
) {
880 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
891 bool wxRegKey::QueryValue(const wxChar
*szValue
,
893 bool WXUNUSED_IN_WINCE(raw
)) const
895 if ( CONST_CAST
Open(Read
) )
898 // first get the type and size of the data
899 DWORD dwType
=REG_NONE
, dwSize
=0;
900 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, WXSTRINGCAST szValue
, RESERVED
,
901 &dwType
, NULL
, &dwSize
);
902 if ( m_dwLastError
== ERROR_SUCCESS
)
906 // must treat this case specially as GetWriteBuf() doesn't like
907 // being called with 0 size
912 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
913 WXSTRINGCAST szValue
,
916 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
919 // expand the var expansions in the string unless disabled
921 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
923 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
, NULL
, 0);
924 bool ok
= dwExpSize
!= 0;
927 wxString strExpValue
;
928 ok
= ::ExpandEnvironmentStrings(strValue
,
929 wxStringBuffer(strExpValue
, dwExpSize
),
932 strValue
= strExpValue
;
937 wxLogLastError(_T("ExpandEnvironmentStrings"));
944 if ( m_dwLastError
== ERROR_SUCCESS
)
946 // check that it was the right type
947 wxASSERT_MSG( !IsNumericValue(szValue
),
948 wxT("Type mismatch in wxRegKey::QueryValue().") );
955 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
956 GetFullName(this, szValue
));
960 bool wxRegKey::SetValue(const wxChar
*szValue
, const wxString
& strValue
)
962 if ( CONST_CAST
Open() ) {
963 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
964 (RegString
)strValue
.c_str(),
965 (strValue
.Len() + 1)*sizeof(wxChar
));
966 if ( m_dwLastError
== ERROR_SUCCESS
)
970 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
971 GetFullName(this, szValue
));
975 wxString
wxRegKey::QueryDefaultValue() const
978 QueryValue(NULL
, str
);
982 // ----------------------------------------------------------------------------
984 // NB: all these functions require an index variable which allows to have
985 // several concurrently running indexations on the same key
986 // ----------------------------------------------------------------------------
988 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
994 return GetNextValue(strValueName
, lIndex
);
997 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
999 wxASSERT( IsOpened() );
1001 // are we already at the end of enumeration?
1005 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1006 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1008 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1009 szValueName
, &dwValueLen
,
1012 NULL
, // [out] buffer for value
1013 NULL
); // [i/o] it's length
1015 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1016 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1017 m_dwLastError
= ERROR_SUCCESS
;
1021 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1028 strValueName
= szValueName
;
1033 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1039 return GetNextKey(strKeyName
, lIndex
);
1042 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1044 wxASSERT( IsOpened() );
1046 // are we already at the end of enumeration?
1050 wxChar szKeyName
[_MAX_PATH
+ 1];
1053 DWORD sizeName
= WXSIZEOF(szKeyName
);
1054 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1055 0, NULL
, NULL
, NULL
);
1057 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1060 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1061 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1062 m_dwLastError
= ERROR_SUCCESS
;
1066 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1073 strKeyName
= szKeyName
;
1077 // returns true if the value contains a number (else it's some string)
1078 bool wxRegKey::IsNumericValue(const wxChar
*szValue
) const
1080 ValueType type
= GetValueType(szValue
);
1083 /* case Type_Dword_little_endian: == Type_Dword */
1084 case Type_Dword_big_endian
:
1092 // ----------------------------------------------------------------------------
1093 // exporting registry keys to file
1094 // ----------------------------------------------------------------------------
1098 // helper functions for writing ASCII strings (even in Unicode build)
1099 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1105 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1107 // as we open the file in text mode, it is enough to write LF without CR
1108 return WriteAsciiChar(ostr
, '\n');
1111 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1113 return ostr
.Write(p
, strlen(p
)).IsOk();
1116 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1119 wxCharBuffer
name(s
.mb_str());
1120 ostr
.Write(name
, strlen(name
));
1122 ostr
.Write(s
, s
.length());
1128 #endif // wxUSE_STREAMS
1130 bool wxRegKey::Export(const wxString
& filename
) const
1132 #if wxUSE_FFILE && wxUSE_STREAMS
1133 if ( wxFile::Exists(filename
) )
1135 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1140 wxFFileOutputStream
ostr(filename
, _T("w"));
1142 return ostr
.Ok() && Export(ostr
);
1144 wxUnusedVar(filename
);
1150 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1152 // write out the header
1153 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1156 return DoExport(ostr
);
1158 #endif // wxUSE_STREAMS
1162 FormatAsHex(const void *data
,
1164 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1166 wxString
value(_T("hex"));
1168 // binary values use just "hex:" prefix while the other ones must indicate
1170 if ( type
!= wxRegKey::Type_Binary
)
1171 value
<< _T('(') << type
<< _T(')');
1174 // write all the rest as comma-separated bytes
1175 value
.reserve(3*size
+ 10);
1176 const char * const p
= wx_static_cast(const char *, data
);
1177 for ( size_t n
= 0; n
< size
; n
++ )
1179 // TODO: line wrapping: although not required by regedit, this makes
1180 // the generated files easier to read and compare with the files
1181 // produced by regedit
1185 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1192 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1194 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1197 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1200 const ValueType type
= GetValueType(name
);
1206 if ( !QueryValue(name
, value
) )
1209 // quotes and backslashes must be quoted, linefeeds are not
1210 // allowed in string values
1211 rhs
.reserve(value
.length() + 2);
1214 // there can be no NULs here
1215 bool useHex
= false;
1216 for ( const wxChar
*p
= value
.c_str(); *p
&& !useHex
; p
++ )
1221 // we can only represent this string in hex
1227 // escape special symbol
1237 rhs
= FormatAsHex(value
, Type_String
);
1244 /* case Type_Dword_little_endian: == Type_Dword */
1247 if ( !QueryValue(name
, &value
) )
1250 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1254 case Type_Expand_String
:
1255 case Type_Multi_String
:
1258 if ( !QueryRawValue(name
, value
) )
1261 rhs
= FormatAsHex(value
, type
);
1268 if ( !QueryValue(name
, buf
) )
1271 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1275 // no idea how those appear in REGEDIT4 files
1277 case Type_Dword_big_endian
:
1279 case Type_Resource_list
:
1280 case Type_Full_resource_descriptor
:
1281 case Type_Resource_requirements_list
:
1283 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1291 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1293 // first examine the value type: if it's unsupported, simply skip it
1294 // instead of aborting the entire export process because we failed to
1295 // export a single value
1296 wxString value
= FormatValue(name
);
1297 if ( value
.empty() )
1299 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1300 name
.c_str(), GetName().c_str());
1304 // we do have the text representation of the value, now write everything
1307 // special case: unnamed/default value is represented as just "@"
1310 if ( !WriteAsciiChar(ostr
, '@') )
1313 else // normal, named, value
1315 if ( !WriteAsciiChar(ostr
, '"') ||
1316 !WriteAsciiString(ostr
, name
) ||
1317 !WriteAsciiChar(ostr
, '"') )
1321 if ( !WriteAsciiChar(ostr
, '=') )
1324 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1327 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1329 // write out this key name
1330 if ( !WriteAsciiChar(ostr
, '[') )
1333 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1336 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1339 // dump all our values
1342 wxRegKey
& self
= wx_const_cast(wxRegKey
&, *this);
1343 bool cont
= self
.GetFirstValue(name
, dummy
);
1346 if ( !DoExportValue(ostr
, name
) )
1349 cont
= GetNextValue(name
, dummy
);
1352 // always terminate values by blank line, even if there were no values
1353 if ( !WriteAsciiEOL(ostr
) )
1356 // recurse to subkeys
1357 cont
= self
.GetFirstKey(name
, dummy
);
1360 wxRegKey
subkey(*this, name
);
1361 if ( !subkey
.DoExport(ostr
) )
1364 cont
= GetNextKey(name
, dummy
);
1370 #endif // wxUSE_STREAMS
1372 // ============================================================================
1373 // implementation of global private functions
1374 // ============================================================================
1376 bool KeyExists(WXHKEY hRootKey
, const wxChar
*szKey
)
1378 // don't close this key itself for the case of empty szKey!
1379 if ( wxIsEmpty(szKey
) )
1388 KEY_READ
, // we might not have enough rights for rw access
1390 ) == ERROR_SUCCESS
)
1392 ::RegCloseKey(hkeyDummy
);
1400 const wxChar
*GetFullName(const wxRegKey
*pKey
, const wxChar
*szValue
)
1402 static wxString s_str
;
1403 s_str
= pKey
->GetName();
1404 if ( !wxIsEmpty(szValue
) )
1405 s_str
<< wxT("\\") << szValue
;
1407 return s_str
.c_str();
1410 void RemoveTrailingSeparator(wxString
& str
)
1412 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1413 str
.Truncate(str
.Len() - 1);