CreateFile方法:
void GetComList_256(CComboBox * CCombox)//获取可用com口支持到256个
{
CString strCom,strComOpen;
int nCom = 0;
int count = 0;
HANDLE hCom;
CCombox->ResetContent();
do
{
nCom ;
strCom.Format("COM%d", nCom);
strComOpen.Format("\\.\COM%d", nCom);
hCom = CreateFile(strComOpen, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if(INVALID_HANDLE_VALUE == hCom )
{
DWORD error=::GetLastError();//取得错误信息
}
else
{
CCombox->AddString( strCom );
count ;
}
CloseHandle(hCom);
} while(nCom<256);
CCombox->SetCurSel(0);
}
*******************************************************************
读取注册表方法:
int GetComList_Reg( CComboBox * CCombox )
{
HKEY hkey;
int result;
int i = 0;
CString strComName;//串口名称
CString strDrName;//串口详细名称
result = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
_T( "Hardware\DeviceMap\SerialComm" ),
NULL,
KEY_READ,
&hkey );
if( ERROR_SUCCESS == result ) // 打开串口注册表
{
TCHAR portName[ 0x100 ], commName[ 0x100 ];
DWORD dwLong, dwSize;
CCombox->ResetContent();
do
{
dwSize = sizeof( portName ) / sizeof( TCHAR );
dwLong = dwSize;
result = RegEnumValue( hkey, i, portName, &dwLong, NULL, NULL, ( LPBYTE )commName, &dwSize );
if( ERROR_NO_MORE_ITEMS == result )
{
// 枚举串口
break; // commName就是串口名字"COM2"
}
strComName=commName;
strDrName = portName;
// 从右往左边开始查找第一个'\',获取左边字符串的长度
int len = strDrName.ReverseFind( '\');
// 获取'\'左边的字符串
CString strFilePath = strDrName.Left( len 1 );
// 获取'\'右边的字符串
CString fileName = strDrName.Right(strDrName.GetLength() - len-1);
fileName = strComName _T(": ") fileName;
CCombox->AddString(fileName);
i ;
} while ( 1 );
RegCloseKey( hkey );
}
CCombox->SetCurSel(0);
return i;
}
读取后还可以加入到组合框中,可以根据需要加入到数据中