==================================声明==================================
本文原创,转载请显要的注明作者和出处,并保证文章的完整性(包括本声明)。
本文不定期修改完善,为保证内容正确,建议移步原文处阅读。
本文链接:http://www.cnblogs.com/wlsandwho/p/4210481.html
=======================================================================
最近做的东西要用到串口,初始化界面的时候要列出一个可用的串口列表。
=======================================================================
最初我打算枚举设备,感觉好麻烦的样子。
网上好多都在说,i从1到N,挨个打开关闭一遍……这特么在逗我?
=======================================================================
思索了一下(虚词),打算从注册表入手,毕竟所有的(可使用)设备都是要在注册表里注册的。
定下了方向,就准备资料了。
=======================================================================
1 串口在注册表里的位置:HKEY_LOCAL_MACHINEHARDWAREDEVICEMAPSERIALCOMM。
2 所使用的主要函数:RegEnumValue,这个可以参见MSDN(http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k%28%22WINREG%2fREGENUMVALUE%22%29;k%28REGENUMVALUE%29;k%28DevLang-%22C%2B%2B%22%29;k%28TargetOS-WINDOWS%29&rd=true),刚好这个函数给出了示例代码(http://msdn.microsoft.com/en-us/library/ms724256%28v=vs.85%29.aspx)。
=======================================================================
下面是微软的代码。
// QueryKey - Enumerates the subkeys of key and its associated values. // hKey - Key whose subkeys and values are to be enumerated. #include <windows.h> #include <stdio.h> #include <tchar.h> #define MAX_KEY_LENGTH 255 #define MAX_VALUE_NAME 16383 void QueryKey(HKEY hKey) { TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name DWORD cbName; // size of name string TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys=0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time DWORD i, retCode; TCHAR achValue[MAX_VALUE_NAME]; DWORD cchValue = MAX_VALUE_NAME; // Get the class name and the value count. retCode = RegQueryInfoKey( hKey, // key handle achClass, // buffer for class name &cchClassName, // size of class string NULL, // reserved &cSubKeys, // number of subkeys &cbMaxSubKey, // longest subkey size &cchMaxClass, // longest class string &cValues, // number of values for this key &cchMaxValue, // longest value name &cbMaxValueData, // longest value data &cbSecurityDescriptor, // security descriptor &ftLastWriteTime); // last write time // Enumerate the subkeys, until RegEnumKeyEx fails. if (cSubKeys) { printf( " Number of subkeys: %d ", cSubKeys); for (i=0; i<cSubKeys; i++) { cbName = MAX_KEY_LENGTH; retCode = RegEnumKeyEx(hKey, i, achKey, &cbName, NULL, NULL, NULL, &ftLastWriteTime); if (retCode == ERROR_SUCCESS) { _tprintf(TEXT("(%d) %s "), i+1, achKey); } } } // Enumerate the key values. if (cValues) { printf( " Number of values: %d ", cValues); for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++) { cchValue = MAX_VALUE_NAME; achValue[0] = '