1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: 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 license
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 ///////////////////////////////////////////////////////////////////////////////
16 #pragma implementation "registry.h"
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 // other wxWindows headers
27 #include "wx/string.h"
30 #include "wx/config.h" // for wxExpandEnvVars
37 #define WIN32_LEAN_AND_MEAN
43 #include <stdlib.h> // for _MAX_PATH
50 #define HKEY_DEFINED // already defined in windows.h
51 #include "wx/msw/registry.h"
53 // some registry functions don't like signed chars
54 typedef unsigned char *RegString
;
56 // ----------------------------------------------------------------------------
58 // ----------------------------------------------------------------------------
60 // the standard key names, short names and handles all bundled together for
66 const char *szShortName
;
70 { HKEY_CLASSES_ROOT
, "HKEY_CLASSES_ROOT", "HKCR" },
72 { HKEY_CURRENT_USER
, "HKEY_CURRENT_USER", "HKCU" },
73 { HKEY_LOCAL_MACHINE
, "HKEY_LOCAL_MACHINE", "HKLM" },
74 { HKEY_USERS
, "HKEY_USERS", "HKU" }, // short name?
75 { HKEY_PERFORMANCE_DATA
, "HKEY_PERFORMANCE_DATA", "HKPD" },
77 { HKEY_CURRENT_CONFIG
, "HKEY_CURRENT_CONFIG", "HKCC" },
79 { HKEY_DYN_DATA
, "HKEY_DYN_DATA", "HKDD" }, // short name?
81 #endif //WINVER >= 4.0
85 // the registry name separator (perhaps one day MS will change it to '/' ;-)
86 #define REG_SEPARATOR '\\'
88 // useful for Windows programmers: makes somewhat more clear all these zeroes
89 // being passed to Windows APIs
90 #define RESERVED (NULL)
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
95 // @ const_cast<> is not yet supported by all compilers
96 #define CONST_CAST ((wxRegKey *)this)->
99 #define m_dwLastError CONST_CAST m_dwLastError
102 // ----------------------------------------------------------------------------
103 // non member functions
104 // ----------------------------------------------------------------------------
106 // removes the trailing backslash from the string if it has one
107 static inline void RemoveTrailingSeparator(wxString
& str
);
109 // returns TRUE if given registry key exists
110 static bool KeyExists(WXHKEY hRootKey
, const char *szKey
);
112 // combines value and key name (uses static buffer!)
113 static const char *GetFullName(const wxRegKey
*pKey
,
114 const char *szValue
= NULL
);
116 // ============================================================================
117 // implementation of wxRegKey class
118 // ============================================================================
120 // ----------------------------------------------------------------------------
121 // static functions and variables
122 // ----------------------------------------------------------------------------
124 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
126 // @@ should take a `StdKey key', but as it's often going to be used in loops
127 // it would require casts in user code.
128 const char *wxRegKey::GetStdKeyName(size_t key
)
130 // return empty string if key is invalid
131 wxCHECK_MSG( key
< nStdKeys
, "", "invalid key in wxRegKey::GetStdKeyName" );
133 return aStdKeys
[key
].szName
;
136 const char *wxRegKey::GetStdKeyShortName(size_t key
)
138 // return empty string if key is invalid
139 wxCHECK( key
< nStdKeys
, "" );
141 return aStdKeys
[key
].szShortName
;
144 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
146 wxString strRoot
= strKey
.Left(REG_SEPARATOR
);
150 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
151 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
152 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
153 hRootKey
= aStdKeys
[ui
].hkey
;
158 if ( ui
== nStdKeys
) {
159 wxFAIL_MSG("invalid key prefix in wxRegKey::ExtractKeyName.");
161 hRootKey
= HKEY_CLASSES_ROOT
;
164 strKey
= strKey
.After(REG_SEPARATOR
);
165 if ( !strKey
.IsEmpty() && strKey
.Last() == REG_SEPARATOR
)
166 strKey
.Truncate(strKey
.Len() - 1);
169 return (wxRegKey::StdKey
)(int)hRootKey
;
172 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
174 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
175 if ( (int) aStdKeys
[ui
].hkey
== (int) hkey
)
179 wxFAIL_MSG("non root hkey passed to wxRegKey::GetStdKeyFromHkey.");
184 // ----------------------------------------------------------------------------
186 // ----------------------------------------------------------------------------
191 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
195 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
197 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
198 m_hKey
= (WXHKEY
) NULL
;
202 // parent is a predefined (and preopened) key
203 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
205 RemoveTrailingSeparator(m_strKey
);
206 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
207 m_hKey
= (WXHKEY
) NULL
;
211 // parent is a normal regkey
212 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
213 : m_strKey(keyParent
.m_strKey
)
215 // combine our name with parent's to get the full name
216 if ( !m_strKey
.IsEmpty() &&
217 (strKey
.IsEmpty() || strKey
[0] != REG_SEPARATOR
) ) {
218 m_strKey
+= REG_SEPARATOR
;
222 RemoveTrailingSeparator(m_strKey
);
224 m_hRootKey
= keyParent
.m_hRootKey
;
225 m_hKey
= (WXHKEY
) NULL
;
229 // dtor closes the key releasing system resource
230 wxRegKey::~wxRegKey()
235 // ----------------------------------------------------------------------------
236 // change the key name/hkey
237 // ----------------------------------------------------------------------------
239 // set the full key name
240 void wxRegKey::SetName(const wxString
& strKey
)
245 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
248 // the name is relative to the parent key
249 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
254 RemoveTrailingSeparator(m_strKey
);
255 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
258 // the name is relative to the parent key
259 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
263 // combine our name with parent's to get the full name
264 m_strKey
= keyParent
.m_strKey
;
265 if ( !strKey
.IsEmpty() && strKey
[0] != REG_SEPARATOR
)
266 m_strKey
+= REG_SEPARATOR
;
269 RemoveTrailingSeparator(m_strKey
);
271 m_hRootKey
= keyParent
.m_hRootKey
;
274 // hKey should be opened and will be closed in wxRegKey dtor
275 void wxRegKey::SetHkey(WXHKEY hKey
)
282 // ----------------------------------------------------------------------------
283 // info about the key
284 // ----------------------------------------------------------------------------
286 // returns TRUE if the key exists
287 bool wxRegKey::Exists() const
289 // opened key has to exist, try to open it if not done yet
290 return IsOpened() ? TRUE
: KeyExists(m_hRootKey
, m_strKey
);
293 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
294 wxString
wxRegKey::GetName(bool bShortPrefix
) const
296 StdKey key
= GetStdKeyFromHkey((StdKey
) m_hRootKey
);
297 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
298 : aStdKeys
[key
].szName
;
299 if ( !m_strKey
.IsEmpty() )
300 str
<< "\\" << m_strKey
;
306 bool wxRegKey::GetKeyInfo(size_t* pnSubKeys
,
309 size_t* pnMaxValueLen
) const
311 bool wxRegKey::GetKeyInfo(ulong
*pnSubKeys
,
314 ulong
*pnMaxValueLen
) const
317 #if defined(__WIN32__) && !defined(__TWIN32__)
318 m_dwLastError
= ::RegQueryInfoKey
322 NULL
, // (ptr to) size of class name buffer
324 pnSubKeys
, // [out] number of subkeys
325 pnMaxKeyLen
, // [out] max length of a subkey name
326 NULL
, // longest subkey class name
327 pnValues
, // [out] number of values
328 pnMaxValueLen
, // [out] max length of a value name
329 NULL
, // longest value data
330 NULL
, // security descriptor
331 NULL
// time of last modification
334 if ( m_dwLastError
!= ERROR_SUCCESS
) {
335 wxLogSysError(m_dwLastError
, _("can't get info about registry key '%s'"),
342 wxFAIL_MSG("GetKeyInfo() not implemented");
348 // ----------------------------------------------------------------------------
350 // ----------------------------------------------------------------------------
352 // opens key (it's not an error to call Open() on an already opened key)
353 bool wxRegKey::Open()
359 m_dwLastError
= RegOpenKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
360 if ( m_dwLastError
!= ERROR_SUCCESS
) {
361 wxLogSysError(m_dwLastError
, _("can't open registry key '%s'"),
367 m_hKey
= (WXHKEY
) tmpKey
;
372 // creates key, failing if it exists and !bOkIfExists
373 bool wxRegKey::Create(bool bOkIfExists
)
375 // check for existence only if asked (i.e. order is important!)
376 if ( !bOkIfExists
&& Exists() ) {
384 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
385 if ( m_dwLastError
!= ERROR_SUCCESS
) {
386 wxLogSysError(m_dwLastError
, _("can't create registry key '%s'"),
392 m_hKey
= (WXHKEY
) tmpKey
;
397 // close the key, it's not an error to call it when not opened
398 bool wxRegKey::Close()
401 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
402 if ( m_dwLastError
!= ERROR_SUCCESS
) {
403 wxLogSysError(m_dwLastError
, _("can't close registry key '%s'"),
417 // ----------------------------------------------------------------------------
418 // delete keys/values
419 // ----------------------------------------------------------------------------
420 bool wxRegKey::DeleteSelf()
425 // it already doesn't exist - ok!
430 // prevent a buggy program from erasing one of the root registry keys or an
431 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
432 // key except HKCR (HKCR has some "deleteable" subkeys)
433 if ( m_strKey
.IsEmpty() || (m_hRootKey
!= HKCR
&&
434 m_strKey
.Find(REG_SEPARATOR
) == wxNOT_FOUND
) ) {
435 wxLogError(_("Registry key '%s' is needed for normal system operation,\n"
436 "deleting it will leave your system in unusable state:\n"
437 "operation aborted."), GetFullName(this));
442 // we can't delete keys while enumerating because it confuses GetNextKey, so
443 // we first save the key names and then delete them all
444 wxArrayString astrSubkeys
;
448 bool bCont
= GetFirstKey(strKey
, lIndex
);
450 astrSubkeys
.Add(strKey
);
452 bCont
= GetNextKey(strKey
, lIndex
);
455 size_t nKeyCount
= astrSubkeys
.Count();
456 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
457 wxRegKey
key(*this, astrSubkeys
[nKey
]);
458 if ( !key
.DeleteSelf() )
462 // now delete this key itself
465 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
466 if ( m_dwLastError
!= ERROR_SUCCESS
) {
467 wxLogSysError(m_dwLastError
, _("can't delete key '%s'"),
475 bool wxRegKey::DeleteKey(const char *szKey
)
480 wxRegKey
key(*this, szKey
);
481 return key
.DeleteSelf();
484 bool wxRegKey::DeleteValue(const char *szValue
)
489 #if defined(__WIN32__) && !defined(__TWIN32__)
490 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, (char*) (const char*) szValue
);
491 if ( m_dwLastError
!= ERROR_SUCCESS
) {
492 wxLogSysError(m_dwLastError
, _("can't delete value '%s' from key '%s'"),
493 szValue
, GetName().c_str());
497 // named registry values don't exist in Win16 world
498 wxASSERT( IsEmpty(szValue
) );
500 // just set the (default and unique) value of the key to ""
501 m_dwLastError
= RegSetValue((HKEY
) m_hKey
, NULL
, REG_SZ
, "", RESERVED
);
502 if ( m_dwLastError
!= ERROR_SUCCESS
) {
503 wxLogSysError(m_dwLastError
, _("can't delete value of key '%s'"),
512 // ----------------------------------------------------------------------------
513 // access to values and subkeys
514 // ----------------------------------------------------------------------------
516 // return TRUE if value exists
517 bool wxRegKey::HasValue(const char *szValue
) const
519 // this function should be silent, so suppress possible messages from Open()
523 if ( CONST_CAST
Open() ) {
524 return RegQueryValueEx((HKEY
) m_hKey
, (char*) (const char*) szValue
, RESERVED
,
525 NULL
, NULL
, NULL
) == ERROR_SUCCESS
;
530 // only unnamed value exists
531 return IsEmpty(szValue
);
535 // returns TRUE if this key has any subkeys
536 bool wxRegKey::HasSubkeys() const
538 // suppress possible messages from GetFirstKey()
541 // just call GetFirstKey with dummy parameters
544 return CONST_CAST
GetFirstKey(str
, l
);
547 // returns TRUE if given subkey exists
548 bool wxRegKey::HasSubKey(const char *szKey
) const
550 // this function should be silent, so suppress possible messages from Open()
553 if ( CONST_CAST
Open() )
554 return KeyExists(m_hKey
, szKey
);
559 wxRegKey::ValueType
wxRegKey::GetValueType(const char *szValue
) const
562 if ( ! CONST_CAST
Open() )
566 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, (char*) (const char*) szValue
, RESERVED
,
567 &dwType
, NULL
, NULL
);
568 if ( m_dwLastError
!= ERROR_SUCCESS
) {
569 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
574 return (ValueType
)dwType
;
576 return IsEmpty(szValue
) ? Type_String
: Type_None
;
581 bool wxRegKey::SetValue(const char *szValue
, long lValue
)
584 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
587 if ( CONST_CAST
Open() ) {
588 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_DWORD
,
589 (RegString
)&lValue
, sizeof(lValue
));
590 if ( m_dwLastError
== ERROR_SUCCESS
)
594 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
595 GetFullName(this, szValue
));
600 bool wxRegKey::QueryValue(const char *szValue
, long *plValue
) const
602 if ( CONST_CAST
Open() ) {
603 DWORD dwType
, dwSize
= sizeof(DWORD
);
604 RegString pBuf
= (RegString
)plValue
;
605 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, (char*) (const char*) szValue
, RESERVED
,
606 &dwType
, pBuf
, &dwSize
);
607 if ( m_dwLastError
!= ERROR_SUCCESS
) {
608 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
613 // check that we read the value of right type
614 wxASSERT_MSG( dwType
== REG_DWORD
,
615 "Type mismatch in wxRegKey::QueryValue()." );
626 bool wxRegKey::QueryValue(const char *szValue
, wxString
& strValue
) const
628 if ( CONST_CAST
Open() ) {
630 // first get the type and size of the data
631 DWORD dwType
, dwSize
;
632 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, (char*) (const char*) szValue
, RESERVED
,
633 &dwType
, NULL
, &dwSize
);
634 if ( m_dwLastError
== ERROR_SUCCESS
) {
635 RegString pBuf
= (RegString
)strValue
.GetWriteBuf(dwSize
);
636 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, (char*) (const char*) szValue
, RESERVED
,
637 &dwType
, pBuf
, &dwSize
);
638 strValue
.UngetWriteBuf();
639 if ( m_dwLastError
== ERROR_SUCCESS
) {
640 // check that it was the right type
641 wxASSERT_MSG( dwType
== REG_SZ
,
642 "Type mismatch in wxRegKey::QueryValue()." );
648 // named registry values don't exist in Win16
649 wxASSERT( IsEmpty(szValue
) );
651 m_dwLastError
= RegQueryValue((HKEY
) m_hKey
, 0, strValue
.GetWriteBuf(256), &l
);
652 strValue
.UngetWriteBuf();
653 if ( m_dwLastError
== ERROR_SUCCESS
)
658 wxLogSysError(m_dwLastError
, _("can't read value of '%s'"),
659 GetFullName(this, szValue
));
663 bool wxRegKey::SetValue(const char *szValue
, const wxString
& strValue
)
665 if ( CONST_CAST
Open() ) {
666 #if defined( __WIN32__) && !defined(__TWIN32__)
667 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, (DWORD
) RESERVED
, REG_SZ
,
668 (RegString
)strValue
.c_str(),
670 if ( m_dwLastError
== ERROR_SUCCESS
)
673 // named registry values don't exist in Win16
674 wxASSERT( IsEmpty(szValue
) );
676 m_dwLastError
= RegSetValue((HKEY
) m_hKey
, NULL
, REG_SZ
, strValue
, NULL
);
677 if ( m_dwLastError
== ERROR_SUCCESS
)
682 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
683 GetFullName(this, szValue
));
687 wxRegKey::operator wxString() const
690 QueryValue(NULL
, str
);
694 // ----------------------------------------------------------------------------
696 // NB: all these functions require an index variable which allows to have
697 // several concurrently running indexations on the same key
698 // ----------------------------------------------------------------------------
700 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
706 return GetNextValue(strValueName
, lIndex
);
709 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
711 wxASSERT( IsOpened() );
713 // are we already at the end of enumeration?
717 #if defined( __WIN32__) && !defined(__TWIN32__)
718 char szValueName
[1024]; // @@ use RegQueryInfoKey...
719 DWORD dwValueLen
= WXSIZEOF(szValueName
);
722 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
,
723 szValueName
, &dwValueLen
,
726 NULL
, // [out] buffer for value
727 NULL
); // [i/o] it's length
729 if ( m_dwLastError
!= ERROR_SUCCESS
) {
730 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
731 m_dwLastError
= ERROR_SUCCESS
;
735 wxLogSysError(m_dwLastError
, _("can't enumerate values of key '%s'"),
742 strValueName
= szValueName
;
744 // only one unnamed value
745 wxASSERT( lIndex
== 0 );
748 strValueName
.Empty();
754 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
760 return GetNextKey(strKeyName
, lIndex
);
763 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
765 wxASSERT( IsOpened() );
767 // are we already at the end of enumeration?
771 char szKeyName
[_MAX_PATH
+ 1];
772 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
774 if ( m_dwLastError
!= ERROR_SUCCESS
) {
775 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
776 m_dwLastError
= ERROR_SUCCESS
;
780 wxLogSysError(m_dwLastError
, _("can't enumerate subkeys of key '%s'"),
787 strKeyName
= szKeyName
;
791 // ============================================================================
792 // implementation of global private functions
793 // ============================================================================
794 bool KeyExists(WXHKEY hRootKey
, const char *szKey
)
797 if ( RegOpenKey( (HKEY
) hRootKey
, szKey
, &hkeyDummy
) == ERROR_SUCCESS
) {
798 RegCloseKey(hkeyDummy
);
805 const char *GetFullName(const wxRegKey
*pKey
, const char *szValue
)
807 static wxString s_str
;
808 s_str
= pKey
->GetName();
809 if ( !IsEmpty(szValue
) )
810 s_str
<< "\\" << szValue
;
812 return s_str
.c_str();
815 void RemoveTrailingSeparator(wxString
& str
)
817 if ( !str
.IsEmpty() && str
.Last() == REG_SEPARATOR
)
818 str
.Truncate(str
.Len() - 1);