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 // ----------------------------------------------------------------------------
73 // ----------------------------------------------------------------------------
75 // the standard key names, short names and handles all bundled together for
81 const wxChar
*szShortName
;
85 { HKEY_CLASSES_ROOT
, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
86 { HKEY_CURRENT_USER
, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
87 { HKEY_LOCAL_MACHINE
, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
88 { HKEY_USERS
, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
89 { HKEY_PERFORMANCE_DATA
, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
90 { HKEY_CURRENT_CONFIG
, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
91 { HKEY_DYN_DATA
, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
94 // the registry name separator (perhaps one day MS will change it to '/' ;-)
95 #define REG_SEPARATOR wxT('\\')
97 // useful for Windows programmers: makes somewhat more clear all these zeroes
98 // being passed to Windows APIs
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
105 // const_cast<> is not yet supported by all compilers
106 #define CONST_CAST ((wxRegKey *)this)->
108 // and neither is mutable which m_dwLastError should be
109 #define m_dwLastError CONST_CAST m_dwLastError
111 // ----------------------------------------------------------------------------
112 // non member functions
113 // ----------------------------------------------------------------------------
115 // removes the trailing backslash from the string if it has one
116 static inline void RemoveTrailingSeparator(wxString
& str
);
118 // returns true if given registry key exists
119 static bool KeyExists(
121 const wxString
& szKey
,
122 wxRegKey::WOW64ViewMode viewMode
= wxRegKey::WOW64ViewMode_Default
);
124 // return the WOW64 registry view flag which can be used with MSW registry
125 // functions for opening the key in the specified view
126 static long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
);
128 // return the access rights which can be used with MSW registry functions for
129 // opening the key in the specified mode
131 GetMSWAccessFlags(wxRegKey::AccessMode mode
, wxRegKey::WOW64ViewMode viewMode
);
133 // combines value and key name
134 static wxString
GetFullName(const wxRegKey
*pKey
);
135 static wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
);
137 // returns "value" argument of wxRegKey methods converted into a value that can
138 // be passed to win32 registry functions; specifically, converts empty string
140 static inline const wxChar
*RegValueStr(const wxString
& szValue
);
142 // ============================================================================
143 // implementation of wxRegKey class
144 // ============================================================================
146 // ----------------------------------------------------------------------------
147 // static functions and variables
148 // ----------------------------------------------------------------------------
150 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
152 // @@ should take a `StdKey key', but as it's often going to be used in loops
153 // it would require casts in user code.
154 const wxChar
*wxRegKey::GetStdKeyName(size_t key
)
156 // return empty string if key is invalid
157 wxCHECK_MSG( key
< nStdKeys
, wxEmptyString
, wxT("invalid key in wxRegKey::GetStdKeyName") );
159 return aStdKeys
[key
].szName
;
162 const wxChar
*wxRegKey::GetStdKeyShortName(size_t key
)
164 // return empty string if key is invalid
165 wxCHECK( key
< nStdKeys
, wxEmptyString
);
167 return aStdKeys
[key
].szShortName
;
170 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
172 wxString strRoot
= strKey
.BeforeFirst(REG_SEPARATOR
);
175 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
176 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
177 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
182 if ( ui
== nStdKeys
) {
183 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
188 strKey
= strKey
.After(REG_SEPARATOR
);
189 if ( !strKey
.empty() && strKey
.Last() == REG_SEPARATOR
)
190 strKey
.Truncate(strKey
.Len() - 1);
196 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
198 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
199 if ( aStdKeys
[ui
].hkey
== (HKEY
)hkey
)
203 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
212 wxRegKey::wxRegKey(WOW64ViewMode viewMode
) : m_viewMode(viewMode
)
214 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
219 wxRegKey::wxRegKey(const wxString
& strKey
, WOW64ViewMode viewMode
)
220 : m_strKey(strKey
), m_viewMode(viewMode
)
222 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
227 // parent is a predefined (and preopened) key
228 wxRegKey::wxRegKey(StdKey keyParent
,
229 const wxString
& strKey
,
230 WOW64ViewMode viewMode
)
231 : m_strKey(strKey
), m_viewMode(viewMode
)
233 RemoveTrailingSeparator(m_strKey
);
234 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
239 // parent is a normal regkey
240 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
241 : m_strKey(keyParent
.m_strKey
), m_viewMode(keyParent
.GetView())
243 // combine our name with parent's to get the full name
244 if ( !m_strKey
.empty() &&
245 (strKey
.empty() || strKey
[0] != REG_SEPARATOR
) ) {
246 m_strKey
+= REG_SEPARATOR
;
250 RemoveTrailingSeparator(m_strKey
);
252 m_hRootKey
= keyParent
.m_hRootKey
;
257 // dtor closes the key releasing system resource
258 wxRegKey::~wxRegKey()
263 // ----------------------------------------------------------------------------
264 // change the key name/hkey
265 // ----------------------------------------------------------------------------
267 // set the full key name
268 void wxRegKey::SetName(const wxString
& strKey
)
273 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
276 // the name is relative to the parent key
277 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
282 RemoveTrailingSeparator(m_strKey
);
283 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
286 // the name is relative to the parent key
287 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
291 // combine our name with parent's to get the full name
293 // NB: this method is called by wxRegConfig::SetPath() which is a performance
294 // critical function and so it preallocates space for our m_strKey to
295 // gain some speed - this is why we only use += here and not = which
296 // would just free the prealloc'd buffer and would have to realloc it the
299 m_strKey
+= keyParent
.m_strKey
;
300 if ( !strKey
.empty() && strKey
[0] != REG_SEPARATOR
)
301 m_strKey
+= REG_SEPARATOR
;
304 RemoveTrailingSeparator(m_strKey
);
306 m_hRootKey
= keyParent
.m_hRootKey
;
309 // hKey should be opened and will be closed in wxRegKey dtor
310 void wxRegKey::SetHkey(WXHKEY hKey
)
316 // we don't know the parent of this key, assume HKLM by default
317 m_hRootKey
= HKEY_LOCAL_MACHINE
;
319 // we don't know in which mode was this key opened but we can't reopen it
320 // anyhow because we don't know its name, so the only thing we can is to hope
321 // that it allows all the operations which we're going to perform on it
329 // ----------------------------------------------------------------------------
330 // info about the key
331 // ----------------------------------------------------------------------------
333 // returns true if the key exists
334 bool wxRegKey::Exists() const
336 // opened key has to exist, try to open it if not done yet
339 : KeyExists(m_hRootKey
, m_strKey
, m_viewMode
);
342 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
343 wxString
wxRegKey::GetName(bool bShortPrefix
) const
345 StdKey key
= GetStdKeyFromHkey((WXHKEY
) m_hRootKey
);
346 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
347 : aStdKeys
[key
].szName
;
348 if ( !m_strKey
.empty() )
349 str
<< wxT("\\") << m_strKey
;
354 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys
,
357 size_t *pnMaxValueLen
) const
359 // old gcc headers incorrectly prototype RegQueryInfoKey()
360 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
361 #define REG_PARAM (size_t *)
363 #define REG_PARAM (LPDWORD)
366 // it might be unexpected to some that this function doesn't open the key
367 wxASSERT_MSG( IsOpened(), wxT("key should be opened in GetKeyInfo") );
369 m_dwLastError
= ::RegQueryInfoKey
373 NULL
, // (ptr to) size of class name buffer
376 pnSubKeys
, // [out] number of subkeys
378 pnMaxKeyLen
, // [out] max length of a subkey name
379 NULL
, // longest subkey class name
381 pnValues
, // [out] number of values
383 pnMaxValueLen
, // [out] max length of a value name
384 NULL
, // longest value data
385 NULL
, // security descriptor
386 NULL
// time of last modification
391 if ( m_dwLastError
!= ERROR_SUCCESS
) {
392 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
400 // ----------------------------------------------------------------------------
402 // ----------------------------------------------------------------------------
404 // opens key (it's not an error to call Open() on an already opened key)
405 bool wxRegKey::Open(AccessMode mode
)
409 if ( mode
<= m_mode
)
412 // we had been opened in read mode but now must be reopened in write
417 m_dwLastError
= ::RegOpenKeyEx
422 GetMSWAccessFlags(mode
, m_viewMode
),
426 if ( m_dwLastError
!= ERROR_SUCCESS
)
428 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
433 m_hKey
= (WXHKEY
) tmpKey
;
439 // creates key, failing if it exists and !bOkIfExists
440 bool wxRegKey::Create(bool bOkIfExists
)
442 // check for existence only if asked (i.e. order is important!)
443 if ( !bOkIfExists
&& Exists() )
451 // Minimum supported OS for RegCreateKeyEx: Win 95, Win NT 3.1, Win CE 1.0
452 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.t_str(),
453 0, // reserved and must be 0
454 NULL
, // The user-defined class type of this key.
455 REG_OPTION_NON_VOLATILE
, // supports other values as well; see MS docs
456 GetMSWAccessFlags(wxRegKey::Write
, m_viewMode
),
457 NULL
, // pointer to a SECURITY_ATTRIBUTES structure
461 if ( m_dwLastError
!= ERROR_SUCCESS
) {
462 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
468 m_hKey
= (WXHKEY
) tmpKey
;
473 // close the key, it's not an error to call it when not opened
474 bool wxRegKey::Close()
477 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
480 if ( m_dwLastError
!= ERROR_SUCCESS
) {
481 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
492 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
495 if ( HasValue(szValueNew
) ) {
496 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
502 !CopyValue(szValueOld
, *this, szValueNew
) ||
503 !DeleteValue(szValueOld
) ) {
504 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
505 szValueOld
, szValueNew
);
513 bool wxRegKey::CopyValue(const wxString
& szValue
,
515 const wxString
& szValueNew
)
517 wxString
valueNew(szValueNew
);
518 if ( valueNew
.empty() ) {
519 // by default, use the same name
523 switch ( GetValueType(szValue
) ) {
527 return QueryValue(szValue
, strVal
) &&
528 keyDst
.SetValue(valueNew
, strVal
);
532 /* case Type_Dword_little_endian: == Type_Dword */
535 return QueryValue(szValue
, &dwVal
) &&
536 keyDst
.SetValue(valueNew
, dwVal
);
542 return QueryValue(szValue
,buf
) &&
543 keyDst
.SetValue(valueNew
,buf
);
546 // these types are unsupported because I am not sure about how
547 // exactly they should be copied and because they shouldn't
548 // occur among the application keys (supposedly created with
551 case Type_Expand_String
:
552 case Type_Dword_big_endian
:
554 case Type_Multi_String
:
555 case Type_Resource_list
:
556 case Type_Full_resource_descriptor
:
557 case Type_Resource_requirements_list
:
559 wxLogError(_("Can't copy values of unsupported type %d."),
560 GetValueType(szValue
));
565 bool wxRegKey::Rename(const wxString
& szNewName
)
567 wxCHECK_MSG( !m_strKey
.empty(), false, wxT("registry hives can't be renamed") );
570 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
576 // do we stay in the same hive?
577 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
579 // construct the full new name of the key
583 // rename the key to the new name under the same parent
584 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
585 if ( !strKey
.empty() ) {
586 // don't add '\\' in the start if strFullNewName is empty
587 strKey
+= REG_SEPARATOR
;
592 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
595 // this is the full name already
596 keyDst
.SetName(szNewName
);
599 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
601 wxLogError(_("Registry key '%s' already exists."),
602 GetFullName(&keyDst
));
605 ok
= Copy(keyDst
) && DeleteSelf();
609 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
610 GetFullName(this), GetFullName(&keyDst
));
613 m_hRootKey
= keyDst
.m_hRootKey
;
614 m_strKey
= keyDst
.m_strKey
;
620 bool wxRegKey::Copy(const wxString
& szNewName
)
622 // create the new key first
623 wxRegKey
keyDst(szNewName
);
624 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
628 // we created the dest key but copying to it failed - delete it
630 (void)keyDst
.DeleteSelf();
637 bool wxRegKey::Copy(wxRegKey
& keyDst
)
641 // copy all sub keys to the new location
644 bool bCont
= GetFirstKey(strKey
, lIndex
);
645 while ( ok
&& bCont
) {
646 wxRegKey
key(*this, strKey
);
648 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
649 ok
= key
.Copy(keyName
);
652 bCont
= GetNextKey(strKey
, lIndex
);
654 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
655 GetFullName(&key
), keyName
.c_str());
661 bCont
= GetFirstValue(strVal
, lIndex
);
662 while ( ok
&& bCont
) {
663 ok
= CopyValue(strVal
, keyDst
);
666 wxLogSysError(m_dwLastError
,
667 _("Failed to copy registry value '%s'"),
671 bCont
= GetNextValue(strVal
, lIndex
);
676 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
677 GetFullName(this), GetFullName(&keyDst
));
683 // ----------------------------------------------------------------------------
684 // delete keys/values
685 // ----------------------------------------------------------------------------
686 bool wxRegKey::DeleteSelf()
691 // it already doesn't exist - ok!
696 // prevent a buggy program from erasing one of the root registry keys or an
697 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
698 // key except HKCR (HKCR has some "deleteable" subkeys)
699 if ( m_strKey
.empty() ||
700 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
701 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
702 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
708 // we can't delete keys while enumerating because it confuses GetNextKey, so
709 // we first save the key names and then delete them all
710 wxArrayString astrSubkeys
;
714 bool bCont
= GetFirstKey(strKey
, lIndex
);
716 astrSubkeys
.Add(strKey
);
718 bCont
= GetNextKey(strKey
, lIndex
);
721 size_t nKeyCount
= astrSubkeys
.Count();
722 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
723 wxRegKey
key(*this, astrSubkeys
[nKey
]);
724 if ( !key
.DeleteSelf() )
728 // now delete this key itself
731 // deleting a key which doesn't exist is not considered an error
732 #if wxUSE_DYNLIB_CLASS
733 wxDynamicLibrary
dllAdvapi32(wxT("advapi32"));
734 // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1
735 if(dllAdvapi32
.HasSymbol(wxT("RegDeleteKeyEx")))
737 typedef LONG (WINAPI
*RegDeleteKeyEx_t
)(HKEY
, LPCTSTR
, REGSAM
, DWORD
);
738 wxDYNLIB_FUNCTION(RegDeleteKeyEx_t
, RegDeleteKeyEx
, dllAdvapi32
);
740 m_dwLastError
= (*pfnRegDeleteKeyEx
)((HKEY
) m_hRootKey
, m_strKey
.t_str(),
741 GetMSWViewFlags(m_viewMode
),
742 0); // This parameter is reserved and must be zero.
745 #endif // wxUSE_DYNLIB_CLASS
747 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
750 if ( m_dwLastError
!= ERROR_SUCCESS
&&
751 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
752 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
760 bool wxRegKey::DeleteKey(const wxString
& szKey
)
765 wxRegKey
key(*this, szKey
);
766 return key
.DeleteSelf();
769 bool wxRegKey::DeleteValue(const wxString
& szValue
)
774 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
776 // deleting a value which doesn't exist is not considered an error
777 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
778 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
780 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
781 szValue
, GetName().c_str());
788 // ----------------------------------------------------------------------------
789 // access to values and subkeys
790 // ----------------------------------------------------------------------------
792 // return true if value exists
793 bool wxRegKey::HasValue(const wxString
& szValue
) const
795 // this function should be silent, so suppress possible messages from Open()
798 if ( !CONST_CAST
Open(Read
) )
801 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
802 RegValueStr(szValue
),
805 return dwRet
== ERROR_SUCCESS
;
808 // returns true if this key has any values
809 bool wxRegKey::HasValues() const
811 // suppress possible messages from GetFirstValue()
814 // just call GetFirstValue with dummy parameters
817 return CONST_CAST
GetFirstValue(str
, l
);
820 // returns true if this key has any subkeys
821 bool wxRegKey::HasSubkeys() const
823 // suppress possible messages from GetFirstKey()
826 // just call GetFirstKey with dummy parameters
829 return CONST_CAST
GetFirstKey(str
, l
);
832 // returns true if given subkey exists
833 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
835 // this function should be silent, so suppress possible messages from Open()
838 if ( !CONST_CAST
Open(Read
) )
841 return KeyExists(m_hKey
, szKey
, m_viewMode
);
844 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
846 if ( ! CONST_CAST
Open(Read
) )
850 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
851 &dwType
, NULL
, NULL
);
852 if ( m_dwLastError
!= ERROR_SUCCESS
) {
853 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
858 return (ValueType
)dwType
;
861 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
863 if ( CONST_CAST
Open() ) {
864 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
865 (DWORD
) RESERVED
, REG_DWORD
,
866 (RegString
)&lValue
, sizeof(lValue
));
867 if ( m_dwLastError
== ERROR_SUCCESS
)
871 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
872 GetFullName(this, szValue
));
876 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
878 if ( CONST_CAST
Open(Read
) ) {
879 DWORD dwType
, dwSize
= sizeof(DWORD
);
880 RegString pBuf
= (RegString
)plValue
;
881 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
883 &dwType
, pBuf
, &dwSize
);
884 if ( m_dwLastError
!= ERROR_SUCCESS
) {
885 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
890 // check that we read the value of right type
891 wxASSERT_MSG( IsNumericValue(szValue
),
892 wxT("Type mismatch in wxRegKey::QueryValue().") );
901 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
904 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
907 if ( CONST_CAST
Open() ) {
908 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
909 (DWORD
) RESERVED
, REG_BINARY
,
910 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
911 if ( m_dwLastError
== ERROR_SUCCESS
)
915 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
916 GetFullName(this, szValue
));
921 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
923 if ( CONST_CAST
Open(Read
) ) {
924 // first get the type and size of the data
925 DWORD dwType
, dwSize
;
926 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
928 &dwType
, NULL
, &dwSize
);
930 if ( m_dwLastError
== ERROR_SUCCESS
) {
932 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
933 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
934 RegValueStr(szValue
),
939 buffer
.UngetWriteBuf(dwSize
);
941 buffer
.SetDataLen(0);
946 if ( m_dwLastError
!= ERROR_SUCCESS
) {
947 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
958 bool wxRegKey::QueryValue(const wxString
& szValue
,
960 bool WXUNUSED_IN_WINCE(raw
)) const
962 if ( CONST_CAST
Open(Read
) )
965 // first get the type and size of the data
966 DWORD dwType
=REG_NONE
, dwSize
=0;
967 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
968 RegValueStr(szValue
),
970 &dwType
, NULL
, &dwSize
);
971 if ( m_dwLastError
== ERROR_SUCCESS
)
975 // must treat this case specially as GetWriteBuf() doesn't like
976 // being called with 0 size
981 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
982 RegValueStr(szValue
),
985 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
988 // expand the var expansions in the string unless disabled
990 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
992 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
993 bool ok
= dwExpSize
!= 0;
996 wxString strExpValue
;
997 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
998 wxStringBuffer(strExpValue
, dwExpSize
),
1001 strValue
= strExpValue
;
1006 wxLogLastError(wxT("ExpandEnvironmentStrings"));
1013 if ( m_dwLastError
== ERROR_SUCCESS
)
1015 // check that it was the right type
1016 wxASSERT_MSG( !IsNumericValue(szValue
),
1017 wxT("Type mismatch in wxRegKey::QueryValue().") );
1024 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
1025 GetFullName(this, szValue
));
1029 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
1031 if ( CONST_CAST
Open() ) {
1032 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
1033 RegValueStr(szValue
),
1034 (DWORD
) RESERVED
, REG_SZ
,
1035 (RegString
)strValue
.t_str(),
1036 (strValue
.Len() + 1)*sizeof(wxChar
));
1037 if ( m_dwLastError
== ERROR_SUCCESS
)
1041 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
1042 GetFullName(this, szValue
));
1046 wxString
wxRegKey::QueryDefaultValue() const
1049 QueryValue(wxEmptyString
, str
, false);
1053 // ----------------------------------------------------------------------------
1055 // NB: all these functions require an index variable which allows to have
1056 // several concurrently running indexations on the same key
1057 // ----------------------------------------------------------------------------
1059 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1065 return GetNextValue(strValueName
, lIndex
);
1068 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1070 wxASSERT( IsOpened() );
1072 // are we already at the end of enumeration?
1076 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1077 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1079 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1080 szValueName
, &dwValueLen
,
1083 NULL
, // [out] buffer for value
1084 NULL
); // [i/o] it's length
1086 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1087 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1088 m_dwLastError
= ERROR_SUCCESS
;
1092 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1099 strValueName
= szValueName
;
1104 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1110 return GetNextKey(strKeyName
, lIndex
);
1113 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1115 wxASSERT( IsOpened() );
1117 // are we already at the end of enumeration?
1121 wxChar szKeyName
[_MAX_PATH
+ 1];
1124 DWORD sizeName
= WXSIZEOF(szKeyName
);
1125 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1126 0, NULL
, NULL
, NULL
);
1128 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1131 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1132 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1133 m_dwLastError
= ERROR_SUCCESS
;
1137 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1144 strKeyName
= szKeyName
;
1148 // returns true if the value contains a number (else it's some string)
1149 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1151 ValueType type
= GetValueType(szValue
);
1154 /* case Type_Dword_little_endian: == Type_Dword */
1155 case Type_Dword_big_endian
:
1163 // ----------------------------------------------------------------------------
1164 // exporting registry keys to file
1165 // ----------------------------------------------------------------------------
1169 // helper functions for writing ASCII strings (even in Unicode build)
1170 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1176 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1178 // as we open the file in text mode, it is enough to write LF without CR
1179 return WriteAsciiChar(ostr
, '\n');
1182 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1184 return ostr
.Write(p
, strlen(p
)).IsOk();
1187 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1190 wxCharBuffer
name(s
.mb_str());
1191 ostr
.Write(name
, strlen(name
));
1193 ostr
.Write(s
.mb_str(), s
.length());
1199 #endif // wxUSE_STREAMS
1201 bool wxRegKey::Export(const wxString
& filename
) const
1203 #if wxUSE_FFILE && wxUSE_STREAMS
1204 if ( wxFile::Exists(filename
) )
1206 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1211 wxFFileOutputStream
ostr(filename
, wxT("w"));
1213 return ostr
.Ok() && Export(ostr
);
1215 wxUnusedVar(filename
);
1221 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1223 // write out the header
1224 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1227 return DoExport(ostr
);
1229 #endif // wxUSE_STREAMS
1233 FormatAsHex(const void *data
,
1235 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1237 wxString
value(wxT("hex"));
1239 // binary values use just "hex:" prefix while the other ones must indicate
1241 if ( type
!= wxRegKey::Type_Binary
)
1242 value
<< wxT('(') << type
<< wxT(')');
1245 // write all the rest as comma-separated bytes
1246 value
.reserve(3*size
+ 10);
1247 const char * const p
= static_cast<const char *>(data
);
1248 for ( size_t n
= 0; n
< size
; n
++ )
1250 // TODO: line wrapping: although not required by regedit, this makes
1251 // the generated files easier to read and compare with the files
1252 // produced by regedit
1256 value
<< wxString::Format(wxT("%02x"), (unsigned char)p
[n
]);
1263 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1265 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1268 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1271 const ValueType type
= GetValueType(name
);
1277 if ( !QueryValue(name
, value
) )
1280 // quotes and backslashes must be quoted, linefeeds are not
1281 // allowed in string values
1282 rhs
.reserve(value
.length() + 2);
1285 // there can be no NULs here
1286 bool useHex
= false;
1287 for ( wxString::const_iterator p
= value
.begin();
1288 p
!= value
.end() && !useHex
; ++p
)
1290 switch ( (*p
).GetValue() )
1293 // we can only represent this string in hex
1299 // escape special symbol
1309 rhs
= FormatAsHex(value
, Type_String
);
1316 /* case Type_Dword_little_endian: == Type_Dword */
1319 if ( !QueryValue(name
, &value
) )
1322 rhs
.Printf(wxT("dword:%08x"), (unsigned int)value
);
1326 case Type_Expand_String
:
1327 case Type_Multi_String
:
1330 if ( !QueryRawValue(name
, value
) )
1333 rhs
= FormatAsHex(value
, type
);
1340 if ( !QueryValue(name
, buf
) )
1343 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1347 // no idea how those appear in REGEDIT4 files
1349 case Type_Dword_big_endian
:
1351 case Type_Resource_list
:
1352 case Type_Full_resource_descriptor
:
1353 case Type_Resource_requirements_list
:
1355 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1363 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1365 // first examine the value type: if it's unsupported, simply skip it
1366 // instead of aborting the entire export process because we failed to
1367 // export a single value
1368 wxString value
= FormatValue(name
);
1369 if ( value
.empty() )
1371 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1372 name
.c_str(), GetName().c_str());
1376 // we do have the text representation of the value, now write everything
1379 // special case: unnamed/default value is represented as just "@"
1382 if ( !WriteAsciiChar(ostr
, '@') )
1385 else // normal, named, value
1387 if ( !WriteAsciiChar(ostr
, '"') ||
1388 !WriteAsciiString(ostr
, name
) ||
1389 !WriteAsciiChar(ostr
, '"') )
1393 if ( !WriteAsciiChar(ostr
, '=') )
1396 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1399 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1401 // write out this key name
1402 if ( !WriteAsciiChar(ostr
, '[') )
1405 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1408 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1411 // dump all our values
1414 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1415 bool cont
= self
.GetFirstValue(name
, dummy
);
1418 if ( !DoExportValue(ostr
, name
) )
1421 cont
= GetNextValue(name
, dummy
);
1424 // always terminate values by blank line, even if there were no values
1425 if ( !WriteAsciiEOL(ostr
) )
1428 // recurse to subkeys
1429 cont
= self
.GetFirstKey(name
, dummy
);
1432 wxRegKey
subkey(*this, name
);
1433 if ( !subkey
.DoExport(ostr
) )
1436 cont
= GetNextKey(name
, dummy
);
1442 #endif // wxUSE_STREAMS
1444 // ============================================================================
1445 // implementation of global private functions
1446 // ============================================================================
1448 bool KeyExists(WXHKEY hRootKey
,
1449 const wxString
& szKey
,
1450 wxRegKey::WOW64ViewMode viewMode
)
1452 // don't close this key itself for the case of empty szKey!
1453 if ( szKey
.empty() )
1462 // we might not have enough rights for rw access
1463 GetMSWAccessFlags(wxRegKey::Read
, viewMode
),
1465 ) == ERROR_SUCCESS
)
1467 ::RegCloseKey(hkeyDummy
);
1475 long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
)
1477 long samWOW64ViewMode
= 0;
1481 case wxRegKey::WOW64ViewMode_32
:
1482 #ifdef __WIN64__ // the flag is only needed by 64 bit apps
1483 samWOW64ViewMode
= KEY_WOW64_32KEY
;
1487 case wxRegKey::WOW64ViewMode_64
:
1488 #ifndef __WIN64__ // the flag is only needed by 32 bit apps
1489 // 64 bit registry can only be accessed under 64 bit platforms
1490 if ( wxIsPlatform64Bit() )
1491 samWOW64ViewMode
= KEY_WOW64_64KEY
;
1496 wxFAIL_MSG("Unknown registry view.");
1499 case wxRegKey::WOW64ViewMode_Default
:
1500 // Use default registry view for the current application,
1501 // i.e. 32 bits for 32 bit ones and 64 bits for 64 bit apps
1505 return samWOW64ViewMode
;
1508 long GetMSWAccessFlags(wxRegKey::AccessMode mode
,
1509 wxRegKey::WOW64ViewMode viewMode
)
1511 long sam
= mode
== wxRegKey::Read
? KEY_READ
: KEY_ALL_ACCESS
;
1513 sam
|= GetMSWViewFlags(viewMode
);
1518 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1520 wxString
str(pKey
->GetName());
1521 if ( !szValue
.empty() )
1522 str
<< wxT("\\") << szValue
;
1527 wxString
GetFullName(const wxRegKey
*pKey
)
1529 return pKey
->GetName();
1532 inline void RemoveTrailingSeparator(wxString
& str
)
1534 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1535 str
.Truncate(str
.Len() - 1);
1538 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1540 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1543 #endif // wxUSE_REGKEY