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"
25 #include "wx/msw/wrapwin.h"
26 #include "wx/string.h"
33 #include "wx/wfstream.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 #ifndef HKEY_PERFORMANCE_DATA
58 #define HKEY_PERFORMANCE_DATA ((HKEY)0x80000004)
61 #ifndef HKEY_CURRENT_CONFIG
62 #define HKEY_CURRENT_CONFIG ((HKEY)0x80000005)
66 #define HKEY_DYN_DATA ((HKEY)0x80000006)
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // the standard key names, short names and handles all bundled together for
79 const wxChar
*szShortName
;
83 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
84 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
85 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
86 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
87 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
88 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
89 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
92 // the registry name separator (perhaps one day MS will change it to '/' ;-)
93 #define REG_SEPARATOR wxT('\\')
95 // useful for Windows programmers: makes somewhat more clear all these zeroes
96 // being passed to Windows APIs
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // const_cast<> is not yet supported by all compilers
104 #define CONST_CAST ((wxRegKey *)this)->
106 // and neither is mutable which m_dwLastError should be
107 #define m_dwLastError CONST_CAST m_dwLastError
109 // ----------------------------------------------------------------------------
110 // non member functions
111 // ----------------------------------------------------------------------------
113 // removes the trailing backslash from the string if it has one
114 static inline void RemoveTrailingSeparator(wxString
& str
);
116 // returns true if given registry key exists
117 static bool KeyExists(WXHKEY hRootKey
, const wxString
& szKey
);
119 // combines value and key name
120 static wxString
GetFullName(const wxRegKey
*pKey
);
121 static wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
);
123 // returns "value" argument of wxRegKey methods converted into a value that can
124 // be passed to win32 registry functions; specifically, converts empty string
126 static inline const wxChar
*RegValueStr(const wxString
& szValue
);
128 // ============================================================================
129 // implementation of wxRegKey class
130 // ============================================================================
132 // ----------------------------------------------------------------------------
133 // static functions and variables
134 // ----------------------------------------------------------------------------
136 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
138 // @@ should take a `StdKey key', but as it's often going to be used in loops
139 // it would require casts in user code.
140 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
142 // return empty string if key is invalid
143 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
145 return aStdKeys
[key
].szName
;
148 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
150 // return empty string if key is invalid
151 wxCHECK( key
< nStdKeys
, wxEmptyString
);
153 return aStdKeys
[key
].szShortName
;
156 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
158 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
161 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
162 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
163 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
168 if ( ui
== nStdKeys
) {
169 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
174 strKey
= strKey
.After(REG_SEPARATOR
);
175 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
176 strKey
.Truncate(strKey
.Len() - 1);
182 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
184 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
185 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
189 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
194 // ----------------------------------------------------------------------------
196 // ----------------------------------------------------------------------------
200 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
205 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
207 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
212 // parent is a predefined (and preopened) key
213 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
215 RemoveTrailingSeparator(m_strKey
);
216 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
221 // parent is a normal regkey
222 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
223 : m_strKey(keyParent
.m_strKey
)
225 // combine our name with parent's to get the full name
226 if ( !m_strKey
.empty() &&
227 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
228 m_strKey
+= REG_SEPARATOR
;
232 RemoveTrailingSeparator(m_strKey
);
234 m_hRootKey
= keyParent
.m_hRootKey
;
239 // dtor closes the key releasing system resource
240 wxRegKey::~wxRegKey()
245 // ----------------------------------------------------------------------------
246 // change the key name/hkey
247 // ----------------------------------------------------------------------------
249 // set the full key name
250 void wxRegKey::SetName(const wxString
& strKey
)
255 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
258 // the name is relative to the parent key
259 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
264 RemoveTrailingSeparator(m_strKey
);
265 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
268 // the name is relative to the parent key
269 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
273 // combine our name with parent's to get the full name
275 // NB: this method is called by wxRegConfig::SetPath() which is a performance
276 // critical function and so it preallocates space for our m_strKey to
277 // gain some speed - this is why we only use += here and not = which
278 // would just free the prealloc'd buffer and would have to realloc it the
281 m_strKey
+= keyParent
.m_strKey
;
282 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
283 m_strKey
+= REG_SEPARATOR
;
286 RemoveTrailingSeparator(m_strKey
);
288 m_hRootKey
= keyParent
.m_hRootKey
;
291 // hKey should be opened and will be closed in wxRegKey dtor
292 void wxRegKey::SetHkey(WXHKEY hKey
)
299 // ----------------------------------------------------------------------------
300 // info about the key
301 // ----------------------------------------------------------------------------
303 // returns true if the key exists
304 bool wxRegKey::Exists() const
306 // opened key has to exist, try to open it if not done yet
307 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
.wx_str());
310 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
311 wxString
wxRegKey::GetName(bool bShortPrefix
) const
313 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
314 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
315 : aStdKeys
[key
].szName
;
316 if ( !m_strKey
.empty() )
317 str
<< _T("\\") << m_strKey
;
322 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
325 size_t *pnMaxValueLen
) const
327 // old gcc headers incorrectly prototype RegQueryInfoKey()
328 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
329 #define REG_PARAM (size_t *)
331 #define REG_PARAM (LPDWORD)
334 // it might be unexpected to some that this function doesn't open the key
335 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
337 m_dwLastError
= ::RegQueryInfoKey
341 NULL
, // (ptr to) size of class name buffer
344 pnSubKeys
, // [out] number of subkeys
346 pnMaxKeyLen
, // [out] max length of a subkey name
347 NULL
, // longest subkey class name
349 pnValues
, // [out] number of values
351 pnMaxValueLen
, // [out] max length of a value name
352 NULL
, // longest value data
353 NULL
, // security descriptor
354 NULL
// time of last modification
359 if ( m_dwLastError
!= ERROR_SUCCESS
) {
360 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
368 // ----------------------------------------------------------------------------
370 // ----------------------------------------------------------------------------
372 // opens key (it's not an error to call Open() on an already opened key)
373 bool wxRegKey::Open(AccessMode mode
)
377 if ( mode
<= m_mode
)
380 // we had been opened in read mode but now must be reopened in write
385 m_dwLastError
= ::RegOpenKeyEx
390 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
394 if ( m_dwLastError
!= ERROR_SUCCESS
)
396 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
401 m_hKey
= (WXHKEY
) tmpKey
;
407 // creates key, failing if it exists and !bOkIfExists
408 bool wxRegKey::Create(bool bOkIfExists
)
410 // check for existence only if asked (i.e. order is important!)
411 if ( !bOkIfExists
&& Exists() )
420 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.wx_str(),
422 NULL
, // class string
429 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
.t_str(), &tmpKey
);
431 if ( m_dwLastError
!= ERROR_SUCCESS
) {
432 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
438 m_hKey
= (WXHKEY
) tmpKey
;
443 // close the key, it's not an error to call it when not opened
444 bool wxRegKey::Close()
447 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
450 if ( m_dwLastError
!= ERROR_SUCCESS
) {
451 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
462 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
465 if ( HasValue(szValueNew
) ) {
466 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
472 !CopyValue(szValueOld
, *this, szValueNew
) ||
473 !DeleteValue(szValueOld
) ) {
474 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
475 szValueOld
, szValueNew
);
483 bool wxRegKey::CopyValue(const wxString
& szValue
,
485 const wxString
& szValueNew
)
487 wxString
valueNew(szValueNew
);
488 if ( valueNew
.empty() ) {
489 // by default, use the same name
493 switch ( GetValueType(szValue
) ) {
497 return QueryValue(szValue
, strVal
) &&
498 keyDst
.SetValue(valueNew
, strVal
);
502 /* case Type_Dword_little_endian: == Type_Dword */
505 return QueryValue(szValue
, &dwVal
) &&
506 keyDst
.SetValue(valueNew
, dwVal
);
512 return QueryValue(szValue
,buf
) &&
513 keyDst
.SetValue(valueNew
,buf
);
516 // these types are unsupported because I am not sure about how
517 // exactly they should be copied and because they shouldn't
518 // occur among the application keys (supposedly created with
521 case Type_Expand_String
:
522 case Type_Dword_big_endian
:
524 case Type_Multi_String
:
525 case Type_Resource_list
:
526 case Type_Full_resource_descriptor
:
527 case Type_Resource_requirements_list
:
529 wxLogError(_("Can't copy values of unsupported type %d."),
530 GetValueType(szValue
));
535 bool wxRegKey::Rename(const wxString
& szNewName
)
537 wxCHECK_MSG( !m_strKey
.empty(), false, _T("registry hives can't be renamed") );
540 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
546 // do we stay in the same hive?
547 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
549 // construct the full new name of the key
553 // rename the key to the new name under the same parent
554 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
555 if ( !strKey
.empty() ) {
556 // don't add '\\' in the start if strFullNewName is empty
557 strKey
+= REG_SEPARATOR
;
562 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
565 // this is the full name already
566 keyDst
.SetName(szNewName
);
569 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
571 wxLogError(_("Registry key '%s' already exists."),
572 GetFullName(&keyDst
));
575 ok
= Copy(keyDst
) && DeleteSelf();
579 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
580 GetFullName(this), GetFullName(&keyDst
));
583 m_hRootKey
= keyDst
.m_hRootKey
;
584 m_strKey
= keyDst
.m_strKey
;
590 bool wxRegKey::Copy(const wxString
& szNewName
)
592 // create the new key first
593 wxRegKey
keyDst(szNewName
);
594 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
598 // we created the dest key but copying to it failed - delete it
600 (void)keyDst
.DeleteSelf();
607 bool wxRegKey::Copy(wxRegKey
& keyDst
)
611 // copy all sub keys to the new location
614 bool bCont
= GetFirstKey(strKey
, lIndex
);
615 while ( ok
&& bCont
) {
616 wxRegKey
key(*this, strKey
);
618 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
619 ok
= key
.Copy(keyName
);
622 bCont
= GetNextKey(strKey
, lIndex
);
624 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
625 GetFullName(&key
), keyName
.c_str());
631 bCont
= GetFirstValue(strVal
, lIndex
);
632 while ( ok
&& bCont
) {
633 ok
= CopyValue(strVal
, keyDst
);
636 wxLogSysError(m_dwLastError
,
637 _("Failed to copy registry value '%s'"),
641 bCont
= GetNextValue(strVal
, lIndex
);
646 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
647 GetFullName(this), GetFullName(&keyDst
));
653 // ----------------------------------------------------------------------------
654 // delete keys/values
655 // ----------------------------------------------------------------------------
656 bool wxRegKey::DeleteSelf()
661 // it already doesn't exist - ok!
666 // prevent a buggy program from erasing one of the root registry keys or an
667 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
668 // key except HKCR (HKCR has some "deleteable" subkeys)
669 if ( m_strKey
.empty() ||
670 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
671 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
672 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
678 // we can't delete keys while enumerating because it confuses GetNextKey, so
679 // we first save the key names and then delete them all
680 wxArrayString astrSubkeys
;
684 bool bCont
= GetFirstKey(strKey
, lIndex
);
686 astrSubkeys
.Add(strKey
);
688 bCont
= GetNextKey(strKey
, lIndex
);
691 size_t nKeyCount
= astrSubkeys
.Count();
692 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
693 wxRegKey
key(*this, astrSubkeys
[nKey
]);
694 if ( !key
.DeleteSelf() )
698 // now delete this key itself
701 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
702 // deleting a key which doesn't exist is not considered an error
703 if ( m_dwLastError
!= ERROR_SUCCESS
&&
704 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
705 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
713 bool wxRegKey::DeleteKey(const wxString
& szKey
)
718 wxRegKey
key(*this, szKey
);
719 return key
.DeleteSelf();
722 bool wxRegKey::DeleteValue(const wxString
& szValue
)
727 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
729 // deleting a value which doesn't exist is not considered an error
730 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
731 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
733 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
734 szValue
, GetName().c_str());
741 // ----------------------------------------------------------------------------
742 // access to values and subkeys
743 // ----------------------------------------------------------------------------
745 // return true if value exists
746 bool wxRegKey::HasValue(const wxString
& szValue
) const
748 // this function should be silent, so suppress possible messages from Open()
751 if ( !CONST_CAST
Open(Read
) )
754 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
755 RegValueStr(szValue
),
758 return dwRet
== ERROR_SUCCESS
;
761 // returns true if this key has any values
762 bool wxRegKey::HasValues() const
764 // suppress possible messages from GetFirstValue()
767 // just call GetFirstValue with dummy parameters
770 return CONST_CAST
GetFirstValue(str
, l
);
773 // returns true if this key has any subkeys
774 bool wxRegKey::HasSubkeys() const
776 // suppress possible messages from GetFirstKey()
779 // just call GetFirstKey with dummy parameters
782 return CONST_CAST
GetFirstKey(str
, l
);
785 // returns true if given subkey exists
786 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
788 // this function should be silent, so suppress possible messages from Open()
791 if ( !CONST_CAST
Open(Read
) )
794 return KeyExists(m_hKey
, szKey
);
797 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
799 if ( ! CONST_CAST
Open(Read
) )
803 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
804 &dwType
, NULL
, NULL
);
805 if ( m_dwLastError
!= ERROR_SUCCESS
) {
806 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
811 return (ValueType
)dwType
;
814 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
816 if ( CONST_CAST
Open() ) {
817 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
818 (DWORD
) RESERVED
, REG_DWORD
,
819 (RegString
)&lValue
, sizeof(lValue
));
820 if ( m_dwLastError
== ERROR_SUCCESS
)
824 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
825 GetFullName(this, szValue
));
829 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
831 if ( CONST_CAST
Open(Read
) ) {
832 DWORD dwType
, dwSize
= sizeof(DWORD
);
833 RegString pBuf
= (RegString
)plValue
;
834 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
836 &dwType
, pBuf
, &dwSize
);
837 if ( m_dwLastError
!= ERROR_SUCCESS
) {
838 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
843 // check that we read the value of right type
844 wxASSERT_MSG( IsNumericValue(szValue
),
845 wxT("Type mismatch in wxRegKey::QueryValue().") );
854 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
857 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
860 if ( CONST_CAST
Open() ) {
861 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
862 (DWORD
) RESERVED
, REG_BINARY
,
863 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
864 if ( m_dwLastError
== ERROR_SUCCESS
)
868 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
869 GetFullName(this, szValue
));
874 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
876 if ( CONST_CAST
Open(Read
) ) {
877 // first get the type and size of the data
878 DWORD dwType
, dwSize
;
879 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
881 &dwType
, NULL
, &dwSize
);
883 if ( m_dwLastError
== ERROR_SUCCESS
) {
885 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
886 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
887 RegValueStr(szValue
),
892 buffer
.UngetWriteBuf(dwSize
);
894 buffer
.SetDataLen(0);
899 if ( m_dwLastError
!= ERROR_SUCCESS
) {
900 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
911 bool wxRegKey::QueryValue(const wxString
& szValue
,
913 bool WXUNUSED_IN_WINCE(raw
)) const
915 if ( CONST_CAST
Open(Read
) )
918 // first get the type and size of the data
919 DWORD dwType
=REG_NONE
, dwSize
=0;
920 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
921 RegValueStr(szValue
),
923 &dwType
, NULL
, &dwSize
);
924 if ( m_dwLastError
== ERROR_SUCCESS
)
928 // must treat this case specially as GetWriteBuf() doesn't like
929 // being called with 0 size
934 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
935 RegValueStr(szValue
),
938 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
941 // expand the var expansions in the string unless disabled
943 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
945 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
946 bool ok
= dwExpSize
!= 0;
949 wxString strExpValue
;
950 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
951 wxStringBuffer(strExpValue
, dwExpSize
),
954 strValue
= strExpValue
;
959 wxLogLastError(_T("ExpandEnvironmentStrings"));
966 if ( m_dwLastError
== ERROR_SUCCESS
)
968 // check that it was the right type
969 wxASSERT_MSG( !IsNumericValue(szValue
),
970 wxT("Type mismatch in wxRegKey::QueryValue().") );
977 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
978 GetFullName(this, szValue
));
982 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
984 if ( CONST_CAST
Open() ) {
985 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
986 RegValueStr(szValue
),
987 (DWORD
) RESERVED
, REG_SZ
,
988 (RegString
)strValue
.wx_str(),
989 (strValue
.Len() + 1)*sizeof(wxChar
));
990 if ( m_dwLastError
== ERROR_SUCCESS
)
994 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
995 GetFullName(this, szValue
));
999 wxString
wxRegKey::QueryDefaultValue() const
1002 QueryValue(wxEmptyString
, str
, false);
1006 // ----------------------------------------------------------------------------
1008 // NB: all these functions require an index variable which allows to have
1009 // several concurrently running indexations on the same key
1010 // ----------------------------------------------------------------------------
1012 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1018 return GetNextValue(strValueName
, lIndex
);
1021 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1023 wxASSERT( IsOpened() );
1025 // are we already at the end of enumeration?
1029 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1030 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1032 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1033 szValueName
, &dwValueLen
,
1036 NULL
, // [out] buffer for value
1037 NULL
); // [i/o] it's length
1039 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1040 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1041 m_dwLastError
= ERROR_SUCCESS
;
1045 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1052 strValueName
= szValueName
;
1057 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1063 return GetNextKey(strKeyName
, lIndex
);
1066 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1068 wxASSERT( IsOpened() );
1070 // are we already at the end of enumeration?
1074 wxChar szKeyName
[_MAX_PATH
+ 1];
1077 DWORD sizeName
= WXSIZEOF(szKeyName
);
1078 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1079 0, NULL
, NULL
, NULL
);
1081 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1084 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1085 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1086 m_dwLastError
= ERROR_SUCCESS
;
1090 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1097 strKeyName
= szKeyName
;
1101 // returns true if the value contains a number (else it's some string)
1102 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1104 ValueType type
= GetValueType(szValue
);
1107 /* case Type_Dword_little_endian: == Type_Dword */
1108 case Type_Dword_big_endian
:
1116 // ----------------------------------------------------------------------------
1117 // exporting registry keys to file
1118 // ----------------------------------------------------------------------------
1122 // helper functions for writing ASCII strings (even in Unicode build)
1123 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1129 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1131 // as we open the file in text mode, it is enough to write LF without CR
1132 return WriteAsciiChar(ostr
, '\n');
1135 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1137 return ostr
.Write(p
, strlen(p
)).IsOk();
1140 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1143 wxCharBuffer
name(s
.mb_str());
1144 ostr
.Write(name
, strlen(name
));
1146 ostr
.Write(s
.mb_str(), s
.length());
1152 #endif // wxUSE_STREAMS
1154 bool wxRegKey::Export(const wxString
& filename
) const
1156 #if wxUSE_FFILE && wxUSE_STREAMS
1157 if ( wxFile::Exists(filename
) )
1159 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1164 wxFFileOutputStream
ostr(filename
, _T("w"));
1166 return ostr
.Ok() && Export(ostr
);
1168 wxUnusedVar(filename
);
1174 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1176 // write out the header
1177 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1180 return DoExport(ostr
);
1182 #endif // wxUSE_STREAMS
1186 FormatAsHex(const void *data
,
1188 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1190 wxString
value(_T("hex"));
1192 // binary values use just "hex:" prefix while the other ones must indicate
1194 if ( type
!= wxRegKey::Type_Binary
)
1195 value
<< _T('(') << type
<< _T(')');
1198 // write all the rest as comma-separated bytes
1199 value
.reserve(3*size
+ 10);
1200 const char * const p
= static_cast<const char *>(data
);
1201 for ( size_t n
= 0; n
< size
; n
++ )
1203 // TODO: line wrapping: although not required by regedit, this makes
1204 // the generated files easier to read and compare with the files
1205 // produced by regedit
1209 value
<< wxString::Format(_T("%02x"), (unsigned char)p
[n
]);
1216 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1218 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1221 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1224 const ValueType type
= GetValueType(name
);
1230 if ( !QueryValue(name
, value
) )
1233 // quotes and backslashes must be quoted, linefeeds are not
1234 // allowed in string values
1235 rhs
.reserve(value
.length() + 2);
1238 // there can be no NULs here
1239 bool useHex
= false;
1240 for ( wxString::const_iterator p
= value
.begin();
1241 p
!= value
.end() && !useHex
; ++p
)
1243 switch ( (*p
).GetValue() )
1246 // we can only represent this string in hex
1252 // escape special symbol
1262 rhs
= FormatAsHex(value
, Type_String
);
1269 /* case Type_Dword_little_endian: == Type_Dword */
1272 if ( !QueryValue(name
, &value
) )
1275 rhs
.Printf(_T("dword:%08x"), (unsigned int)value
);
1279 case Type_Expand_String
:
1280 case Type_Multi_String
:
1283 if ( !QueryRawValue(name
, value
) )
1286 rhs
= FormatAsHex(value
, type
);
1293 if ( !QueryValue(name
, buf
) )
1296 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1300 // no idea how those appear in REGEDIT4 files
1302 case Type_Dword_big_endian
:
1304 case Type_Resource_list
:
1305 case Type_Full_resource_descriptor
:
1306 case Type_Resource_requirements_list
:
1308 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1316 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1318 // first examine the value type: if it's unsupported, simply skip it
1319 // instead of aborting the entire export process because we failed to
1320 // export a single value
1321 wxString value
= FormatValue(name
);
1322 if ( value
.empty() )
1324 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1325 name
.c_str(), GetName().c_str());
1329 // we do have the text representation of the value, now write everything
1332 // special case: unnamed/default value is represented as just "@"
1335 if ( !WriteAsciiChar(ostr
, '@') )
1338 else // normal, named, value
1340 if ( !WriteAsciiChar(ostr
, '"') ||
1341 !WriteAsciiString(ostr
, name
) ||
1342 !WriteAsciiChar(ostr
, '"') )
1346 if ( !WriteAsciiChar(ostr
, '=') )
1349 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1352 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1354 // write out this key name
1355 if ( !WriteAsciiChar(ostr
, '[') )
1358 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1361 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1364 // dump all our values
1367 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1368 bool cont
= self
.GetFirstValue(name
, dummy
);
1371 if ( !DoExportValue(ostr
, name
) )
1374 cont
= GetNextValue(name
, dummy
);
1377 // always terminate values by blank line, even if there were no values
1378 if ( !WriteAsciiEOL(ostr
) )
1381 // recurse to subkeys
1382 cont
= self
.GetFirstKey(name
, dummy
);
1385 wxRegKey
subkey(*this, name
);
1386 if ( !subkey
.DoExport(ostr
) )
1389 cont
= GetNextKey(name
, dummy
);
1395 #endif // wxUSE_STREAMS
1397 // ============================================================================
1398 // implementation of global private functions
1399 // ============================================================================
1401 bool KeyExists(WXHKEY hRootKey
, const wxString
& szKey
)
1403 // don't close this key itself for the case of empty szKey!
1404 if ( szKey
.empty() )
1413 KEY_READ
, // we might not have enough rights for rw access
1415 ) == ERROR_SUCCESS
)
1417 ::RegCloseKey(hkeyDummy
);
1425 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1427 wxString
str(pKey
->GetName());
1428 if ( !szValue
.empty() )
1429 str
<< wxT("\\") << szValue
;
1434 wxString
GetFullName(const wxRegKey
*pKey
)
1436 return pKey
->GetName();
1439 inline void RemoveTrailingSeparator(wxString
& str
)
1441 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1442 str
.Truncate(str
.Len() - 1);
1445 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1447 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1450 #endif // wxUSE_REGKEY