1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/registry.cpp
3 // Purpose: implementation of registry classes and functions
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
8 // Licence: wxWindows licence
9 // TODO: - parsing of registry key names
10 // - support of other (than REG_SZ/REG_DWORD) registry types
11 // - add high level functions (RegisterOleServer, ...)
12 ///////////////////////////////////////////////////////////////////////////////
14 // for compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
24 #include "wx/msw/wrapwin.h"
25 #include "wx/string.h"
32 #include "wx/dynlib.h"
34 #include "wx/wfstream.h"
35 #include "wx/msw/private.h"
44 #include <stdlib.h> // for _MAX_PATH
51 #define HKEY_DEFINED // already defined in windows.h
52 #include "wx/msw/registry.h"
54 // some registry functions don't like signed chars
55 typedef unsigned char *RegString
;
56 typedef BYTE
* RegBinary
;
58 #ifndef HKEY_PERFORMANCE_DATA
59 #define HKEY_PERFORMANCE_DATA ((HKEY)0x80000004)
62 #ifndef HKEY_CURRENT_CONFIG
63 #define HKEY_CURRENT_CONFIG ((HKEY)0x80000005)
67 #define HKEY_DYN_DATA ((HKEY)0x80000006)
70 #ifndef KEY_WOW64_64KEY
71 #define KEY_WOW64_64KEY 0x0100
74 // ----------------------------------------------------------------------------
76 // ----------------------------------------------------------------------------
78 // the standard key names, short names and handles all bundled together for
84 const wxChar
*szShortName
;
88 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
89 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
90 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
91 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
92 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
93 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
94 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
97 // the registry name separator (perhaps one day MS will change it to '/' ;-)
98 #define REG_SEPARATOR wxT('\\')
100 // useful for Windows programmers: makes somewhat more clear all these zeroes
101 // being passed to Windows APIs
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 // const_cast<> is not yet supported by all compilers
109 #define CONST_CAST ((wxRegKey *)this)->
111 // and neither is mutable which m_dwLastError should be
112 #define m_dwLastError CONST_CAST m_dwLastError
114 // ----------------------------------------------------------------------------
115 // non member functions
116 // ----------------------------------------------------------------------------
118 // removes the trailing backslash from the string if it has one
119 static inline void RemoveTrailingSeparator(wxString
& str
);
121 // returns true if given registry key exists
122 static bool KeyExists(
124 const wxString
& szKey
,
125 wxRegKey::WOW64ViewMode viewMode
= wxRegKey::WOW64ViewMode_Default
);
127 // return the WOW64 registry view flag which can be used with MSW registry
128 // functions for opening the key in the specified view
129 static long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
);
131 // return the access rights which can be used with MSW registry functions for
132 // opening the key in the specified mode
134 GetMSWAccessFlags(wxRegKey::AccessMode mode
, wxRegKey::WOW64ViewMode viewMode
);
136 // combines value and key name
137 static wxString
GetFullName(const wxRegKey
*pKey
);
138 static wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
);
140 // returns "value" argument of wxRegKey methods converted into a value that can
141 // be passed to win32 registry functions; specifically, converts empty string
143 static inline const wxChar
*RegValueStr(const wxString
& szValue
);
145 // ============================================================================
146 // implementation of wxRegKey class
147 // ============================================================================
149 // ----------------------------------------------------------------------------
150 // static functions and variables
151 // ----------------------------------------------------------------------------
153 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
155 // @@ should take a `StdKey key', but as it's often going to be used in loops
156 // it would require casts in user code.
157 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
159 // return empty string if key is invalid
160 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
162 return aStdKeys
[key
].szName
;
165 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
167 // return empty string if key is invalid
168 wxCHECK( key
< nStdKeys
, wxEmptyString
);
170 return aStdKeys
[key
].szShortName
;
173 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
175 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
178 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
179 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
180 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
185 if ( ui
== nStdKeys
) {
186 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
191 strKey
= strKey
.After(REG_SEPARATOR
);
192 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
193 strKey
.Truncate(strKey
.Len() - 1);
199 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
201 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
202 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
206 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
211 // ----------------------------------------------------------------------------
213 // ----------------------------------------------------------------------------
215 wxRegKey::wxRegKey(WOW64ViewMode viewMode
) : m_viewMode(viewMode
)
217 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
222 wxRegKey::wxRegKey(const wxString
& strKey
, WOW64ViewMode viewMode
)
223 : m_strKey(strKey
), m_viewMode(viewMode
)
225 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
230 // parent is a predefined (and preopened) key
231 wxRegKey::wxRegKey(StdKey keyParent
,
232 const wxString
& strKey
,
233 WOW64ViewMode viewMode
)
234 : m_strKey(strKey
), m_viewMode(viewMode
)
236 RemoveTrailingSeparator(m_strKey
);
237 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
242 // parent is a normal regkey
243 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
244 : m_strKey(keyParent
.m_strKey
), m_viewMode(keyParent
.GetView())
246 // combine our name with parent's to get the full name
247 if ( !m_strKey
.empty() &&
248 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
249 m_strKey
+= REG_SEPARATOR
;
253 RemoveTrailingSeparator(m_strKey
);
255 m_hRootKey
= keyParent
.m_hRootKey
;
260 // dtor closes the key releasing system resource
261 wxRegKey::~wxRegKey()
266 // ----------------------------------------------------------------------------
267 // change the key name/hkey
268 // ----------------------------------------------------------------------------
270 // set the full key name
271 void wxRegKey::SetName(const wxString
& strKey
)
276 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
279 // the name is relative to the parent key
280 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
285 RemoveTrailingSeparator(m_strKey
);
286 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
289 // the name is relative to the parent key
290 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
294 // combine our name with parent's to get the full name
296 // NB: this method is called by wxRegConfig::SetPath() which is a performance
297 // critical function and so it preallocates space for our m_strKey to
298 // gain some speed - this is why we only use += here and not = which
299 // would just free the prealloc'd buffer and would have to realloc it the
302 m_strKey
+= keyParent
.m_strKey
;
303 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
304 m_strKey
+= REG_SEPARATOR
;
307 RemoveTrailingSeparator(m_strKey
);
309 m_hRootKey
= keyParent
.m_hRootKey
;
312 // hKey should be opened and will be closed in wxRegKey dtor
313 void wxRegKey::SetHkey(WXHKEY hKey
)
319 // we don't know the parent of this key, assume HKLM by default
320 m_hRootKey
= HKEY_LOCAL_MACHINE
;
322 // we don't know in which mode was this key opened but we can't reopen it
323 // anyhow because we don't know its name, so the only thing we can is to hope
324 // that it allows all the operations which we're going to perform on it
332 // ----------------------------------------------------------------------------
333 // info about the key
334 // ----------------------------------------------------------------------------
336 // returns true if the key exists
337 bool wxRegKey::Exists() const
339 // opened key has to exist, try to open it if not done yet
342 : KeyExists(m_hRootKey
, m_strKey
, m_viewMode
);
345 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
346 wxString
wxRegKey::GetName(bool bShortPrefix
) const
348 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
349 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
350 : aStdKeys
[key
].szName
;
351 if ( !m_strKey
.empty() )
352 str
<< wxT("\\") << m_strKey
;
357 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
360 size_t *pnMaxValueLen
) const
362 // it might be unexpected to some that this function doesn't open the key
363 wxASSERT_MSG( IsOpened(), wxT("key should be opened in GetKeyInfo") );
365 // We need to use intermediate variables in 64 bit build as the function
366 // parameters must be 32 bit DWORDs and not 64 bit size_t values.
373 #define REG_PARAM(name) &dw##name
375 // Old gcc headers incorrectly prototype RegQueryInfoKey() as taking
376 // size_t but normally we need a cast, even when sizeof(size_t) is the same
378 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
379 #define REG_PARAM(name) pn##name
381 #define REG_PARAM(name) (LPDWORD)(pn##name)
386 m_dwLastError
= ::RegQueryInfoKey
390 NULL
, // (ptr to) size of class name buffer
392 REG_PARAM(SubKeys
), // [out] number of subkeys
393 REG_PARAM(MaxKeyLen
), // [out] max length of a subkey name
394 NULL
, // longest subkey class name
395 REG_PARAM(Values
), // [out] number of values
396 REG_PARAM(MaxValueLen
), // [out] max length of a value name
397 NULL
, // longest value data
398 NULL
, // security descriptor
399 NULL
// time of last modification
404 *pnSubKeys
= dwSubKeys
;
406 *pnMaxKeyLen
= dwMaxKeyLen
;
408 *pnValues
= dwValues
;
410 *pnMaxValueLen
= dwMaxValueLen
;
415 if ( m_dwLastError
!= ERROR_SUCCESS
) {
416 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
424 // ----------------------------------------------------------------------------
426 // ----------------------------------------------------------------------------
428 // opens key (it's not an error to call Open() on an already opened key)
429 bool wxRegKey::Open(AccessMode mode
)
433 if ( mode
<= m_mode
)
436 // we had been opened in read mode but now must be reopened in write
441 m_dwLastError
= ::RegOpenKeyEx
446 GetMSWAccessFlags(mode
, m_viewMode
),
450 if ( m_dwLastError
!= ERROR_SUCCESS
)
452 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
457 m_hKey
= (WXHKEY
) tmpKey
;
463 // creates key, failing if it exists and !bOkIfExists
464 bool wxRegKey::Create(bool bOkIfExists
)
466 // check for existence only if asked (i.e. order is important!)
467 if ( !bOkIfExists
&& Exists() )
475 // Minimum supported OS for RegCreateKeyEx: Win 95, Win NT 3.1, Win CE 1.0
476 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.t_str(),
477 0, // reserved and must be 0
478 NULL
, // The user-defined class type of this key.
479 REG_OPTION_NON_VOLATILE
, // supports other values as well; see MS docs
480 GetMSWAccessFlags(wxRegKey::Write
, m_viewMode
),
481 NULL
, // pointer to a SECURITY_ATTRIBUTES structure
485 if ( m_dwLastError
!= ERROR_SUCCESS
) {
486 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
492 m_hKey
= (WXHKEY
) tmpKey
;
497 // close the key, it's not an error to call it when not opened
498 bool wxRegKey::Close()
501 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
504 if ( m_dwLastError
!= ERROR_SUCCESS
) {
505 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
516 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
519 if ( HasValue(szValueNew
) ) {
520 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
526 !CopyValue(szValueOld
, *this, szValueNew
) ||
527 !DeleteValue(szValueOld
) ) {
528 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
529 szValueOld
, szValueNew
);
537 bool wxRegKey::CopyValue(const wxString
& szValue
,
539 const wxString
& szValueNew
)
541 wxString
valueNew(szValueNew
);
542 if ( valueNew
.empty() ) {
543 // by default, use the same name
547 switch ( GetValueType(szValue
) ) {
551 return QueryValue(szValue
, strVal
) &&
552 keyDst
.SetValue(valueNew
, strVal
);
556 /* case Type_Dword_little_endian: == Type_Dword */
559 return QueryValue(szValue
, &dwVal
) &&
560 keyDst
.SetValue(valueNew
, dwVal
);
566 return QueryValue(szValue
,buf
) &&
567 keyDst
.SetValue(valueNew
,buf
);
570 // these types are unsupported because I am not sure about how
571 // exactly they should be copied and because they shouldn't
572 // occur among the application keys (supposedly created with
575 case Type_Expand_String
:
576 case Type_Dword_big_endian
:
578 case Type_Multi_String
:
579 case Type_Resource_list
:
580 case Type_Full_resource_descriptor
:
581 case Type_Resource_requirements_list
:
583 wxLogError(_("Can't copy values of unsupported type %d."),
584 GetValueType(szValue
));
589 bool wxRegKey::Rename(const wxString
& szNewName
)
591 wxCHECK_MSG( !m_strKey
.empty(), false, wxT("registry hives can't be renamed") );
594 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
600 // do we stay in the same hive?
601 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
603 // construct the full new name of the key
607 // rename the key to the new name under the same parent
608 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
609 if ( !strKey
.empty() ) {
610 // don't add '\\' in the start if strFullNewName is empty
611 strKey
+= REG_SEPARATOR
;
616 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
619 // this is the full name already
620 keyDst
.SetName(szNewName
);
623 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
625 wxLogError(_("Registry key '%s' already exists."),
626 GetFullName(&keyDst
));
629 ok
= Copy(keyDst
) && DeleteSelf();
633 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
634 GetFullName(this), GetFullName(&keyDst
));
637 m_hRootKey
= keyDst
.m_hRootKey
;
638 m_strKey
= keyDst
.m_strKey
;
644 bool wxRegKey::Copy(const wxString
& szNewName
)
646 // create the new key first
647 wxRegKey
keyDst(szNewName
);
648 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
652 // we created the dest key but copying to it failed - delete it
654 (void)keyDst
.DeleteSelf();
661 bool wxRegKey::Copy(wxRegKey
& keyDst
)
665 // copy all sub keys to the new location
668 bool bCont
= GetFirstKey(strKey
, lIndex
);
669 while ( ok
&& bCont
) {
670 wxRegKey
key(*this, strKey
);
672 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
673 ok
= key
.Copy(keyName
);
676 bCont
= GetNextKey(strKey
, lIndex
);
678 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
679 GetFullName(&key
), keyName
.c_str());
685 bCont
= GetFirstValue(strVal
, lIndex
);
686 while ( ok
&& bCont
) {
687 ok
= CopyValue(strVal
, keyDst
);
690 wxLogSysError(m_dwLastError
,
691 _("Failed to copy registry value '%s'"),
695 bCont
= GetNextValue(strVal
, lIndex
);
700 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
701 GetFullName(this), GetFullName(&keyDst
));
707 // ----------------------------------------------------------------------------
708 // delete keys/values
709 // ----------------------------------------------------------------------------
710 bool wxRegKey::DeleteSelf()
715 // it already doesn't exist - ok!
720 // prevent a buggy program from erasing one of the root registry keys or an
721 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
722 // key except HKCR (HKCR has some "deleteable" subkeys)
723 if ( m_strKey
.empty() ||
724 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
725 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
726 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
732 // we can't delete keys while enumerating because it confuses GetNextKey, so
733 // we first save the key names and then delete them all
734 wxArrayString astrSubkeys
;
738 bool bCont
= GetFirstKey(strKey
, lIndex
);
740 astrSubkeys
.Add(strKey
);
742 bCont
= GetNextKey(strKey
, lIndex
);
745 size_t nKeyCount
= astrSubkeys
.Count();
746 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
747 wxRegKey
key(*this, astrSubkeys
[nKey
]);
748 if ( !key
.DeleteSelf() )
752 // now delete this key itself
755 // deleting a key which doesn't exist is not considered an error
756 #if wxUSE_DYNLIB_CLASS
757 wxDynamicLibrary
dllAdvapi32(wxT("advapi32"));
758 // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1
759 if(dllAdvapi32
.HasSymbol(wxT("RegDeleteKeyEx")))
761 typedef LONG (WINAPI
*RegDeleteKeyEx_t
)(HKEY
, LPCTSTR
, REGSAM
, DWORD
);
762 wxDYNLIB_FUNCTION(RegDeleteKeyEx_t
, RegDeleteKeyEx
, dllAdvapi32
);
764 m_dwLastError
= (*pfnRegDeleteKeyEx
)((HKEY
) m_hRootKey
, m_strKey
.t_str(),
765 GetMSWViewFlags(m_viewMode
),
766 0); // This parameter is reserved and must be zero.
769 #endif // wxUSE_DYNLIB_CLASS
771 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
774 if ( m_dwLastError
!= ERROR_SUCCESS
&&
775 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
776 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
784 bool wxRegKey::DeleteKey(const wxString
& szKey
)
789 wxRegKey
key(*this, szKey
);
790 return key
.DeleteSelf();
793 bool wxRegKey::DeleteValue(const wxString
& szValue
)
798 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
800 // deleting a value which doesn't exist is not considered an error
801 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
802 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
804 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
805 szValue
, GetName().c_str());
812 // ----------------------------------------------------------------------------
813 // access to values and subkeys
814 // ----------------------------------------------------------------------------
816 // return true if value exists
817 bool wxRegKey::HasValue(const wxString
& szValue
) const
819 // this function should be silent, so suppress possible messages from Open()
822 if ( !CONST_CAST
Open(Read
) )
825 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
826 RegValueStr(szValue
),
829 return dwRet
== ERROR_SUCCESS
;
832 // returns true if this key has any values
833 bool wxRegKey::HasValues() const
835 // suppress possible messages from GetFirstValue()
838 // just call GetFirstValue with dummy parameters
841 return CONST_CAST
GetFirstValue(str
, l
);
844 // returns true if this key has any subkeys
845 bool wxRegKey::HasSubkeys() const
847 // suppress possible messages from GetFirstKey()
850 // just call GetFirstKey with dummy parameters
853 return CONST_CAST
GetFirstKey(str
, l
);
856 // returns true if given subkey exists
857 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
859 // this function should be silent, so suppress possible messages from Open()
862 if ( !CONST_CAST
Open(Read
) )
865 return KeyExists(m_hKey
, szKey
, m_viewMode
);
868 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
870 if ( ! CONST_CAST
Open(Read
) )
874 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
875 &dwType
, NULL
, NULL
);
876 if ( m_dwLastError
!= ERROR_SUCCESS
) {
877 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
882 return (ValueType
)dwType
;
885 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
887 if ( CONST_CAST
Open() ) {
888 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
889 (DWORD
) RESERVED
, REG_DWORD
,
890 (RegString
)&lValue
, sizeof(lValue
));
891 if ( m_dwLastError
== ERROR_SUCCESS
)
895 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
896 GetFullName(this, szValue
));
900 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
902 if ( CONST_CAST
Open(Read
) ) {
903 DWORD dwType
, dwSize
= sizeof(DWORD
);
904 RegString pBuf
= (RegString
)plValue
;
905 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
907 &dwType
, pBuf
, &dwSize
);
908 if ( m_dwLastError
!= ERROR_SUCCESS
) {
909 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
914 // check that we read the value of right type
915 wxASSERT_MSG( IsNumericValue(szValue
),
916 wxT("Type mismatch in wxRegKey::QueryValue().") );
925 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
928 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
931 if ( CONST_CAST
Open() ) {
932 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
933 (DWORD
) RESERVED
, REG_BINARY
,
934 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
935 if ( m_dwLastError
== ERROR_SUCCESS
)
939 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
940 GetFullName(this, szValue
));
945 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
947 if ( CONST_CAST
Open(Read
) ) {
948 // first get the type and size of the data
949 DWORD dwType
, dwSize
;
950 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
952 &dwType
, NULL
, &dwSize
);
954 if ( m_dwLastError
== ERROR_SUCCESS
) {
956 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
957 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
958 RegValueStr(szValue
),
963 buffer
.UngetWriteBuf(dwSize
);
965 buffer
.SetDataLen(0);
970 if ( m_dwLastError
!= ERROR_SUCCESS
) {
971 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
982 bool wxRegKey::QueryValue(const wxString
& szValue
,
984 bool WXUNUSED_IN_WINCE(raw
)) const
986 if ( CONST_CAST
Open(Read
) )
989 // first get the type and size of the data
990 DWORD dwType
=REG_NONE
, dwSize
=0;
991 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
992 RegValueStr(szValue
),
994 &dwType
, NULL
, &dwSize
);
995 if ( m_dwLastError
== ERROR_SUCCESS
)
999 // must treat this case specially as GetWriteBuf() doesn't like
1000 // being called with 0 size
1005 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
1006 RegValueStr(szValue
),
1009 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
1012 // expand the var expansions in the string unless disabled
1014 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
1016 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
1017 bool ok
= dwExpSize
!= 0;
1020 wxString strExpValue
;
1021 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
1022 wxStringBuffer(strExpValue
, dwExpSize
),
1025 strValue
= strExpValue
;
1030 wxLogLastError(wxT("ExpandEnvironmentStrings"));
1037 if ( m_dwLastError
== ERROR_SUCCESS
)
1039 // check that it was the right type
1040 wxASSERT_MSG( !IsNumericValue(szValue
),
1041 wxT("Type mismatch in wxRegKey::QueryValue().") );
1048 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
1049 GetFullName(this, szValue
));
1053 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
1055 if ( CONST_CAST
Open() ) {
1056 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
1057 RegValueStr(szValue
),
1058 (DWORD
) RESERVED
, REG_SZ
,
1059 (RegString
)wxMSW_CONV_LPCTSTR(strValue
),
1060 (strValue
.Len() + 1)*sizeof(wxChar
));
1061 if ( m_dwLastError
== ERROR_SUCCESS
)
1065 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
1066 GetFullName(this, szValue
));
1070 wxString
wxRegKey::QueryDefaultValue() const
1073 QueryValue(wxEmptyString
, str
, false);
1077 // ----------------------------------------------------------------------------
1079 // NB: all these functions require an index variable which allows to have
1080 // several concurrently running indexations on the same key
1081 // ----------------------------------------------------------------------------
1083 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1089 return GetNextValue(strValueName
, lIndex
);
1092 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1094 wxASSERT( IsOpened() );
1096 // are we already at the end of enumeration?
1100 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1101 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1103 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1104 szValueName
, &dwValueLen
,
1107 NULL
, // [out] buffer for value
1108 NULL
); // [i/o] it's length
1110 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1111 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1112 m_dwLastError
= ERROR_SUCCESS
;
1116 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1123 strValueName
= szValueName
;
1128 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1134 return GetNextKey(strKeyName
, lIndex
);
1137 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1139 wxASSERT( IsOpened() );
1141 // are we already at the end of enumeration?
1145 wxChar szKeyName
[_MAX_PATH
+ 1];
1148 DWORD sizeName
= WXSIZEOF(szKeyName
);
1149 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1150 0, NULL
, NULL
, NULL
);
1152 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1155 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1156 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1157 m_dwLastError
= ERROR_SUCCESS
;
1161 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1168 strKeyName
= szKeyName
;
1172 // returns true if the value contains a number (else it's some string)
1173 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1175 ValueType type
= GetValueType(szValue
);
1178 /* case Type_Dword_little_endian: == Type_Dword */
1179 case Type_Dword_big_endian
:
1187 // ----------------------------------------------------------------------------
1188 // exporting registry keys to file
1189 // ----------------------------------------------------------------------------
1193 // helper functions for writing ASCII strings (even in Unicode build)
1194 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1200 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1202 // as we open the file in text mode, it is enough to write LF without CR
1203 return WriteAsciiChar(ostr
, '\n');
1206 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1208 return ostr
.Write(p
, strlen(p
)).IsOk();
1211 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1214 wxCharBuffer
name(s
.mb_str());
1215 ostr
.Write(name
, strlen(name
));
1217 ostr
.Write(s
.mb_str(), s
.length());
1223 #endif // wxUSE_STREAMS
1225 bool wxRegKey::Export(const wxString
& filename
) const
1227 #if wxUSE_FFILE && wxUSE_STREAMS
1228 if ( wxFile::Exists(filename
) )
1230 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1235 wxFFileOutputStream
ostr(filename
, wxT("w"));
1237 return ostr
.IsOk() && Export(ostr
);
1239 wxUnusedVar(filename
);
1245 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1247 // write out the header
1248 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1251 return DoExport(ostr
);
1253 #endif // wxUSE_STREAMS
1257 FormatAsHex(const void *data
,
1259 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1261 wxString
value(wxT("hex"));
1263 // binary values use just "hex:" prefix while the other ones must indicate
1265 if ( type
!= wxRegKey::Type_Binary
)
1266 value
<< wxT('(') << type
<< wxT(')');
1269 // write all the rest as comma-separated bytes
1270 value
.reserve(3*size
+ 10);
1271 const char * const p
= static_cast<const char *>(data
);
1272 for ( size_t n
= 0; n
< size
; n
++ )
1274 // TODO: line wrapping: although not required by regedit, this makes
1275 // the generated files easier to read and compare with the files
1276 // produced by regedit
1280 value
<< wxString::Format(wxT("%02x"), (unsigned char)p
[n
]);
1287 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1289 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1292 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1295 const ValueType type
= GetValueType(name
);
1301 if ( !QueryValue(name
, value
) )
1304 // quotes and backslashes must be quoted, linefeeds are not
1305 // allowed in string values
1306 rhs
.reserve(value
.length() + 2);
1309 // there can be no NULs here
1310 bool useHex
= false;
1311 for ( wxString::const_iterator p
= value
.begin();
1312 p
!= value
.end() && !useHex
; ++p
)
1314 switch ( (*p
).GetValue() )
1317 // we can only represent this string in hex
1323 // escape special symbol
1333 rhs
= FormatAsHex(value
, Type_String
);
1340 /* case Type_Dword_little_endian: == Type_Dword */
1343 if ( !QueryValue(name
, &value
) )
1346 rhs
.Printf(wxT("dword:%08x"), (unsigned int)value
);
1350 case Type_Expand_String
:
1351 case Type_Multi_String
:
1354 if ( !QueryRawValue(name
, value
) )
1357 rhs
= FormatAsHex(value
, type
);
1364 if ( !QueryValue(name
, buf
) )
1367 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1371 // no idea how those appear in REGEDIT4 files
1373 case Type_Dword_big_endian
:
1375 case Type_Resource_list
:
1376 case Type_Full_resource_descriptor
:
1377 case Type_Resource_requirements_list
:
1379 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1387 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1389 // first examine the value type: if it's unsupported, simply skip it
1390 // instead of aborting the entire export process because we failed to
1391 // export a single value
1392 wxString value
= FormatValue(name
);
1393 if ( value
.empty() )
1395 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1396 name
.c_str(), GetName().c_str());
1400 // we do have the text representation of the value, now write everything
1403 // special case: unnamed/default value is represented as just "@"
1406 if ( !WriteAsciiChar(ostr
, '@') )
1409 else // normal, named, value
1411 if ( !WriteAsciiChar(ostr
, '"') ||
1412 !WriteAsciiString(ostr
, name
) ||
1413 !WriteAsciiChar(ostr
, '"') )
1417 if ( !WriteAsciiChar(ostr
, '=') )
1420 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1423 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1425 // write out this key name
1426 if ( !WriteAsciiChar(ostr
, '[') )
1429 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1432 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1435 // dump all our values
1438 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1439 bool cont
= self
.GetFirstValue(name
, dummy
);
1442 if ( !DoExportValue(ostr
, name
) )
1445 cont
= GetNextValue(name
, dummy
);
1448 // always terminate values by blank line, even if there were no values
1449 if ( !WriteAsciiEOL(ostr
) )
1452 // recurse to subkeys
1453 cont
= self
.GetFirstKey(name
, dummy
);
1456 wxRegKey
subkey(*this, name
);
1457 if ( !subkey
.DoExport(ostr
) )
1460 cont
= GetNextKey(name
, dummy
);
1466 #endif // wxUSE_STREAMS
1468 // ============================================================================
1469 // implementation of global private functions
1470 // ============================================================================
1472 bool KeyExists(WXHKEY hRootKey
,
1473 const wxString
& szKey
,
1474 wxRegKey::WOW64ViewMode viewMode
)
1476 // don't close this key itself for the case of empty szKey!
1477 if ( szKey
.empty() )
1486 // we might not have enough rights for rw access
1487 GetMSWAccessFlags(wxRegKey::Read
, viewMode
),
1489 ) == ERROR_SUCCESS
)
1491 ::RegCloseKey(hkeyDummy
);
1499 long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
)
1501 long samWOW64ViewMode
= 0;
1505 case wxRegKey::WOW64ViewMode_32
:
1506 #ifdef __WIN64__ // the flag is only needed by 64 bit apps
1507 samWOW64ViewMode
= KEY_WOW64_32KEY
;
1511 case wxRegKey::WOW64ViewMode_64
:
1512 #ifndef __WIN64__ // the flag is only needed by 32 bit apps
1513 // 64 bit registry can only be accessed under 64 bit platforms
1514 if ( wxIsPlatform64Bit() )
1515 samWOW64ViewMode
= KEY_WOW64_64KEY
;
1520 wxFAIL_MSG("Unknown registry view.");
1523 case wxRegKey::WOW64ViewMode_Default
:
1524 // Use default registry view for the current application,
1525 // i.e. 32 bits for 32 bit ones and 64 bits for 64 bit apps
1529 return samWOW64ViewMode
;
1532 long GetMSWAccessFlags(wxRegKey::AccessMode mode
,
1533 wxRegKey::WOW64ViewMode viewMode
)
1535 long sam
= mode
== wxRegKey::Read
? KEY_READ
: KEY_ALL_ACCESS
;
1537 sam
|= GetMSWViewFlags(viewMode
);
1542 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1544 wxString
str(pKey
->GetName());
1545 if ( !szValue
.empty() )
1546 str
<< wxT("\\") << szValue
;
1551 wxString
GetFullName(const wxRegKey
*pKey
)
1553 return pKey
->GetName();
1556 inline void RemoveTrailingSeparator(wxString
& str
)
1558 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1559 str
.Truncate(str
.Len() - 1);
1562 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1564 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1567 #endif // wxUSE_REGKEY