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/dynlib.h"
35 #include "wx/wfstream.h"
39 #include "wx/msw/private.h"
45 #include <stdlib.h> // for _MAX_PATH
52 #define HKEY_DEFINED // already defined in windows.h
53 #include "wx/msw/registry.h"
55 // some registry functions don't like signed chars
56 typedef unsigned char *RegString
;
57 typedef BYTE
* RegBinary
;
59 #ifndef HKEY_PERFORMANCE_DATA
60 #define HKEY_PERFORMANCE_DATA ((HKEY)0x80000004)
63 #ifndef HKEY_CURRENT_CONFIG
64 #define HKEY_CURRENT_CONFIG ((HKEY)0x80000005)
68 #define HKEY_DYN_DATA ((HKEY)0x80000006)
71 #ifndef KEY_WOW64_64KEY
72 #define KEY_WOW64_64KEY 0x0100
75 // ----------------------------------------------------------------------------
77 // ----------------------------------------------------------------------------
79 // the standard key names, short names and handles all bundled together for
85 const wxChar
*szShortName
;
89 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
90 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
91 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
92 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
93 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
94 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
95 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
98 // the registry name separator (perhaps one day MS will change it to '/' ;-)
99 #define REG_SEPARATOR wxT('\\')
101 // useful for Windows programmers: makes somewhat more clear all these zeroes
102 // being passed to Windows APIs
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 // const_cast<> is not yet supported by all compilers
110 #define CONST_CAST ((wxRegKey *)this)->
112 // and neither is mutable which m_dwLastError should be
113 #define m_dwLastError CONST_CAST m_dwLastError
115 // ----------------------------------------------------------------------------
116 // non member functions
117 // ----------------------------------------------------------------------------
119 // removes the trailing backslash from the string if it has one
120 static inline void RemoveTrailingSeparator(wxString
& str
);
122 // returns true if given registry key exists
123 static bool KeyExists(
125 const wxString
& szKey
,
126 wxRegKey::WOW64ViewMode viewMode
= wxRegKey::WOW64ViewMode_Default
);
128 // return the WOW64 registry view flag which can be used with MSW registry
129 // functions for opening the key in the specified view
130 static long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
);
132 // return the access rights which can be used with MSW registry functions for
133 // opening the key in the specified mode
135 GetMSWAccessFlags(wxRegKey::AccessMode mode
, wxRegKey::WOW64ViewMode viewMode
);
137 // combines value and key name
138 static wxString
GetFullName(const wxRegKey
*pKey
);
139 static wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
);
141 // returns "value" argument of wxRegKey methods converted into a value that can
142 // be passed to win32 registry functions; specifically, converts empty string
144 static inline const wxChar
*RegValueStr(const wxString
& szValue
);
146 // ============================================================================
147 // implementation of wxRegKey class
148 // ============================================================================
150 // ----------------------------------------------------------------------------
151 // static functions and variables
152 // ----------------------------------------------------------------------------
154 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
156 // @@ should take a `StdKey key', but as it's often going to be used in loops
157 // it would require casts in user code.
158 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
160 // return empty string if key is invalid
161 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
163 return aStdKeys
[key
].szName
;
166 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
168 // return empty string if key is invalid
169 wxCHECK( key
< nStdKeys
, wxEmptyString
);
171 return aStdKeys
[key
].szShortName
;
174 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
176 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
179 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
180 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
181 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
186 if ( ui
== nStdKeys
) {
187 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
192 strKey
= strKey
.After(REG_SEPARATOR
);
193 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
194 strKey
.Truncate(strKey
.Len() - 1);
200 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
202 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
203 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
207 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
212 // ----------------------------------------------------------------------------
214 // ----------------------------------------------------------------------------
216 wxRegKey::wxRegKey(WOW64ViewMode viewMode
) : m_viewMode(viewMode
)
218 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
223 wxRegKey::wxRegKey(const wxString
& strKey
, WOW64ViewMode viewMode
)
224 : m_strKey(strKey
), m_viewMode(viewMode
)
226 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
231 // parent is a predefined (and preopened) key
232 wxRegKey::wxRegKey(StdKey keyParent
,
233 const wxString
& strKey
,
234 WOW64ViewMode viewMode
)
235 : m_strKey(strKey
), m_viewMode(viewMode
)
237 RemoveTrailingSeparator(m_strKey
);
238 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
243 // parent is a normal regkey
244 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
245 : m_strKey(keyParent
.m_strKey
), m_viewMode(keyParent
.GetView())
247 // combine our name with parent's to get the full name
248 if ( !m_strKey
.empty() &&
249 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
250 m_strKey
+= REG_SEPARATOR
;
254 RemoveTrailingSeparator(m_strKey
);
256 m_hRootKey
= keyParent
.m_hRootKey
;
261 // dtor closes the key releasing system resource
262 wxRegKey::~wxRegKey()
267 // ----------------------------------------------------------------------------
268 // change the key name/hkey
269 // ----------------------------------------------------------------------------
271 // set the full key name
272 void wxRegKey::SetName(const wxString
& strKey
)
277 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
280 // the name is relative to the parent key
281 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
286 RemoveTrailingSeparator(m_strKey
);
287 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
290 // the name is relative to the parent key
291 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
295 // combine our name with parent's to get the full name
297 // NB: this method is called by wxRegConfig::SetPath() which is a performance
298 // critical function and so it preallocates space for our m_strKey to
299 // gain some speed - this is why we only use += here and not = which
300 // would just free the prealloc'd buffer and would have to realloc it the
303 m_strKey
+= keyParent
.m_strKey
;
304 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
305 m_strKey
+= REG_SEPARATOR
;
308 RemoveTrailingSeparator(m_strKey
);
310 m_hRootKey
= keyParent
.m_hRootKey
;
313 // hKey should be opened and will be closed in wxRegKey dtor
314 void wxRegKey::SetHkey(WXHKEY hKey
)
320 // we don't know the parent of this key, assume HKLM by default
321 m_hRootKey
= HKEY_LOCAL_MACHINE
;
323 // we don't know in which mode was this key opened but we can't reopen it
324 // anyhow because we don't know its name, so the only thing we can is to hope
325 // that it allows all the operations which we're going to perform on it
333 // ----------------------------------------------------------------------------
334 // info about the key
335 // ----------------------------------------------------------------------------
337 // returns true if the key exists
338 bool wxRegKey::Exists() const
340 // opened key has to exist, try to open it if not done yet
343 : KeyExists(m_hRootKey
, m_strKey
, m_viewMode
);
346 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
347 wxString
wxRegKey::GetName(bool bShortPrefix
) const
349 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
350 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
351 : aStdKeys
[key
].szName
;
352 if ( !m_strKey
.empty() )
353 str
<< wxT("\\") << m_strKey
;
358 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
361 size_t *pnMaxValueLen
) const
363 // it might be unexpected to some that this function doesn't open the key
364 wxASSERT_MSG( IsOpened(), wxT("key should be opened in GetKeyInfo") );
366 // We need to use intermediate variables in 64 bit build as the function
367 // parameters must be 32 bit DWORDs and not 64 bit size_t values.
374 #define REG_PARAM(name) &dw##name
376 // Old gcc headers incorrectly prototype RegQueryInfoKey() as taking
377 // size_t but normally we need a cast, even when sizeof(size_t) is the same
379 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
380 #define REG_PARAM(name) pn##name
382 #define REG_PARAM(name) (LPDWORD)(pn##name)
387 m_dwLastError
= ::RegQueryInfoKey
391 NULL
, // (ptr to) size of class name buffer
393 REG_PARAM(SubKeys
), // [out] number of subkeys
394 REG_PARAM(MaxKeyLen
), // [out] max length of a subkey name
395 NULL
, // longest subkey class name
396 REG_PARAM(Values
), // [out] number of values
397 REG_PARAM(MaxValueLen
), // [out] max length of a value name
398 NULL
, // longest value data
399 NULL
, // security descriptor
400 NULL
// time of last modification
405 *pnSubKeys
= dwSubKeys
;
407 *pnMaxKeyLen
= dwMaxKeyLen
;
409 *pnValues
= dwValues
;
411 *pnMaxValueLen
= dwMaxValueLen
;
416 if ( m_dwLastError
!= ERROR_SUCCESS
) {
417 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
429 // opens key (it's not an error to call Open() on an already opened key)
430 bool wxRegKey::Open(AccessMode mode
)
434 if ( mode
<= m_mode
)
437 // we had been opened in read mode but now must be reopened in write
442 m_dwLastError
= ::RegOpenKeyEx
447 GetMSWAccessFlags(mode
, m_viewMode
),
451 if ( m_dwLastError
!= ERROR_SUCCESS
)
453 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
458 m_hKey
= (WXHKEY
) tmpKey
;
464 // creates key, failing if it exists and !bOkIfExists
465 bool wxRegKey::Create(bool bOkIfExists
)
467 // check for existence only if asked (i.e. order is important!)
468 if ( !bOkIfExists
&& Exists() )
476 // Minimum supported OS for RegCreateKeyEx: Win 95, Win NT 3.1, Win CE 1.0
477 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.t_str(),
478 0, // reserved and must be 0
479 NULL
, // The user-defined class type of this key.
480 REG_OPTION_NON_VOLATILE
, // supports other values as well; see MS docs
481 GetMSWAccessFlags(wxRegKey::Write
, m_viewMode
),
482 NULL
, // pointer to a SECURITY_ATTRIBUTES structure
486 if ( m_dwLastError
!= ERROR_SUCCESS
) {
487 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
493 m_hKey
= (WXHKEY
) tmpKey
;
498 // close the key, it's not an error to call it when not opened
499 bool wxRegKey::Close()
502 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
505 if ( m_dwLastError
!= ERROR_SUCCESS
) {
506 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
517 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
520 if ( HasValue(szValueNew
) ) {
521 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
527 !CopyValue(szValueOld
, *this, szValueNew
) ||
528 !DeleteValue(szValueOld
) ) {
529 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
530 szValueOld
, szValueNew
);
538 bool wxRegKey::CopyValue(const wxString
& szValue
,
540 const wxString
& szValueNew
)
542 wxString
valueNew(szValueNew
);
543 if ( valueNew
.empty() ) {
544 // by default, use the same name
548 switch ( GetValueType(szValue
) ) {
552 return QueryValue(szValue
, strVal
) &&
553 keyDst
.SetValue(valueNew
, strVal
);
557 /* case Type_Dword_little_endian: == Type_Dword */
560 return QueryValue(szValue
, &dwVal
) &&
561 keyDst
.SetValue(valueNew
, dwVal
);
567 return QueryValue(szValue
,buf
) &&
568 keyDst
.SetValue(valueNew
,buf
);
571 // these types are unsupported because I am not sure about how
572 // exactly they should be copied and because they shouldn't
573 // occur among the application keys (supposedly created with
576 case Type_Expand_String
:
577 case Type_Dword_big_endian
:
579 case Type_Multi_String
:
580 case Type_Resource_list
:
581 case Type_Full_resource_descriptor
:
582 case Type_Resource_requirements_list
:
584 wxLogError(_("Can't copy values of unsupported type %d."),
585 GetValueType(szValue
));
590 bool wxRegKey::Rename(const wxString
& szNewName
)
592 wxCHECK_MSG( !m_strKey
.empty(), false, wxT("registry hives can't be renamed") );
595 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
601 // do we stay in the same hive?
602 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
604 // construct the full new name of the key
608 // rename the key to the new name under the same parent
609 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
610 if ( !strKey
.empty() ) {
611 // don't add '\\' in the start if strFullNewName is empty
612 strKey
+= REG_SEPARATOR
;
617 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
620 // this is the full name already
621 keyDst
.SetName(szNewName
);
624 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
626 wxLogError(_("Registry key '%s' already exists."),
627 GetFullName(&keyDst
));
630 ok
= Copy(keyDst
) && DeleteSelf();
634 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
635 GetFullName(this), GetFullName(&keyDst
));
638 m_hRootKey
= keyDst
.m_hRootKey
;
639 m_strKey
= keyDst
.m_strKey
;
645 bool wxRegKey::Copy(const wxString
& szNewName
)
647 // create the new key first
648 wxRegKey
keyDst(szNewName
);
649 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
653 // we created the dest key but copying to it failed - delete it
655 (void)keyDst
.DeleteSelf();
662 bool wxRegKey::Copy(wxRegKey
& keyDst
)
666 // copy all sub keys to the new location
669 bool bCont
= GetFirstKey(strKey
, lIndex
);
670 while ( ok
&& bCont
) {
671 wxRegKey
key(*this, strKey
);
673 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
674 ok
= key
.Copy(keyName
);
677 bCont
= GetNextKey(strKey
, lIndex
);
679 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
680 GetFullName(&key
), keyName
.c_str());
686 bCont
= GetFirstValue(strVal
, lIndex
);
687 while ( ok
&& bCont
) {
688 ok
= CopyValue(strVal
, keyDst
);
691 wxLogSysError(m_dwLastError
,
692 _("Failed to copy registry value '%s'"),
696 bCont
= GetNextValue(strVal
, lIndex
);
701 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
702 GetFullName(this), GetFullName(&keyDst
));
708 // ----------------------------------------------------------------------------
709 // delete keys/values
710 // ----------------------------------------------------------------------------
711 bool wxRegKey::DeleteSelf()
716 // it already doesn't exist - ok!
721 // prevent a buggy program from erasing one of the root registry keys or an
722 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
723 // key except HKCR (HKCR has some "deleteable" subkeys)
724 if ( m_strKey
.empty() ||
725 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
726 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
727 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
733 // we can't delete keys while enumerating because it confuses GetNextKey, so
734 // we first save the key names and then delete them all
735 wxArrayString astrSubkeys
;
739 bool bCont
= GetFirstKey(strKey
, lIndex
);
741 astrSubkeys
.Add(strKey
);
743 bCont
= GetNextKey(strKey
, lIndex
);
746 size_t nKeyCount
= astrSubkeys
.Count();
747 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
748 wxRegKey
key(*this, astrSubkeys
[nKey
]);
749 if ( !key
.DeleteSelf() )
753 // now delete this key itself
756 // deleting a key which doesn't exist is not considered an error
757 #if wxUSE_DYNLIB_CLASS
758 wxDynamicLibrary
dllAdvapi32(wxT("advapi32"));
759 // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1
760 if(dllAdvapi32
.HasSymbol(wxT("RegDeleteKeyEx")))
762 typedef LONG (WINAPI
*RegDeleteKeyEx_t
)(HKEY
, LPCTSTR
, REGSAM
, DWORD
);
763 wxDYNLIB_FUNCTION(RegDeleteKeyEx_t
, RegDeleteKeyEx
, dllAdvapi32
);
765 m_dwLastError
= (*pfnRegDeleteKeyEx
)((HKEY
) m_hRootKey
, m_strKey
.t_str(),
766 GetMSWViewFlags(m_viewMode
),
767 0); // This parameter is reserved and must be zero.
770 #endif // wxUSE_DYNLIB_CLASS
772 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
775 if ( m_dwLastError
!= ERROR_SUCCESS
&&
776 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
777 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
785 bool wxRegKey::DeleteKey(const wxString
& szKey
)
790 wxRegKey
key(*this, szKey
);
791 return key
.DeleteSelf();
794 bool wxRegKey::DeleteValue(const wxString
& szValue
)
799 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
801 // deleting a value which doesn't exist is not considered an error
802 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
803 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
805 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
806 szValue
, GetName().c_str());
813 // ----------------------------------------------------------------------------
814 // access to values and subkeys
815 // ----------------------------------------------------------------------------
817 // return true if value exists
818 bool wxRegKey::HasValue(const wxString
& szValue
) const
820 // this function should be silent, so suppress possible messages from Open()
823 if ( !CONST_CAST
Open(Read
) )
826 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
827 RegValueStr(szValue
),
830 return dwRet
== ERROR_SUCCESS
;
833 // returns true if this key has any values
834 bool wxRegKey::HasValues() const
836 // suppress possible messages from GetFirstValue()
839 // just call GetFirstValue with dummy parameters
842 return CONST_CAST
GetFirstValue(str
, l
);
845 // returns true if this key has any subkeys
846 bool wxRegKey::HasSubkeys() const
848 // suppress possible messages from GetFirstKey()
851 // just call GetFirstKey with dummy parameters
854 return CONST_CAST
GetFirstKey(str
, l
);
857 // returns true if given subkey exists
858 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
860 // this function should be silent, so suppress possible messages from Open()
863 if ( !CONST_CAST
Open(Read
) )
866 return KeyExists(m_hKey
, szKey
, m_viewMode
);
869 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
871 if ( ! CONST_CAST
Open(Read
) )
875 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
876 &dwType
, NULL
, NULL
);
877 if ( m_dwLastError
!= ERROR_SUCCESS
) {
878 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
883 return (ValueType
)dwType
;
886 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
888 if ( CONST_CAST
Open() ) {
889 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
890 (DWORD
) RESERVED
, REG_DWORD
,
891 (RegString
)&lValue
, sizeof(lValue
));
892 if ( m_dwLastError
== ERROR_SUCCESS
)
896 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
897 GetFullName(this, szValue
));
901 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
903 if ( CONST_CAST
Open(Read
) ) {
904 DWORD dwType
, dwSize
= sizeof(DWORD
);
905 RegString pBuf
= (RegString
)plValue
;
906 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
908 &dwType
, pBuf
, &dwSize
);
909 if ( m_dwLastError
!= ERROR_SUCCESS
) {
910 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
915 // check that we read the value of right type
916 wxASSERT_MSG( IsNumericValue(szValue
),
917 wxT("Type mismatch in wxRegKey::QueryValue().") );
926 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
929 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
932 if ( CONST_CAST
Open() ) {
933 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
934 (DWORD
) RESERVED
, REG_BINARY
,
935 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
936 if ( m_dwLastError
== ERROR_SUCCESS
)
940 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
941 GetFullName(this, szValue
));
946 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
948 if ( CONST_CAST
Open(Read
) ) {
949 // first get the type and size of the data
950 DWORD dwType
, dwSize
;
951 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
953 &dwType
, NULL
, &dwSize
);
955 if ( m_dwLastError
== ERROR_SUCCESS
) {
957 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
958 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
959 RegValueStr(szValue
),
964 buffer
.UngetWriteBuf(dwSize
);
966 buffer
.SetDataLen(0);
971 if ( m_dwLastError
!= ERROR_SUCCESS
) {
972 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
983 bool wxRegKey::QueryValue(const wxString
& szValue
,
985 bool WXUNUSED_IN_WINCE(raw
)) const
987 if ( CONST_CAST
Open(Read
) )
990 // first get the type and size of the data
991 DWORD dwType
=REG_NONE
, dwSize
=0;
992 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
993 RegValueStr(szValue
),
995 &dwType
, NULL
, &dwSize
);
996 if ( m_dwLastError
== ERROR_SUCCESS
)
1000 // must treat this case specially as GetWriteBuf() doesn't like
1001 // being called with 0 size
1006 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
1007 RegValueStr(szValue
),
1010 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
1013 // expand the var expansions in the string unless disabled
1015 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
1017 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
1018 bool ok
= dwExpSize
!= 0;
1021 wxString strExpValue
;
1022 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
1023 wxStringBuffer(strExpValue
, dwExpSize
),
1026 strValue
= strExpValue
;
1031 wxLogLastError(wxT("ExpandEnvironmentStrings"));
1038 if ( m_dwLastError
== ERROR_SUCCESS
)
1040 // check that it was the right type
1041 wxASSERT_MSG( !IsNumericValue(szValue
),
1042 wxT("Type mismatch in wxRegKey::QueryValue().") );
1049 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
1050 GetFullName(this, szValue
));
1054 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
1056 if ( CONST_CAST
Open() ) {
1057 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
1058 RegValueStr(szValue
),
1059 (DWORD
) RESERVED
, REG_SZ
,
1060 (RegString
)strValue
.t_str(),
1061 (strValue
.Len() + 1)*sizeof(wxChar
));
1062 if ( m_dwLastError
== ERROR_SUCCESS
)
1066 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
1067 GetFullName(this, szValue
));
1071 wxString
wxRegKey::QueryDefaultValue() const
1074 QueryValue(wxEmptyString
, str
, false);
1078 // ----------------------------------------------------------------------------
1080 // NB: all these functions require an index variable which allows to have
1081 // several concurrently running indexations on the same key
1082 // ----------------------------------------------------------------------------
1084 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1090 return GetNextValue(strValueName
, lIndex
);
1093 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1095 wxASSERT( IsOpened() );
1097 // are we already at the end of enumeration?
1101 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1102 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1104 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1105 szValueName
, &dwValueLen
,
1108 NULL
, // [out] buffer for value
1109 NULL
); // [i/o] it's length
1111 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1112 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1113 m_dwLastError
= ERROR_SUCCESS
;
1117 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1124 strValueName
= szValueName
;
1129 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1135 return GetNextKey(strKeyName
, lIndex
);
1138 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1140 wxASSERT( IsOpened() );
1142 // are we already at the end of enumeration?
1146 wxChar szKeyName
[_MAX_PATH
+ 1];
1149 DWORD sizeName
= WXSIZEOF(szKeyName
);
1150 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1151 0, NULL
, NULL
, NULL
);
1153 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1156 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1157 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1158 m_dwLastError
= ERROR_SUCCESS
;
1162 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1169 strKeyName
= szKeyName
;
1173 // returns true if the value contains a number (else it's some string)
1174 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1176 ValueType type
= GetValueType(szValue
);
1179 /* case Type_Dword_little_endian: == Type_Dword */
1180 case Type_Dword_big_endian
:
1188 // ----------------------------------------------------------------------------
1189 // exporting registry keys to file
1190 // ----------------------------------------------------------------------------
1194 // helper functions for writing ASCII strings (even in Unicode build)
1195 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1201 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1203 // as we open the file in text mode, it is enough to write LF without CR
1204 return WriteAsciiChar(ostr
, '\n');
1207 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1209 return ostr
.Write(p
, strlen(p
)).IsOk();
1212 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1215 wxCharBuffer
name(s
.mb_str());
1216 ostr
.Write(name
, strlen(name
));
1218 ostr
.Write(s
.mb_str(), s
.length());
1224 #endif // wxUSE_STREAMS
1226 bool wxRegKey::Export(const wxString
& filename
) const
1228 #if wxUSE_FFILE && wxUSE_STREAMS
1229 if ( wxFile::Exists(filename
) )
1231 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1236 wxFFileOutputStream
ostr(filename
, wxT("w"));
1238 return ostr
.IsOk() && Export(ostr
);
1240 wxUnusedVar(filename
);
1246 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1248 // write out the header
1249 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1252 return DoExport(ostr
);
1254 #endif // wxUSE_STREAMS
1258 FormatAsHex(const void *data
,
1260 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1262 wxString
value(wxT("hex"));
1264 // binary values use just "hex:" prefix while the other ones must indicate
1266 if ( type
!= wxRegKey::Type_Binary
)
1267 value
<< wxT('(') << type
<< wxT(')');
1270 // write all the rest as comma-separated bytes
1271 value
.reserve(3*size
+ 10);
1272 const char * const p
= static_cast<const char *>(data
);
1273 for ( size_t n
= 0; n
< size
; n
++ )
1275 // TODO: line wrapping: although not required by regedit, this makes
1276 // the generated files easier to read and compare with the files
1277 // produced by regedit
1281 value
<< wxString::Format(wxT("%02x"), (unsigned char)p
[n
]);
1288 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1290 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1293 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1296 const ValueType type
= GetValueType(name
);
1302 if ( !QueryValue(name
, value
) )
1305 // quotes and backslashes must be quoted, linefeeds are not
1306 // allowed in string values
1307 rhs
.reserve(value
.length() + 2);
1310 // there can be no NULs here
1311 bool useHex
= false;
1312 for ( wxString::const_iterator p
= value
.begin();
1313 p
!= value
.end() && !useHex
; ++p
)
1315 switch ( (*p
).GetValue() )
1318 // we can only represent this string in hex
1324 // escape special symbol
1334 rhs
= FormatAsHex(value
, Type_String
);
1341 /* case Type_Dword_little_endian: == Type_Dword */
1344 if ( !QueryValue(name
, &value
) )
1347 rhs
.Printf(wxT("dword:%08x"), (unsigned int)value
);
1351 case Type_Expand_String
:
1352 case Type_Multi_String
:
1355 if ( !QueryRawValue(name
, value
) )
1358 rhs
= FormatAsHex(value
, type
);
1365 if ( !QueryValue(name
, buf
) )
1368 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1372 // no idea how those appear in REGEDIT4 files
1374 case Type_Dword_big_endian
:
1376 case Type_Resource_list
:
1377 case Type_Full_resource_descriptor
:
1378 case Type_Resource_requirements_list
:
1380 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1388 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1390 // first examine the value type: if it's unsupported, simply skip it
1391 // instead of aborting the entire export process because we failed to
1392 // export a single value
1393 wxString value
= FormatValue(name
);
1394 if ( value
.empty() )
1396 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1397 name
.c_str(), GetName().c_str());
1401 // we do have the text representation of the value, now write everything
1404 // special case: unnamed/default value is represented as just "@"
1407 if ( !WriteAsciiChar(ostr
, '@') )
1410 else // normal, named, value
1412 if ( !WriteAsciiChar(ostr
, '"') ||
1413 !WriteAsciiString(ostr
, name
) ||
1414 !WriteAsciiChar(ostr
, '"') )
1418 if ( !WriteAsciiChar(ostr
, '=') )
1421 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1424 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1426 // write out this key name
1427 if ( !WriteAsciiChar(ostr
, '[') )
1430 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1433 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1436 // dump all our values
1439 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1440 bool cont
= self
.GetFirstValue(name
, dummy
);
1443 if ( !DoExportValue(ostr
, name
) )
1446 cont
= GetNextValue(name
, dummy
);
1449 // always terminate values by blank line, even if there were no values
1450 if ( !WriteAsciiEOL(ostr
) )
1453 // recurse to subkeys
1454 cont
= self
.GetFirstKey(name
, dummy
);
1457 wxRegKey
subkey(*this, name
);
1458 if ( !subkey
.DoExport(ostr
) )
1461 cont
= GetNextKey(name
, dummy
);
1467 #endif // wxUSE_STREAMS
1469 // ============================================================================
1470 // implementation of global private functions
1471 // ============================================================================
1473 bool KeyExists(WXHKEY hRootKey
,
1474 const wxString
& szKey
,
1475 wxRegKey::WOW64ViewMode viewMode
)
1477 // don't close this key itself for the case of empty szKey!
1478 if ( szKey
.empty() )
1487 // we might not have enough rights for rw access
1488 GetMSWAccessFlags(wxRegKey::Read
, viewMode
),
1490 ) == ERROR_SUCCESS
)
1492 ::RegCloseKey(hkeyDummy
);
1500 long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
)
1502 long samWOW64ViewMode
= 0;
1506 case wxRegKey::WOW64ViewMode_32
:
1507 #ifdef __WIN64__ // the flag is only needed by 64 bit apps
1508 samWOW64ViewMode
= KEY_WOW64_32KEY
;
1512 case wxRegKey::WOW64ViewMode_64
:
1513 #ifndef __WIN64__ // the flag is only needed by 32 bit apps
1514 // 64 bit registry can only be accessed under 64 bit platforms
1515 if ( wxIsPlatform64Bit() )
1516 samWOW64ViewMode
= KEY_WOW64_64KEY
;
1521 wxFAIL_MSG("Unknown registry view.");
1524 case wxRegKey::WOW64ViewMode_Default
:
1525 // Use default registry view for the current application,
1526 // i.e. 32 bits for 32 bit ones and 64 bits for 64 bit apps
1530 return samWOW64ViewMode
;
1533 long GetMSWAccessFlags(wxRegKey::AccessMode mode
,
1534 wxRegKey::WOW64ViewMode viewMode
)
1536 long sam
= mode
== wxRegKey::Read
? KEY_READ
: KEY_ALL_ACCESS
;
1538 sam
|= GetMSWViewFlags(viewMode
);
1543 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1545 wxString
str(pKey
->GetName());
1546 if ( !szValue
.empty() )
1547 str
<< wxT("\\") << szValue
;
1552 wxString
GetFullName(const wxRegKey
*pKey
)
1554 return pKey
->GetName();
1557 inline void RemoveTrailingSeparator(wxString
& str
)
1559 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1560 str
.Truncate(str
.Len() - 1);
1563 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1565 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1568 #endif // wxUSE_REGKEY