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
)
298 // we don't know the parent of this key, assume HKLM by default
299 m_hRootKey
= HKEY_LOCAL_MACHINE
;
301 // we don't know in which mode was this key opened but we can't reopen it
302 // anyhow because we don't know its name, so the only thing we can is to hope
303 // that it allows all the operations which we're going to perform on it
311 // ----------------------------------------------------------------------------
312 // info about the key
313 // ----------------------------------------------------------------------------
315 // returns true if the key exists
316 bool wxRegKey::Exists() const
318 // opened key has to exist, try to open it if not done yet
319 return IsOpened() ? true : KeyExists(m_hRootKey
, m_strKey
.wx_str());
322 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
323 wxString
wxRegKey::GetName(bool bShortPrefix
) const
325 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
326 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
327 : aStdKeys
[key
].szName
;
328 if ( !m_strKey
.empty() )
329 str
<< wxT("\\") << m_strKey
;
334 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
337 size_t *pnMaxValueLen
) const
339 // old gcc headers incorrectly prototype RegQueryInfoKey()
340 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
341 #define REG_PARAM (size_t *)
343 #define REG_PARAM (LPDWORD)
346 // it might be unexpected to some that this function doesn't open the key
347 wxASSERT_MSG( IsOpened(), wxT("key should be opened in GetKeyInfo") );
349 m_dwLastError
= ::RegQueryInfoKey
353 NULL
, // (ptr to) size of class name buffer
356 pnSubKeys
, // [out] number of subkeys
358 pnMaxKeyLen
, // [out] max length of a subkey name
359 NULL
, // longest subkey class name
361 pnValues
, // [out] number of values
363 pnMaxValueLen
, // [out] max length of a value name
364 NULL
, // longest value data
365 NULL
, // security descriptor
366 NULL
// time of last modification
371 if ( m_dwLastError
!= ERROR_SUCCESS
) {
372 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
380 // ----------------------------------------------------------------------------
382 // ----------------------------------------------------------------------------
384 // opens key (it's not an error to call Open() on an already opened key)
385 bool wxRegKey::Open(AccessMode mode
)
389 if ( mode
<= m_mode
)
392 // we had been opened in read mode but now must be reopened in write
397 m_dwLastError
= ::RegOpenKeyEx
402 mode
== Read
? KEY_READ
: KEY_ALL_ACCESS
,
406 if ( m_dwLastError
!= ERROR_SUCCESS
)
408 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
413 m_hKey
= (WXHKEY
) tmpKey
;
419 // creates key, failing if it exists and !bOkIfExists
420 bool wxRegKey::Create(bool bOkIfExists
)
422 // check for existence only if asked (i.e. order is important!)
423 if ( !bOkIfExists
&& Exists() )
432 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.wx_str(),
434 NULL
, // class string
441 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
.t_str(), &tmpKey
);
443 if ( m_dwLastError
!= ERROR_SUCCESS
) {
444 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
450 m_hKey
= (WXHKEY
) tmpKey
;
455 // close the key, it's not an error to call it when not opened
456 bool wxRegKey::Close()
459 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
462 if ( m_dwLastError
!= ERROR_SUCCESS
) {
463 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
474 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
477 if ( HasValue(szValueNew
) ) {
478 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
484 !CopyValue(szValueOld
, *this, szValueNew
) ||
485 !DeleteValue(szValueOld
) ) {
486 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
487 szValueOld
, szValueNew
);
495 bool wxRegKey::CopyValue(const wxString
& szValue
,
497 const wxString
& szValueNew
)
499 wxString
valueNew(szValueNew
);
500 if ( valueNew
.empty() ) {
501 // by default, use the same name
505 switch ( GetValueType(szValue
) ) {
509 return QueryValue(szValue
, strVal
) &&
510 keyDst
.SetValue(valueNew
, strVal
);
514 /* case Type_Dword_little_endian: == Type_Dword */
517 return QueryValue(szValue
, &dwVal
) &&
518 keyDst
.SetValue(valueNew
, dwVal
);
524 return QueryValue(szValue
,buf
) &&
525 keyDst
.SetValue(valueNew
,buf
);
528 // these types are unsupported because I am not sure about how
529 // exactly they should be copied and because they shouldn't
530 // occur among the application keys (supposedly created with
533 case Type_Expand_String
:
534 case Type_Dword_big_endian
:
536 case Type_Multi_String
:
537 case Type_Resource_list
:
538 case Type_Full_resource_descriptor
:
539 case Type_Resource_requirements_list
:
541 wxLogError(_("Can't copy values of unsupported type %d."),
542 GetValueType(szValue
));
547 bool wxRegKey::Rename(const wxString
& szNewName
)
549 wxCHECK_MSG( !m_strKey
.empty(), false, wxT("registry hives can't be renamed") );
552 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
558 // do we stay in the same hive?
559 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
561 // construct the full new name of the key
565 // rename the key to the new name under the same parent
566 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
567 if ( !strKey
.empty() ) {
568 // don't add '\\' in the start if strFullNewName is empty
569 strKey
+= REG_SEPARATOR
;
574 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
577 // this is the full name already
578 keyDst
.SetName(szNewName
);
581 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
583 wxLogError(_("Registry key '%s' already exists."),
584 GetFullName(&keyDst
));
587 ok
= Copy(keyDst
) && DeleteSelf();
591 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
592 GetFullName(this), GetFullName(&keyDst
));
595 m_hRootKey
= keyDst
.m_hRootKey
;
596 m_strKey
= keyDst
.m_strKey
;
602 bool wxRegKey::Copy(const wxString
& szNewName
)
604 // create the new key first
605 wxRegKey
keyDst(szNewName
);
606 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
610 // we created the dest key but copying to it failed - delete it
612 (void)keyDst
.DeleteSelf();
619 bool wxRegKey::Copy(wxRegKey
& keyDst
)
623 // copy all sub keys to the new location
626 bool bCont
= GetFirstKey(strKey
, lIndex
);
627 while ( ok
&& bCont
) {
628 wxRegKey
key(*this, strKey
);
630 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
631 ok
= key
.Copy(keyName
);
634 bCont
= GetNextKey(strKey
, lIndex
);
636 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
637 GetFullName(&key
), keyName
.c_str());
643 bCont
= GetFirstValue(strVal
, lIndex
);
644 while ( ok
&& bCont
) {
645 ok
= CopyValue(strVal
, keyDst
);
648 wxLogSysError(m_dwLastError
,
649 _("Failed to copy registry value '%s'"),
653 bCont
= GetNextValue(strVal
, lIndex
);
658 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
659 GetFullName(this), GetFullName(&keyDst
));
665 // ----------------------------------------------------------------------------
666 // delete keys/values
667 // ----------------------------------------------------------------------------
668 bool wxRegKey::DeleteSelf()
673 // it already doesn't exist - ok!
678 // prevent a buggy program from erasing one of the root registry keys or an
679 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
680 // key except HKCR (HKCR has some "deleteable" subkeys)
681 if ( m_strKey
.empty() ||
682 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
683 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
684 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
690 // we can't delete keys while enumerating because it confuses GetNextKey, so
691 // we first save the key names and then delete them all
692 wxArrayString astrSubkeys
;
696 bool bCont
= GetFirstKey(strKey
, lIndex
);
698 astrSubkeys
.Add(strKey
);
700 bCont
= GetNextKey(strKey
, lIndex
);
703 size_t nKeyCount
= astrSubkeys
.Count();
704 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
705 wxRegKey
key(*this, astrSubkeys
[nKey
]);
706 if ( !key
.DeleteSelf() )
710 // now delete this key itself
713 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
714 // deleting a key which doesn't exist is not considered an error
715 if ( m_dwLastError
!= ERROR_SUCCESS
&&
716 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
717 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
725 bool wxRegKey::DeleteKey(const wxString
& szKey
)
730 wxRegKey
key(*this, szKey
);
731 return key
.DeleteSelf();
734 bool wxRegKey::DeleteValue(const wxString
& szValue
)
739 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
741 // deleting a value which doesn't exist is not considered an error
742 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
743 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
745 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
746 szValue
, GetName().c_str());
753 // ----------------------------------------------------------------------------
754 // access to values and subkeys
755 // ----------------------------------------------------------------------------
757 // return true if value exists
758 bool wxRegKey::HasValue(const wxString
& szValue
) const
760 // this function should be silent, so suppress possible messages from Open()
763 if ( !CONST_CAST
Open(Read
) )
766 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
767 RegValueStr(szValue
),
770 return dwRet
== ERROR_SUCCESS
;
773 // returns true if this key has any values
774 bool wxRegKey::HasValues() const
776 // suppress possible messages from GetFirstValue()
779 // just call GetFirstValue with dummy parameters
782 return CONST_CAST
GetFirstValue(str
, l
);
785 // returns true if this key has any subkeys
786 bool wxRegKey::HasSubkeys() const
788 // suppress possible messages from GetFirstKey()
791 // just call GetFirstKey with dummy parameters
794 return CONST_CAST
GetFirstKey(str
, l
);
797 // returns true if given subkey exists
798 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
800 // this function should be silent, so suppress possible messages from Open()
803 if ( !CONST_CAST
Open(Read
) )
806 return KeyExists(m_hKey
, szKey
);
809 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
811 if ( ! CONST_CAST
Open(Read
) )
815 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
816 &dwType
, NULL
, NULL
);
817 if ( m_dwLastError
!= ERROR_SUCCESS
) {
818 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
823 return (ValueType
)dwType
;
826 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
828 if ( CONST_CAST
Open() ) {
829 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
830 (DWORD
) RESERVED
, REG_DWORD
,
831 (RegString
)&lValue
, sizeof(lValue
));
832 if ( m_dwLastError
== ERROR_SUCCESS
)
836 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
837 GetFullName(this, szValue
));
841 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
843 if ( CONST_CAST
Open(Read
) ) {
844 DWORD dwType
, dwSize
= sizeof(DWORD
);
845 RegString pBuf
= (RegString
)plValue
;
846 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
848 &dwType
, pBuf
, &dwSize
);
849 if ( m_dwLastError
!= ERROR_SUCCESS
) {
850 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
855 // check that we read the value of right type
856 wxASSERT_MSG( IsNumericValue(szValue
),
857 wxT("Type mismatch in wxRegKey::QueryValue().") );
866 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
869 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
872 if ( CONST_CAST
Open() ) {
873 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
874 (DWORD
) RESERVED
, REG_BINARY
,
875 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
876 if ( m_dwLastError
== ERROR_SUCCESS
)
880 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
881 GetFullName(this, szValue
));
886 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
888 if ( CONST_CAST
Open(Read
) ) {
889 // first get the type and size of the data
890 DWORD dwType
, dwSize
;
891 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
893 &dwType
, NULL
, &dwSize
);
895 if ( m_dwLastError
== ERROR_SUCCESS
) {
897 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
898 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
899 RegValueStr(szValue
),
904 buffer
.UngetWriteBuf(dwSize
);
906 buffer
.SetDataLen(0);
911 if ( m_dwLastError
!= ERROR_SUCCESS
) {
912 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
923 bool wxRegKey::QueryValue(const wxString
& szValue
,
925 bool WXUNUSED_IN_WINCE(raw
)) const
927 if ( CONST_CAST
Open(Read
) )
930 // first get the type and size of the data
931 DWORD dwType
=REG_NONE
, dwSize
=0;
932 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
933 RegValueStr(szValue
),
935 &dwType
, NULL
, &dwSize
);
936 if ( m_dwLastError
== ERROR_SUCCESS
)
940 // must treat this case specially as GetWriteBuf() doesn't like
941 // being called with 0 size
946 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
947 RegValueStr(szValue
),
950 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
953 // expand the var expansions in the string unless disabled
955 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
957 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
958 bool ok
= dwExpSize
!= 0;
961 wxString strExpValue
;
962 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
963 wxStringBuffer(strExpValue
, dwExpSize
),
966 strValue
= strExpValue
;
971 wxLogLastError(wxT("ExpandEnvironmentStrings"));
978 if ( m_dwLastError
== ERROR_SUCCESS
)
980 // check that it was the right type
981 wxASSERT_MSG( !IsNumericValue(szValue
),
982 wxT("Type mismatch in wxRegKey::QueryValue().") );
989 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
990 GetFullName(this, szValue
));
994 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
996 if ( CONST_CAST
Open() ) {
997 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
998 RegValueStr(szValue
),
999 (DWORD
) RESERVED
, REG_SZ
,
1000 (RegString
)strValue
.wx_str(),
1001 (strValue
.Len() + 1)*sizeof(wxChar
));
1002 if ( m_dwLastError
== ERROR_SUCCESS
)
1006 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
1007 GetFullName(this, szValue
));
1011 wxString
wxRegKey::QueryDefaultValue() const
1014 QueryValue(wxEmptyString
, str
, false);
1018 // ----------------------------------------------------------------------------
1020 // NB: all these functions require an index variable which allows to have
1021 // several concurrently running indexations on the same key
1022 // ----------------------------------------------------------------------------
1024 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1030 return GetNextValue(strValueName
, lIndex
);
1033 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1035 wxASSERT( IsOpened() );
1037 // are we already at the end of enumeration?
1041 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1042 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1044 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1045 szValueName
, &dwValueLen
,
1048 NULL
, // [out] buffer for value
1049 NULL
); // [i/o] it's length
1051 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1052 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1053 m_dwLastError
= ERROR_SUCCESS
;
1057 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1064 strValueName
= szValueName
;
1069 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1075 return GetNextKey(strKeyName
, lIndex
);
1078 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1080 wxASSERT( IsOpened() );
1082 // are we already at the end of enumeration?
1086 wxChar szKeyName
[_MAX_PATH
+ 1];
1089 DWORD sizeName
= WXSIZEOF(szKeyName
);
1090 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1091 0, NULL
, NULL
, NULL
);
1093 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1096 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1097 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1098 m_dwLastError
= ERROR_SUCCESS
;
1102 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1109 strKeyName
= szKeyName
;
1113 // returns true if the value contains a number (else it's some string)
1114 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1116 ValueType type
= GetValueType(szValue
);
1119 /* case Type_Dword_little_endian: == Type_Dword */
1120 case Type_Dword_big_endian
:
1128 // ----------------------------------------------------------------------------
1129 // exporting registry keys to file
1130 // ----------------------------------------------------------------------------
1134 // helper functions for writing ASCII strings (even in Unicode build)
1135 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1141 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1143 // as we open the file in text mode, it is enough to write LF without CR
1144 return WriteAsciiChar(ostr
, '\n');
1147 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1149 return ostr
.Write(p
, strlen(p
)).IsOk();
1152 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1155 wxCharBuffer
name(s
.mb_str());
1156 ostr
.Write(name
, strlen(name
));
1158 ostr
.Write(s
.mb_str(), s
.length());
1164 #endif // wxUSE_STREAMS
1166 bool wxRegKey::Export(const wxString
& filename
) const
1168 #if wxUSE_FFILE && wxUSE_STREAMS
1169 if ( wxFile::Exists(filename
) )
1171 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1176 wxFFileOutputStream
ostr(filename
, wxT("w"));
1178 return ostr
.Ok() && Export(ostr
);
1180 wxUnusedVar(filename
);
1186 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1188 // write out the header
1189 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1192 return DoExport(ostr
);
1194 #endif // wxUSE_STREAMS
1198 FormatAsHex(const void *data
,
1200 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1202 wxString
value(wxT("hex"));
1204 // binary values use just "hex:" prefix while the other ones must indicate
1206 if ( type
!= wxRegKey::Type_Binary
)
1207 value
<< wxT('(') << type
<< wxT(')');
1210 // write all the rest as comma-separated bytes
1211 value
.reserve(3*size
+ 10);
1212 const char * const p
= static_cast<const char *>(data
);
1213 for ( size_t n
= 0; n
< size
; n
++ )
1215 // TODO: line wrapping: although not required by regedit, this makes
1216 // the generated files easier to read and compare with the files
1217 // produced by regedit
1221 value
<< wxString::Format(wxT("%02x"), (unsigned char)p
[n
]);
1228 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1230 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1233 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1236 const ValueType type
= GetValueType(name
);
1242 if ( !QueryValue(name
, value
) )
1245 // quotes and backslashes must be quoted, linefeeds are not
1246 // allowed in string values
1247 rhs
.reserve(value
.length() + 2);
1250 // there can be no NULs here
1251 bool useHex
= false;
1252 for ( wxString::const_iterator p
= value
.begin();
1253 p
!= value
.end() && !useHex
; ++p
)
1255 switch ( (*p
).GetValue() )
1258 // we can only represent this string in hex
1264 // escape special symbol
1274 rhs
= FormatAsHex(value
, Type_String
);
1281 /* case Type_Dword_little_endian: == Type_Dword */
1284 if ( !QueryValue(name
, &value
) )
1287 rhs
.Printf(wxT("dword:%08x"), (unsigned int)value
);
1291 case Type_Expand_String
:
1292 case Type_Multi_String
:
1295 if ( !QueryRawValue(name
, value
) )
1298 rhs
= FormatAsHex(value
, type
);
1305 if ( !QueryValue(name
, buf
) )
1308 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1312 // no idea how those appear in REGEDIT4 files
1314 case Type_Dword_big_endian
:
1316 case Type_Resource_list
:
1317 case Type_Full_resource_descriptor
:
1318 case Type_Resource_requirements_list
:
1320 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1328 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1330 // first examine the value type: if it's unsupported, simply skip it
1331 // instead of aborting the entire export process because we failed to
1332 // export a single value
1333 wxString value
= FormatValue(name
);
1334 if ( value
.empty() )
1336 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1337 name
.c_str(), GetName().c_str());
1341 // we do have the text representation of the value, now write everything
1344 // special case: unnamed/default value is represented as just "@"
1347 if ( !WriteAsciiChar(ostr
, '@') )
1350 else // normal, named, value
1352 if ( !WriteAsciiChar(ostr
, '"') ||
1353 !WriteAsciiString(ostr
, name
) ||
1354 !WriteAsciiChar(ostr
, '"') )
1358 if ( !WriteAsciiChar(ostr
, '=') )
1361 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1364 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1366 // write out this key name
1367 if ( !WriteAsciiChar(ostr
, '[') )
1370 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1373 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1376 // dump all our values
1379 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1380 bool cont
= self
.GetFirstValue(name
, dummy
);
1383 if ( !DoExportValue(ostr
, name
) )
1386 cont
= GetNextValue(name
, dummy
);
1389 // always terminate values by blank line, even if there were no values
1390 if ( !WriteAsciiEOL(ostr
) )
1393 // recurse to subkeys
1394 cont
= self
.GetFirstKey(name
, dummy
);
1397 wxRegKey
subkey(*this, name
);
1398 if ( !subkey
.DoExport(ostr
) )
1401 cont
= GetNextKey(name
, dummy
);
1407 #endif // wxUSE_STREAMS
1409 // ============================================================================
1410 // implementation of global private functions
1411 // ============================================================================
1413 bool KeyExists(WXHKEY hRootKey
, const wxString
& szKey
)
1415 // don't close this key itself for the case of empty szKey!
1416 if ( szKey
.empty() )
1425 KEY_READ
, // we might not have enough rights for rw access
1427 ) == ERROR_SUCCESS
)
1429 ::RegCloseKey(hkeyDummy
);
1437 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1439 wxString
str(pKey
->GetName());
1440 if ( !szValue
.empty() )
1441 str
<< wxT("\\") << szValue
;
1446 wxString
GetFullName(const wxRegKey
*pKey
)
1448 return pKey
->GetName();
1451 inline void RemoveTrailingSeparator(wxString
& str
)
1453 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1454 str
.Truncate(str
.Len() - 1);
1457 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1459 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1462 #endif // wxUSE_REGKEY