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 ///////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
23 // for compilers that support precompilation, includes "wx.h".
24 #include "wx/wxprec.h"
30 // other wxWindows headers
31 #include "wx/string.h"
35 #include "wx/config.h" // for wxExpandEnvVars
40 #define WIN32_LEAN_AND_MEAN
46 #include <stdlib.h> // for _MAX_PATH
53 #define HKEY_DEFINED // already defined in windows.h
54 #include "wx/msw/registry.h"
56 // some registry functions don't like signed chars
57 typedef unsigned char *RegString
;
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // the standard key names, short names and handles all bundled together for
69 const char *szShortName
;
73 { HKEY_CLASSES_ROOT
, "HKEY_CLASSES_ROOT", "HKCR" },
75 { HKEY_CURRENT_USER
, "HKEY_CURRENT_USER", "HKCU" },
76 { HKEY_LOCAL_MACHINE
, "HKEY_LOCAL_MACHINE", "HKLM" },
77 { HKEY_USERS
, "HKEY_USERS", "HKU" }, // short name?
78 { HKEY_PERFORMANCE_DATA
, "HKEY_PERFORMANCE_DATA", "HKPD" },
80 { HKEY_CURRENT_CONFIG
, "HKEY_CURRENT_CONFIG", "HKCC" },
82 { HKEY_DYN_DATA
, "HKEY_DYN_DATA", "HKDD" }, // short name?
84 #endif //WINVER >= 4.0
88 // the registry name separator (perhaps one day MS will change it to '/' ;-)
89 #define REG_SEPARATOR '\\'
91 // useful for Windows programmers: makes somewhat more clear all these zeroes
92 // being passed to Windows APIs
93 #define RESERVED (NULL)
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
98 // @ const_cast<> is not yet supported by all compilers
99 #define CONST_CAST ((wxRegKey *)this)->
102 #define m_dwLastError CONST_CAST m_dwLastError
105 // ----------------------------------------------------------------------------
106 // non member functions
107 // ----------------------------------------------------------------------------
109 // removes the trailing backslash from the string if it has one
110 static inline void RemoveTrailingSeparator(wxString
& str
);
112 // returns TRUE if given registry key exists
113 static bool KeyExists(WXHKEY hRootKey
, const char *szKey
);
115 // combines value and key name (uses static buffer!)
116 static const char *GetFullName(const wxRegKey
*pKey
,
117 const char *szValue
= NULL
);
119 // ============================================================================
120 // implementation of wxRegKey class
121 // ============================================================================
123 // ----------------------------------------------------------------------------
124 // static functions and variables
125 // ----------------------------------------------------------------------------
127 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
129 // @@ should take a `StdKey key', but as it's often going to be used in loops
130 // it would require casts in user code.
131 const char *wxRegKey::GetStdKeyName(size_t key
)
133 // return empty string if key is invalid
134 wxCHECK_MSG( key
< nStdKeys
, "", "invalid key in wxRegKey::GetStdKeyName" );
136 return aStdKeys
[key
].szName
;
139 const char *wxRegKey::GetStdKeyShortName(size_t key
)
141 // return empty string if key is invalid
142 wxCHECK( key
< nStdKeys
, "" );
144 return aStdKeys
[key
].szShortName
;
147 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
149 wxString strRoot
= strKey
.Left(REG_SEPARATOR
);
153 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
154 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
155 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
156 hRootKey
= aStdKeys
[ui
].hkey
;
161 if ( ui
== nStdKeys
) {
162 wxFAIL_MSG("invalid key prefix in wxRegKey::ExtractKeyName.");
164 hRootKey
= HKEY_CLASSES_ROOT
;
167 strKey
= strKey
.After(REG_SEPARATOR
);
168 if ( !strKey
.IsEmpty() && strKey
.Last() == REG_SEPARATOR
)
169 strKey
.Truncate(strKey
.Len() - 1);
172 return (wxRegKey::StdKey
)(int)hRootKey
;
175 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(WXHKEY hkey
)
177 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
178 if ( (int) aStdKeys
[ui
].hkey
== (int) hkey
)
182 wxFAIL_MSG("non root hkey passed to wxRegKey::GetStdKeyFromHkey.");
187 // ----------------------------------------------------------------------------
189 // ----------------------------------------------------------------------------
194 m_hRootKey
= (WXHKEY
) aStdKeys
[HKCR
].hkey
;
198 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
200 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
205 // parent is a predefined (and preopened) key
206 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
208 RemoveTrailingSeparator(m_strKey
);
209 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
214 // parent is a normal regkey
215 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
216 : m_strKey(keyParent
.m_strKey
)
218 // combine our name with parent's to get the full name
219 if ( !m_strKey
.IsEmpty() &&
220 (strKey
.IsEmpty() || strKey
[0] != REG_SEPARATOR
) ) {
221 m_strKey
+= REG_SEPARATOR
;
225 RemoveTrailingSeparator(m_strKey
);
227 m_hRootKey
= keyParent
.m_hRootKey
;
232 // dtor closes the key releasing system resource
233 wxRegKey::~wxRegKey()
238 // ----------------------------------------------------------------------------
239 // change the key name/hkey
240 // ----------------------------------------------------------------------------
242 // set the full key name
243 void wxRegKey::SetName(const wxString
& strKey
)
248 m_hRootKey
= (WXHKEY
) aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
251 // the name is relative to the parent key
252 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
257 RemoveTrailingSeparator(m_strKey
);
258 m_hRootKey
= (WXHKEY
) aStdKeys
[keyParent
].hkey
;
261 // the name is relative to the parent key
262 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
266 // combine our name with parent's to get the full name
267 m_strKey
= keyParent
.m_strKey
;
268 if ( !strKey
.IsEmpty() && strKey
[0] != REG_SEPARATOR
)
269 m_strKey
+= REG_SEPARATOR
;
272 RemoveTrailingSeparator(m_strKey
);
274 m_hRootKey
= keyParent
.m_hRootKey
;
277 // hKey should be opened and will be closed in wxRegKey dtor
278 void wxRegKey::SetHkey(WXHKEY hKey
)
285 // ----------------------------------------------------------------------------
286 // info about the key
287 // ----------------------------------------------------------------------------
289 // returns TRUE if the key exists
290 bool wxRegKey::Exists() const
292 // opened key has to exist, try to open it if not done yet
293 return IsOpened() ? TRUE
: KeyExists(m_hRootKey
, m_strKey
);
296 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
297 wxString
wxRegKey::GetName(bool bShortPrefix
) const
299 StdKey key
= GetStdKeyFromHkey((StdKey
) m_hRootKey
);
300 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
301 : aStdKeys
[key
].szName
;
302 if ( !m_strKey
.IsEmpty() )
303 str
<< "\\" << m_strKey
;
309 bool wxRegKey::GetKeyInfo(size_t* pnSubKeys
,
312 size_t* pnMaxValueLen
) const
314 bool wxRegKey::GetKeyInfo(ulong
*pnSubKeys
,
317 ulong
*pnMaxValueLen
) const
321 m_dwLastError
= ::RegQueryInfoKey
325 NULL
, // (ptr to) size of class name buffer
327 pnSubKeys
, // [out] number of subkeys
328 pnMaxKeyLen
, // [out] max length of a subkey name
329 NULL
, // longest subkey class name
330 pnValues
, // [out] number of values
331 pnMaxValueLen
, // [out] max length of a value name
332 NULL
, // longest value data
333 NULL
, // security descriptor
334 NULL
// time of last modification
337 if ( m_dwLastError
!= ERROR_SUCCESS
) {
338 wxLogSysError(m_dwLastError
, _("can't get info about registry key '%s'"),
345 wxFAIL_MSG("GetKeyInfo() not implemented");
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
355 // opens key (it's not an error to call Open() on an already opened key)
356 bool wxRegKey::Open()
362 m_dwLastError
= RegOpenKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
363 if ( m_dwLastError
!= ERROR_SUCCESS
) {
364 wxLogSysError(m_dwLastError
, _("can't open registry key '%s'"),
370 m_hKey
= (WXHKEY
) tmpKey
;
375 // creates key, failing if it exists and !bOkIfExists
376 bool wxRegKey::Create(bool bOkIfExists
)
378 // check for existence only if asked (i.e. order is important!)
379 if ( !bOkIfExists
&& Exists() ) {
387 m_dwLastError
= RegCreateKey((HKEY
) m_hRootKey
, m_strKey
, &tmpKey
);
388 if ( m_dwLastError
!= ERROR_SUCCESS
) {
389 wxLogSysError(m_dwLastError
, _("can't create registry key '%s'"),
395 m_hKey
= (WXHKEY
) tmpKey
;
400 // close the key, it's not an error to call it when not opened
401 bool wxRegKey::Close()
404 m_dwLastError
= RegCloseKey((HKEY
) m_hKey
);
405 if ( m_dwLastError
!= ERROR_SUCCESS
) {
406 wxLogSysError(m_dwLastError
, _("can't close registry key '%s'"),
420 // ----------------------------------------------------------------------------
421 // delete keys/values
422 // ----------------------------------------------------------------------------
423 bool wxRegKey::DeleteSelf()
428 // it already doesn't exist - ok!
433 // we can't delete keys while enumerating because it confuses GetNextKey, so
434 // we first save the key names and then delete them all
435 wxArrayString astrSubkeys
;
439 bool bCont
= GetFirstKey(strKey
, lIndex
);
441 astrSubkeys
.Add(strKey
);
443 bCont
= GetNextKey(strKey
, lIndex
);
446 size_t nKeyCount
= astrSubkeys
.Count();
447 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
448 wxRegKey
key(*this, astrSubkeys
[nKey
]);
449 if ( !key
.DeleteSelf() )
453 // now delete this key itself
456 m_dwLastError
= RegDeleteKey((HKEY
) m_hRootKey
, m_strKey
);
457 if ( m_dwLastError
!= ERROR_SUCCESS
) {
458 wxLogSysError(m_dwLastError
, _("can't delete key '%s'"),
466 bool wxRegKey::DeleteKey(const char *szKey
)
471 wxRegKey
key(*this, szKey
);
472 return key
.DeleteSelf();
475 bool wxRegKey::DeleteValue(const char *szValue
)
481 m_dwLastError
= RegDeleteValue((HKEY
) m_hKey
, szValue
);
482 if ( m_dwLastError
!= ERROR_SUCCESS
) {
483 wxLogSysError(m_dwLastError
, _("can't delete value '%s' from key '%s'"),
484 szValue
, GetName().c_str());
488 // named registry values don't exist in Win16 world
489 wxASSERT( IsEmpty(szValue
) );
491 // just set the (default and unique) value of the key to ""
492 m_dwLastError
= RegSetValue((HKEY
) m_hKey
, NULL
, REG_SZ
, "", RESERVED
);
493 if ( m_dwLastError
!= ERROR_SUCCESS
) {
494 wxLogSysError(m_dwLastError
, _("can't delete value of key '%s'"),
503 // ----------------------------------------------------------------------------
504 // access to values and subkeys
505 // ----------------------------------------------------------------------------
507 // return TRUE if value exists
508 bool wxRegKey::HasValue(const char *szValue
) const
510 // this function should be silent, so suppress possible messages from Open()
514 if ( CONST_CAST
Open() ) {
515 return RegQueryValueEx((HKEY
) m_hKey
, szValue
, RESERVED
,
516 NULL
, NULL
, NULL
) == ERROR_SUCCESS
;
521 // only unnamed value exists
522 return IsEmpty(szValue
);
526 // returns TRUE if this key has any subkeys
527 bool wxRegKey::HasSubkeys() const
529 // just call GetFirstKey with dummy parameters
532 return CONST_CAST
GetFirstKey(str
, l
);
535 // returns TRUE if given subkey exists
536 bool wxRegKey::HasSubKey(const char *szKey
) const
538 if ( CONST_CAST
Open() )
539 return KeyExists(m_hKey
, szKey
);
544 wxRegKey::ValueType
wxRegKey::GetValueType(const char *szValue
)
551 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, szValue
, RESERVED
,
552 &dwType
, NULL
, NULL
);
553 if ( m_dwLastError
!= ERROR_SUCCESS
) {
554 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
559 return (ValueType
)dwType
;
561 return IsEmpty(szValue
) ? Type_String
: Type_None
;
566 bool wxRegKey::SetValue(const char *szValue
, long lValue
)
568 if ( CONST_CAST
Open() ) {
569 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, RESERVED
, REG_DWORD
,
570 (RegString
)&lValue
, sizeof(lValue
));
571 if ( m_dwLastError
== ERROR_SUCCESS
)
575 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
576 GetFullName(this, szValue
));
580 bool wxRegKey::QueryValue(const char *szValue
, long *plValue
) const
582 if ( CONST_CAST
Open() ) {
583 DWORD dwType
, dwSize
= sizeof(DWORD
);
584 RegString pBuf
= (RegString
)plValue
;
585 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, szValue
, RESERVED
,
586 &dwType
, pBuf
, &dwSize
);
587 if ( m_dwLastError
!= ERROR_SUCCESS
) {
588 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
593 // check that we read the value of right type
594 wxASSERT_MSG( dwType
== REG_DWORD
,
595 "Type mismatch in wxRegKey::QueryValue()." );
606 bool wxRegKey::QueryValue(const char *szValue
, wxString
& strValue
) const
608 if ( CONST_CAST
Open() ) {
610 // first get the type and size of the data
611 DWORD dwType
, dwSize
;
612 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, szValue
, RESERVED
,
613 &dwType
, NULL
, &dwSize
);
614 if ( m_dwLastError
== ERROR_SUCCESS
) {
615 RegString pBuf
= (RegString
)strValue
.GetWriteBuf(dwSize
);
616 m_dwLastError
= RegQueryValueEx((HKEY
) m_hKey
, szValue
, RESERVED
,
617 &dwType
, pBuf
, &dwSize
);
618 strValue
.UngetWriteBuf();
619 if ( m_dwLastError
== ERROR_SUCCESS
) {
620 // check that it was the right type
621 wxASSERT_MSG( dwType
== REG_SZ
,
622 "Type mismatch in wxRegKey::QueryValue()." );
628 // named registry values don't exist in Win16
629 wxASSERT( IsEmpty(szValue
) );
631 m_dwLastError
= RegQueryValue((HKEY
) m_hKey
, 0, strValue
.GetWriteBuf(256), &l
);
632 strValue
.UngetWriteBuf();
633 if ( m_dwLastError
== ERROR_SUCCESS
)
638 wxLogSysError(m_dwLastError
, _("can't read value of '%s'"),
639 GetFullName(this, szValue
));
643 bool wxRegKey::SetValue(const char *szValue
, const wxString
& strValue
)
645 if ( CONST_CAST
Open() ) {
647 m_dwLastError
= RegSetValueEx((HKEY
) m_hKey
, szValue
, RESERVED
, REG_SZ
,
648 (RegString
)strValue
.c_str(),
650 if ( m_dwLastError
== ERROR_SUCCESS
)
653 // named registry values don't exist in Win16
654 wxASSERT( IsEmpty(szValue
) );
656 m_dwLastError
= RegSetValue((HKEY
) m_hKey
, NULL
, REG_SZ
, strValue
, NULL
);
657 if ( m_dwLastError
== ERROR_SUCCESS
)
662 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
663 GetFullName(this, szValue
));
667 wxRegKey::operator wxString() const
670 QueryValue(NULL
, str
);
674 // ----------------------------------------------------------------------------
676 // NB: all these functions require an index variable which allows to have
677 // several concurrently running indexations on the same key
678 // ----------------------------------------------------------------------------
680 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
686 return GetNextValue(strValueName
, lIndex
);
689 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
691 wxASSERT( IsOpened() );
693 // are we already at the end of enumeration?
698 char szValueName
[1024]; // @@ use RegQueryInfoKey...
699 DWORD dwValueLen
= WXSIZEOF(szValueName
);
702 m_dwLastError
= RegEnumValue((HKEY
) m_hKey
, lIndex
,
703 szValueName
, &dwValueLen
,
706 NULL
, // [out] buffer for value
707 NULL
); // [i/o] it's length
709 if ( m_dwLastError
!= ERROR_SUCCESS
) {
710 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
711 m_dwLastError
= ERROR_SUCCESS
;
715 wxLogSysError(m_dwLastError
, _("can't enumerate values of key '%s'"),
722 strValueName
= szValueName
;
724 // only one unnamed value
725 wxASSERT( lIndex
== 0 );
728 strValueName
.Empty();
734 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
740 return GetNextKey(strKeyName
, lIndex
);
743 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
745 wxASSERT( IsOpened() );
747 // are we already at the end of enumeration?
751 char szKeyName
[_MAX_PATH
+ 1];
752 m_dwLastError
= RegEnumKey((HKEY
) m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
754 if ( m_dwLastError
!= ERROR_SUCCESS
) {
755 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
756 m_dwLastError
= ERROR_SUCCESS
;
760 wxLogSysError(m_dwLastError
, _("can't enumerate subkeys of key '%s'"),
767 strKeyName
= szKeyName
;
771 // ============================================================================
772 // implementation of global private functions
773 // ============================================================================
774 bool KeyExists(WXHKEY hRootKey
, const char *szKey
)
777 if ( RegOpenKey( (HKEY
) hRootKey
, szKey
, &hkeyDummy
) == ERROR_SUCCESS
) {
778 RegCloseKey(hkeyDummy
);
785 const char *GetFullName(const wxRegKey
*pKey
, const char *szValue
)
787 static wxString s_str
;
788 s_str
= pKey
->GetName();
789 if ( !IsEmpty(szValue
) )
790 s_str
<< "\\" << szValue
;
792 return s_str
.c_str();
795 void RemoveTrailingSeparator(wxString
& str
)
797 if ( !str
.IsEmpty() && str
.Last() == REG_SEPARATOR
)
798 str
.Truncate(str
.Len() - 1);
801 // ============================================================================
802 // global public functions
803 // ============================================================================
805 bool GetExtensionFromMimeType(wxString
*pExt
, const wxString
& strMimeType
)
807 // @@@ VZ: I don't know of any official documentation which mentions this
808 // location, but as a matter of fact IE uses it, so why not we?
809 static const char *szMimeDbase
= "MIME\\Database\\Content Type\\";
811 wxString strKey
= szMimeDbase
;
812 strKey
<< strMimeType
;
814 // suppress possible error messages
816 wxRegKey
key(wxRegKey::HKCR
, strKey
);
818 if ( key
.QueryValue("Extension", *pExt
) )
822 // no such MIME type or no extension for it
826 bool GetMimeTypeFromExtension(wxString
*pMimeType
, const wxString
& strExt
)
828 wxCHECK( !strExt
.IsEmpty(), FALSE
);
830 // add the leading point if necessary
832 if ( strExt
[0] != '.' ) {
837 // suppress possible error messages
839 wxRegKey
key(wxRegKey::HKCR
, str
);
841 if ( key
.QueryValue("Content Type", *pMimeType
) )
845 // no such extension or no content-type
849 bool GetFileTypeFromExtension(wxString
*pFileType
, const wxString
& strExt
)
851 wxCHECK( !strExt
.IsEmpty(), FALSE
);
853 // add the leading point if necessary
855 if ( strExt
[0] != '.' ) {
860 // suppress possible error messages
862 wxRegKey
key(wxRegKey::HKCR
, str
);
864 if ( key
.QueryValue("", *pFileType
) ) // it's the default value of the key
868 // no such extension or no value
872 bool GetFileTypeIcon(wxIcon
*pIcon
, const wxString
& strFileType
)
874 wxCHECK( !strFileType
.IsEmpty(), FALSE
);
877 strIconKey
<< strFileType
<< REG_SEPARATOR
<< "DefaultIcon";
879 // suppress possible error messages
881 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
885 if ( key
.QueryValue("", strIcon
) ) { // it's the default value of the key
886 // the format is the following: <full path to file>, <icon index>
887 // NB: icon index may be negative as well as positive and the full path
888 // may contain the environment variables inside '%'
889 wxString strFullPath
= strIcon
.Before(','),
890 strIndex
= strIcon
.After(',');
892 // unless I misunderstand the format (may be index may be ommited, I
894 wxASSERT( !(strFullPath
.IsEmpty() || strIndex
.IsEmpty()) );
896 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
897 int nIndex
= atoi(strIndex
);
899 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
900 switch ( (int)hIcon
) {
901 case 0: // means no icons were found
902 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
903 wxLogDebug("incorrect registry entry '%s': no such icon.",
908 pIcon
->SetHICON((WXHICON
)hIcon
);
914 // no such file type or no value or incorrect icon entry
918 bool GetFileTypeDescription(wxString
*pDesc
, const wxString
& strFileType
)
920 wxCHECK( !strFileType
.IsEmpty(), FALSE
);
922 // suppress possible error messages
924 wxRegKey
key(wxRegKey::HKCR
, strFileType
);
927 if ( key
.QueryValue("", *pDesc
) ) // it's the default value of the key
931 // no such file type or no value