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 // old gcc headers incorrectly prototype RegQueryInfoKey()
364 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
365 #define REG_PARAM (size_t *)
367 #define REG_PARAM (LPDWORD)
370 // it might be unexpected to some that this function doesn't open the key
371 wxASSERT_MSG( IsOpened(), wxT("key should be opened in GetKeyInfo") );
373 m_dwLastError
= ::RegQueryInfoKey
377 NULL
, // (ptr to) size of class name buffer
380 pnSubKeys
, // [out] number of subkeys
382 pnMaxKeyLen
, // [out] max length of a subkey name
383 NULL
, // longest subkey class name
385 pnValues
, // [out] number of values
387 pnMaxValueLen
, // [out] max length of a value name
388 NULL
, // longest value data
389 NULL
, // security descriptor
390 NULL
// time of last modification
395 if ( m_dwLastError
!= ERROR_SUCCESS
) {
396 wxLogSysError(m_dwLastError
, _("Can't get info about registry key '%s'"),
404 // ----------------------------------------------------------------------------
406 // ----------------------------------------------------------------------------
408 // opens key (it's not an error to call Open() on an already opened key)
409 bool wxRegKey::Open(AccessMode mode
)
413 if ( mode
<= m_mode
)
416 // we had been opened in read mode but now must be reopened in write
421 m_dwLastError
= ::RegOpenKeyEx
426 GetMSWAccessFlags(mode
, m_viewMode
),
430 if ( m_dwLastError
!= ERROR_SUCCESS
)
432 wxLogSysError(m_dwLastError
, _("Can't open registry key '%s'"),
437 m_hKey
= (WXHKEY
) tmpKey
;
443 // creates key, failing if it exists and !bOkIfExists
444 bool wxRegKey::Create(bool bOkIfExists
)
446 // check for existence only if asked (i.e. order is important!)
447 if ( !bOkIfExists
&& Exists() )
455 // Minimum supported OS for RegCreateKeyEx: Win 95, Win NT 3.1, Win CE 1.0
456 m_dwLastError
= RegCreateKeyEx((HKEY
) m_hRootKey
, m_strKey
.t_str(),
457 0, // reserved and must be 0
458 NULL
, // The user-defined class type of this key.
459 REG_OPTION_NON_VOLATILE
, // supports other values as well; see MS docs
460 GetMSWAccessFlags(wxRegKey::Write
, m_viewMode
),
461 NULL
, // pointer to a SECURITY_ATTRIBUTES structure
465 if ( m_dwLastError
!= ERROR_SUCCESS
) {
466 wxLogSysError(m_dwLastError
, _("Can't create registry key '%s'"),
472 m_hKey
= (WXHKEY
) tmpKey
;
477 // close the key, it's not an error to call it when not opened
478 bool wxRegKey::Close()
481 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
484 if ( m_dwLastError
!= ERROR_SUCCESS
) {
485 wxLogSysError(m_dwLastError
, _("Can't close registry key '%s'"),
496 wxRegKey::RenameValue(const wxString
& szValueOld
, const wxString
& szValueNew
)
499 if ( HasValue(szValueNew
) ) {
500 wxLogError(_("Registry value '%s' already exists."), szValueNew
);
506 !CopyValue(szValueOld
, *this, szValueNew
) ||
507 !DeleteValue(szValueOld
) ) {
508 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
509 szValueOld
, szValueNew
);
517 bool wxRegKey::CopyValue(const wxString
& szValue
,
519 const wxString
& szValueNew
)
521 wxString
valueNew(szValueNew
);
522 if ( valueNew
.empty() ) {
523 // by default, use the same name
527 switch ( GetValueType(szValue
) ) {
531 return QueryValue(szValue
, strVal
) &&
532 keyDst
.SetValue(valueNew
, strVal
);
536 /* case Type_Dword_little_endian: == Type_Dword */
539 return QueryValue(szValue
, &dwVal
) &&
540 keyDst
.SetValue(valueNew
, dwVal
);
546 return QueryValue(szValue
,buf
) &&
547 keyDst
.SetValue(valueNew
,buf
);
550 // these types are unsupported because I am not sure about how
551 // exactly they should be copied and because they shouldn't
552 // occur among the application keys (supposedly created with
555 case Type_Expand_String
:
556 case Type_Dword_big_endian
:
558 case Type_Multi_String
:
559 case Type_Resource_list
:
560 case Type_Full_resource_descriptor
:
561 case Type_Resource_requirements_list
:
563 wxLogError(_("Can't copy values of unsupported type %d."),
564 GetValueType(szValue
));
569 bool wxRegKey::Rename(const wxString
& szNewName
)
571 wxCHECK_MSG( !m_strKey
.empty(), false, wxT("registry hives can't be renamed") );
574 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
580 // do we stay in the same hive?
581 bool inSameHive
= !wxStrchr(szNewName
, REG_SEPARATOR
);
583 // construct the full new name of the key
587 // rename the key to the new name under the same parent
588 wxString strKey
= m_strKey
.BeforeLast(REG_SEPARATOR
);
589 if ( !strKey
.empty() ) {
590 // don't add '\\' in the start if strFullNewName is empty
591 strKey
+= REG_SEPARATOR
;
596 keyDst
.SetName(GetStdKeyFromHkey(m_hRootKey
), strKey
);
599 // this is the full name already
600 keyDst
.SetName(szNewName
);
603 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
605 wxLogError(_("Registry key '%s' already exists."),
606 GetFullName(&keyDst
));
609 ok
= Copy(keyDst
) && DeleteSelf();
613 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
614 GetFullName(this), GetFullName(&keyDst
));
617 m_hRootKey
= keyDst
.m_hRootKey
;
618 m_strKey
= keyDst
.m_strKey
;
624 bool wxRegKey::Copy(const wxString
& szNewName
)
626 // create the new key first
627 wxRegKey
keyDst(szNewName
);
628 bool ok
= keyDst
.Create(false /* fail if alredy exists */);
632 // we created the dest key but copying to it failed - delete it
634 (void)keyDst
.DeleteSelf();
641 bool wxRegKey::Copy(wxRegKey
& keyDst
)
645 // copy all sub keys to the new location
648 bool bCont
= GetFirstKey(strKey
, lIndex
);
649 while ( ok
&& bCont
) {
650 wxRegKey
key(*this, strKey
);
652 keyName
<< GetFullName(&keyDst
) << REG_SEPARATOR
<< strKey
;
653 ok
= key
.Copy(keyName
);
656 bCont
= GetNextKey(strKey
, lIndex
);
658 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
659 GetFullName(&key
), keyName
.c_str());
665 bCont
= GetFirstValue(strVal
, lIndex
);
666 while ( ok
&& bCont
) {
667 ok
= CopyValue(strVal
, keyDst
);
670 wxLogSysError(m_dwLastError
,
671 _("Failed to copy registry value '%s'"),
675 bCont
= GetNextValue(strVal
, lIndex
);
680 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
681 GetFullName(this), GetFullName(&keyDst
));
687 // ----------------------------------------------------------------------------
688 // delete keys/values
689 // ----------------------------------------------------------------------------
690 bool wxRegKey::DeleteSelf()
695 // it already doesn't exist - ok!
700 // prevent a buggy program from erasing one of the root registry keys or an
701 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
702 // key except HKCR (HKCR has some "deleteable" subkeys)
703 if ( m_strKey
.empty() ||
704 ((m_hRootKey
!= (WXHKEY
) aStdKeys
[HKCR
].hkey
) &&
705 (m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
)) ) {
706 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
712 // we can't delete keys while enumerating because it confuses GetNextKey, so
713 // we first save the key names and then delete them all
714 wxArrayString astrSubkeys
;
718 bool bCont
= GetFirstKey(strKey
, lIndex
);
720 astrSubkeys
.Add(strKey
);
722 bCont
= GetNextKey(strKey
, lIndex
);
725 size_t nKeyCount
= astrSubkeys
.Count();
726 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
727 wxRegKey
key(*this, astrSubkeys
[nKey
]);
728 if ( !key
.DeleteSelf() )
732 // now delete this key itself
735 // deleting a key which doesn't exist is not considered an error
736 #if wxUSE_DYNLIB_CLASS
737 wxDynamicLibrary
dllAdvapi32(wxT("advapi32"));
738 // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1
739 if(dllAdvapi32
.HasSymbol(wxT("RegDeleteKeyEx")))
741 typedef LONG (WINAPI
*RegDeleteKeyEx_t
)(HKEY
, LPCTSTR
, REGSAM
, DWORD
);
742 wxDYNLIB_FUNCTION(RegDeleteKeyEx_t
, RegDeleteKeyEx
, dllAdvapi32
);
744 m_dwLastError
= (*pfnRegDeleteKeyEx
)((HKEY
) m_hRootKey
, m_strKey
.t_str(),
745 GetMSWViewFlags(m_viewMode
),
746 0); // This parameter is reserved and must be zero.
749 #endif // wxUSE_DYNLIB_CLASS
751 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
.t_str());
754 if ( m_dwLastError
!= ERROR_SUCCESS
&&
755 m_dwLastError
!= ERROR_FILE_NOT_FOUND
) {
756 wxLogSysError(m_dwLastError
, _("Can't delete key '%s'"),
764 bool wxRegKey::DeleteKey(const wxString
& szKey
)
769 wxRegKey
key(*this, szKey
);
770 return key
.DeleteSelf();
773 bool wxRegKey::DeleteValue(const wxString
& szValue
)
778 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, RegValueStr(szValue
));
780 // deleting a value which doesn't exist is not considered an error
781 if ( (m_dwLastError
!= ERROR_SUCCESS
) &&
782 (m_dwLastError
!= ERROR_FILE_NOT_FOUND
) )
784 wxLogSysError(m_dwLastError
, _("Can't delete value '%s' from key '%s'"),
785 szValue
, GetName().c_str());
792 // ----------------------------------------------------------------------------
793 // access to values and subkeys
794 // ----------------------------------------------------------------------------
796 // return true if value exists
797 bool wxRegKey::HasValue(const wxString
& szValue
) const
799 // this function should be silent, so suppress possible messages from Open()
802 if ( !CONST_CAST
Open(Read
) )
805 LONG dwRet
= ::RegQueryValueEx((HKEY
) m_hKey
,
806 RegValueStr(szValue
),
809 return dwRet
== ERROR_SUCCESS
;
812 // returns true if this key has any values
813 bool wxRegKey::HasValues() const
815 // suppress possible messages from GetFirstValue()
818 // just call GetFirstValue with dummy parameters
821 return CONST_CAST
GetFirstValue(str
, l
);
824 // returns true if this key has any subkeys
825 bool wxRegKey::HasSubkeys() const
827 // suppress possible messages from GetFirstKey()
830 // just call GetFirstKey with dummy parameters
833 return CONST_CAST
GetFirstKey(str
, l
);
836 // returns true if given subkey exists
837 bool wxRegKey::HasSubKey(const wxString
& szKey
) const
839 // this function should be silent, so suppress possible messages from Open()
842 if ( !CONST_CAST
Open(Read
) )
845 return KeyExists(m_hKey
, szKey
, m_viewMode
);
848 wxRegKey::ValueType
wxRegKey::GetValueType(const wxString
& szValue
) const
850 if ( ! CONST_CAST
Open(Read
) )
854 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
), RESERVED
,
855 &dwType
, NULL
, NULL
);
856 if ( m_dwLastError
!= ERROR_SUCCESS
) {
857 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
862 return (ValueType
)dwType
;
865 bool wxRegKey::SetValue(const wxString
& szValue
, long lValue
)
867 if ( CONST_CAST
Open() ) {
868 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
869 (DWORD
) RESERVED
, REG_DWORD
,
870 (RegString
)&lValue
, sizeof(lValue
));
871 if ( m_dwLastError
== ERROR_SUCCESS
)
875 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
876 GetFullName(this, szValue
));
880 bool wxRegKey::QueryValue(const wxString
& szValue
, long *plValue
) const
882 if ( CONST_CAST
Open(Read
) ) {
883 DWORD dwType
, dwSize
= sizeof(DWORD
);
884 RegString pBuf
= (RegString
)plValue
;
885 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
887 &dwType
, pBuf
, &dwSize
);
888 if ( m_dwLastError
!= ERROR_SUCCESS
) {
889 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
894 // check that we read the value of right type
895 wxASSERT_MSG( IsNumericValue(szValue
),
896 wxT("Type mismatch in wxRegKey::QueryValue().") );
905 bool wxRegKey::SetValue(const wxString
& szValue
, const wxMemoryBuffer
& buffer
)
908 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
911 if ( CONST_CAST
Open() ) {
912 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
913 (DWORD
) RESERVED
, REG_BINARY
,
914 (RegBinary
)buffer
.GetData(),buffer
.GetDataLen());
915 if ( m_dwLastError
== ERROR_SUCCESS
)
919 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
920 GetFullName(this, szValue
));
925 bool wxRegKey::QueryValue(const wxString
& szValue
, wxMemoryBuffer
& buffer
) const
927 if ( CONST_CAST
Open(Read
) ) {
928 // first get the type and size of the data
929 DWORD dwType
, dwSize
;
930 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, RegValueStr(szValue
),
932 &dwType
, NULL
, &dwSize
);
934 if ( m_dwLastError
== ERROR_SUCCESS
) {
936 const RegBinary pBuf
= (RegBinary
)buffer
.GetWriteBuf(dwSize
);
937 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
938 RegValueStr(szValue
),
943 buffer
.UngetWriteBuf(dwSize
);
945 buffer
.SetDataLen(0);
950 if ( m_dwLastError
!= ERROR_SUCCESS
) {
951 wxLogSysError(m_dwLastError
, _("Can't read value of key '%s'"),
962 bool wxRegKey::QueryValue(const wxString
& szValue
,
964 bool WXUNUSED_IN_WINCE(raw
)) const
966 if ( CONST_CAST
Open(Read
) )
969 // first get the type and size of the data
970 DWORD dwType
=REG_NONE
, dwSize
=0;
971 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
972 RegValueStr(szValue
),
974 &dwType
, NULL
, &dwSize
);
975 if ( m_dwLastError
== ERROR_SUCCESS
)
979 // must treat this case specially as GetWriteBuf() doesn't like
980 // being called with 0 size
985 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
,
986 RegValueStr(szValue
),
989 (RegString
)(wxChar
*)wxStringBuffer(strValue
, dwSize
),
992 // expand the var expansions in the string unless disabled
994 if ( (dwType
== REG_EXPAND_SZ
) && !raw
)
996 DWORD dwExpSize
= ::ExpandEnvironmentStrings(strValue
.t_str(), NULL
, 0);
997 bool ok
= dwExpSize
!= 0;
1000 wxString strExpValue
;
1001 ok
= ::ExpandEnvironmentStrings(strValue
.t_str(),
1002 wxStringBuffer(strExpValue
, dwExpSize
),
1005 strValue
= strExpValue
;
1010 wxLogLastError(wxT("ExpandEnvironmentStrings"));
1017 if ( m_dwLastError
== ERROR_SUCCESS
)
1019 // check that it was the right type
1020 wxASSERT_MSG( !IsNumericValue(szValue
),
1021 wxT("Type mismatch in wxRegKey::QueryValue().") );
1028 wxLogSysError(m_dwLastError
, _("Can't read value of '%s'"),
1029 GetFullName(this, szValue
));
1033 bool wxRegKey::SetValue(const wxString
& szValue
, const wxString
& strValue
)
1035 if ( CONST_CAST
Open() ) {
1036 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
,
1037 RegValueStr(szValue
),
1038 (DWORD
) RESERVED
, REG_SZ
,
1039 (RegString
)strValue
.t_str(),
1040 (strValue
.Len() + 1)*sizeof(wxChar
));
1041 if ( m_dwLastError
== ERROR_SUCCESS
)
1045 wxLogSysError(m_dwLastError
, _("Can't set value of '%s'"),
1046 GetFullName(this, szValue
));
1050 wxString
wxRegKey::QueryDefaultValue() const
1053 QueryValue(wxEmptyString
, str
, false);
1057 // ----------------------------------------------------------------------------
1059 // NB: all these functions require an index variable which allows to have
1060 // several concurrently running indexations on the same key
1061 // ----------------------------------------------------------------------------
1063 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
1069 return GetNextValue(strValueName
, lIndex
);
1072 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
1074 wxASSERT( IsOpened() );
1076 // are we already at the end of enumeration?
1080 wxChar szValueName
[1024]; // @@ use RegQueryInfoKey...
1081 DWORD dwValueLen
= WXSIZEOF(szValueName
);
1083 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
++,
1084 szValueName
, &dwValueLen
,
1087 NULL
, // [out] buffer for value
1088 NULL
); // [i/o] it's length
1090 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1091 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1092 m_dwLastError
= ERROR_SUCCESS
;
1096 wxLogSysError(m_dwLastError
, _("Can't enumerate values of key '%s'"),
1103 strValueName
= szValueName
;
1108 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
1114 return GetNextKey(strKeyName
, lIndex
);
1117 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
1119 wxASSERT( IsOpened() );
1121 // are we already at the end of enumeration?
1125 wxChar szKeyName
[_MAX_PATH
+ 1];
1128 DWORD sizeName
= WXSIZEOF(szKeyName
);
1129 m_dwLastError
= RegEnumKeyEx((HKEY
) m_hKey
, lIndex
++, szKeyName
, & sizeName
,
1130 0, NULL
, NULL
, NULL
);
1132 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
1135 if ( m_dwLastError
!= ERROR_SUCCESS
) {
1136 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
1137 m_dwLastError
= ERROR_SUCCESS
;
1141 wxLogSysError(m_dwLastError
, _("Can't enumerate subkeys of key '%s'"),
1148 strKeyName
= szKeyName
;
1152 // returns true if the value contains a number (else it's some string)
1153 bool wxRegKey::IsNumericValue(const wxString
& szValue
) const
1155 ValueType type
= GetValueType(szValue
);
1158 /* case Type_Dword_little_endian: == Type_Dword */
1159 case Type_Dword_big_endian
:
1167 // ----------------------------------------------------------------------------
1168 // exporting registry keys to file
1169 // ----------------------------------------------------------------------------
1173 // helper functions for writing ASCII strings (even in Unicode build)
1174 static inline bool WriteAsciiChar(wxOutputStream
& ostr
, char ch
)
1180 static inline bool WriteAsciiEOL(wxOutputStream
& ostr
)
1182 // as we open the file in text mode, it is enough to write LF without CR
1183 return WriteAsciiChar(ostr
, '\n');
1186 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const char *p
)
1188 return ostr
.Write(p
, strlen(p
)).IsOk();
1191 static inline bool WriteAsciiString(wxOutputStream
& ostr
, const wxString
& s
)
1194 wxCharBuffer
name(s
.mb_str());
1195 ostr
.Write(name
, strlen(name
));
1197 ostr
.Write(s
.mb_str(), s
.length());
1203 #endif // wxUSE_STREAMS
1205 bool wxRegKey::Export(const wxString
& filename
) const
1207 #if wxUSE_FFILE && wxUSE_STREAMS
1208 if ( wxFile::Exists(filename
) )
1210 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1215 wxFFileOutputStream
ostr(filename
, wxT("w"));
1217 return ostr
.Ok() && Export(ostr
);
1219 wxUnusedVar(filename
);
1225 bool wxRegKey::Export(wxOutputStream
& ostr
) const
1227 // write out the header
1228 if ( !WriteAsciiString(ostr
, "REGEDIT4\n\n") )
1231 return DoExport(ostr
);
1233 #endif // wxUSE_STREAMS
1237 FormatAsHex(const void *data
,
1239 wxRegKey::ValueType type
= wxRegKey::Type_Binary
)
1241 wxString
value(wxT("hex"));
1243 // binary values use just "hex:" prefix while the other ones must indicate
1245 if ( type
!= wxRegKey::Type_Binary
)
1246 value
<< wxT('(') << type
<< wxT(')');
1249 // write all the rest as comma-separated bytes
1250 value
.reserve(3*size
+ 10);
1251 const char * const p
= static_cast<const char *>(data
);
1252 for ( size_t n
= 0; n
< size
; n
++ )
1254 // TODO: line wrapping: although not required by regedit, this makes
1255 // the generated files easier to read and compare with the files
1256 // produced by regedit
1260 value
<< wxString::Format(wxT("%02x"), (unsigned char)p
[n
]);
1267 wxString
FormatAsHex(const wxString
& value
, wxRegKey::ValueType type
)
1269 return FormatAsHex(value
.c_str(), value
.length() + 1, type
);
1272 wxString
wxRegKey::FormatValue(const wxString
& name
) const
1275 const ValueType type
= GetValueType(name
);
1281 if ( !QueryValue(name
, value
) )
1284 // quotes and backslashes must be quoted, linefeeds are not
1285 // allowed in string values
1286 rhs
.reserve(value
.length() + 2);
1289 // there can be no NULs here
1290 bool useHex
= false;
1291 for ( wxString::const_iterator p
= value
.begin();
1292 p
!= value
.end() && !useHex
; ++p
)
1294 switch ( (*p
).GetValue() )
1297 // we can only represent this string in hex
1303 // escape special symbol
1313 rhs
= FormatAsHex(value
, Type_String
);
1320 /* case Type_Dword_little_endian: == Type_Dword */
1323 if ( !QueryValue(name
, &value
) )
1326 rhs
.Printf(wxT("dword:%08x"), (unsigned int)value
);
1330 case Type_Expand_String
:
1331 case Type_Multi_String
:
1334 if ( !QueryRawValue(name
, value
) )
1337 rhs
= FormatAsHex(value
, type
);
1344 if ( !QueryValue(name
, buf
) )
1347 rhs
= FormatAsHex(buf
.GetData(), buf
.GetDataLen());
1351 // no idea how those appear in REGEDIT4 files
1353 case Type_Dword_big_endian
:
1355 case Type_Resource_list
:
1356 case Type_Full_resource_descriptor
:
1357 case Type_Resource_requirements_list
:
1359 wxLogWarning(_("Can't export value of unsupported type %d."), type
);
1367 bool wxRegKey::DoExportValue(wxOutputStream
& ostr
, const wxString
& name
) const
1369 // first examine the value type: if it's unsupported, simply skip it
1370 // instead of aborting the entire export process because we failed to
1371 // export a single value
1372 wxString value
= FormatValue(name
);
1373 if ( value
.empty() )
1375 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1376 name
.c_str(), GetName().c_str());
1380 // we do have the text representation of the value, now write everything
1383 // special case: unnamed/default value is represented as just "@"
1386 if ( !WriteAsciiChar(ostr
, '@') )
1389 else // normal, named, value
1391 if ( !WriteAsciiChar(ostr
, '"') ||
1392 !WriteAsciiString(ostr
, name
) ||
1393 !WriteAsciiChar(ostr
, '"') )
1397 if ( !WriteAsciiChar(ostr
, '=') )
1400 return WriteAsciiString(ostr
, value
) && WriteAsciiEOL(ostr
);
1403 bool wxRegKey::DoExport(wxOutputStream
& ostr
) const
1405 // write out this key name
1406 if ( !WriteAsciiChar(ostr
, '[') )
1409 if ( !WriteAsciiString(ostr
, GetName(false /* no short prefix */)) )
1412 if ( !WriteAsciiChar(ostr
, ']') || !WriteAsciiEOL(ostr
) )
1415 // dump all our values
1418 wxRegKey
& self
= const_cast<wxRegKey
&>(*this);
1419 bool cont
= self
.GetFirstValue(name
, dummy
);
1422 if ( !DoExportValue(ostr
, name
) )
1425 cont
= GetNextValue(name
, dummy
);
1428 // always terminate values by blank line, even if there were no values
1429 if ( !WriteAsciiEOL(ostr
) )
1432 // recurse to subkeys
1433 cont
= self
.GetFirstKey(name
, dummy
);
1436 wxRegKey
subkey(*this, name
);
1437 if ( !subkey
.DoExport(ostr
) )
1440 cont
= GetNextKey(name
, dummy
);
1446 #endif // wxUSE_STREAMS
1448 // ============================================================================
1449 // implementation of global private functions
1450 // ============================================================================
1452 bool KeyExists(WXHKEY hRootKey
,
1453 const wxString
& szKey
,
1454 wxRegKey::WOW64ViewMode viewMode
)
1456 // don't close this key itself for the case of empty szKey!
1457 if ( szKey
.empty() )
1466 // we might not have enough rights for rw access
1467 GetMSWAccessFlags(wxRegKey::Read
, viewMode
),
1469 ) == ERROR_SUCCESS
)
1471 ::RegCloseKey(hkeyDummy
);
1479 long GetMSWViewFlags(wxRegKey::WOW64ViewMode viewMode
)
1481 long samWOW64ViewMode
= 0;
1485 case wxRegKey::WOW64ViewMode_32
:
1486 #ifdef __WIN64__ // the flag is only needed by 64 bit apps
1487 samWOW64ViewMode
= KEY_WOW64_32KEY
;
1491 case wxRegKey::WOW64ViewMode_64
:
1492 #ifndef __WIN64__ // the flag is only needed by 32 bit apps
1493 // 64 bit registry can only be accessed under 64 bit platforms
1494 if ( wxIsPlatform64Bit() )
1495 samWOW64ViewMode
= KEY_WOW64_64KEY
;
1500 wxFAIL_MSG("Unknown registry view.");
1503 case wxRegKey::WOW64ViewMode_Default
:
1504 // Use default registry view for the current application,
1505 // i.e. 32 bits for 32 bit ones and 64 bits for 64 bit apps
1509 return samWOW64ViewMode
;
1512 long GetMSWAccessFlags(wxRegKey::AccessMode mode
,
1513 wxRegKey::WOW64ViewMode viewMode
)
1515 long sam
= mode
== wxRegKey::Read
? KEY_READ
: KEY_ALL_ACCESS
;
1517 sam
|= GetMSWViewFlags(viewMode
);
1522 wxString
GetFullName(const wxRegKey
*pKey
, const wxString
& szValue
)
1524 wxString
str(pKey
->GetName());
1525 if ( !szValue
.empty() )
1526 str
<< wxT("\\") << szValue
;
1531 wxString
GetFullName(const wxRegKey
*pKey
)
1533 return pKey
->GetName();
1536 inline void RemoveTrailingSeparator(wxString
& str
)
1538 if ( !str
.empty() && str
.Last() == REG_SEPARATOR
)
1539 str
.Truncate(str
.Len() - 1);
1542 inline const wxChar
*RegValueStr(const wxString
& szValue
)
1544 return szValue
.empty() ? (const wxChar
*)NULL
: szValue
.t_str();
1547 #endif // wxUSE_REGKEY