思路:
占用串口,其它程序无法使用串口,则起到禁用的作用;
启用串口:关闭已启用的串口,使其它程序可以使用串口。
首先需要获取设备中串口的数目
void enumCom() { HKEY hKey; LONG lResult ; TCHAR szKeyName[64] ; RegOpenKeyEx(HKEY_LOCAL_MACHINE,TEXT("Drivers//BuiltIn"),0,0,&hKey); int i = 0; do { DWORD dwKeynameLength = MAX_PATH; lResult = RegEnumKeyEx(hKey,i,szKeyName,&dwKeynameLength,0,NULL,NULL,NULL); if(lResult != ERROR_SUCCESS) { break; } if( !wcsncmp(TEXT("Serial"),szKeyName,6)) { TCHAR szComKey[MAX_PATH] = TEXT("Drivers//BuiltIn//"); wcscat(szComKey,szKeyName); HKEY hComKey; RegOpenKeyEx(HKEY_LOCAL_MACHINE,szComKey,0,0,&hComKey); DWORD keyType; DWORD dwLength = 20; TCHAR buf[64]; RegQueryValueEx(hComKey,TEXT("Port"),0,&keyType,(BYTE *)buf,&dwLength); //comArray[comNum] = wide2short(buf); strcpy(comArray[nComCouont], wide2short(buf)); //ListBox_AddString(GetDlgItem(hDlg,IDC_LIST1),buf); RegCloseKey(hComKey); nComCouont++; } i++; } while (lResult != ERROR_NO_MORE_ITEMS); RegCloseKey(hKey); }
禁用串口:
void CComCtrlDlg::OnBnClickedForbidCom() { // TODO: 在此添加控件通知处理程序代码 //枚举串口 if(nComCouont == 0) enumCom(); if(nComCouont > 0) { hComList = new HANDLE[nComCouont]; ZeroMemory(hComList,(sizeof(HANDLE))*nComCouont); } int nOpenCom = 0; for(int i=0; i< nComCouont; i++) { hComList[i] = CreateFile(short2wide(comArray[i]), GENERIC_READ | GENERIC_WRITE,0, NULL, OPEN_EXISTING, 0, NULL); MTCHAR msg = {0}; wcscpy(msg, L"禁用串口: "); wchar_t * wname = short2wide(comArray[i]); wcscat(msg, wname); if(hComList[i] == INVALID_HANDLE_VALUE) { wcscat(msg, L" 失败!"); } else { nOpenCom++; wcscat(msg, L" 成功!"); } ::MessageBox(NULL,msg,L"Notice",MB_OK); } if(nOpenCom == nComCouont) ::MessageBox(NULL, L"成功禁用所有串口", L"Notice", MB_OK ); }
启用串口:关闭打开的串口
void CComCtrlDlg::OnBnClickedRestartCom() { // TODO: 在此添加控件通知处理程序代码 if(nComCouont == 0) enumCom(); int nClose = 0; for(int i=0; i< nComCouont; i++) { MTCHAR msg = {0}; wcscpy(msg, L"启用串口: "); wchar_t * wname = short2wide(comArray[i]); wcscat(msg, wname); if(hComList[i] != INVALID_HANDLE_VALUE) { CloseHandle(hComList[i]); hComList[i] = NULL; nClose++; wcscat(msg, L"成功!"); } else { wcscat(msg, L" 失败!"); } ::MessageBox(NULL,msg,L"Notice",MB_OK); } if(nClose == nComCouont) ::MessageBox(NULL, L"成功启动所有串口", L"Notice", MB_OK ); }