本文主要是介绍Windows上 C语言枚举com串口(serial_port),打印值和其编号(port),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
宽字节版本
void enumerate_serial_ports() {HDEVINFO deviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, NULL, NULL, DIGCF_PRESENT);if (deviceInfoSet == INVALID_HANDLE_VALUE)return;SP_DEVINFO_DATA deviceInfoData;deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);for (DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, &deviceInfoData); i++) {HKEY hDeviceKey = SetupDiOpenDevRegKey(deviceInfoSet, &deviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);if (hDeviceKey != INVALID_HANDLE_VALUE) {DWORD dwType, dwSize = 0;wchar_t portName[256];dwSize = sizeof(portName);if (RegQueryValueEx(hDeviceKey, L"PortName", NULL, &dwType, (LPBYTE)portName, &dwSize) == ERROR_SUCCESS) {if (dwType == REG_SZ) {wchar_t deviceName[256];if (SetupDiGetDeviceRegistryProperty(deviceInfoSet, &deviceInfoData, SPDRP_DEVICEDESC, NULL, (PBYTE)deviceName, sizeof(deviceName), NULL)) {wprintf(L"%ls (%ls)\n", deviceName, portName);}}}RegCloseKey(hDeviceKey);}}SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
多字节版本
#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#include <regstr.h>
#include <stdio.h>#pragma comment(lib, "setupapi.lib")void enumerate_serial_ports() {HDEVINFO deviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, NULL, NULL, DIGCF_PRESENT);if (deviceInfoSet == INVALID_HANDLE_VALUE)return;SP_DEVINFO_DATA deviceInfoData;deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);for (DWORD i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, &deviceInfoData); i++) {HKEY hDeviceKey = SetupDiOpenDevRegKey(deviceInfoSet, &deviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);if (hDeviceKey != INVALID_HANDLE_VALUE) {DWORD dwType, dwSize = 0;char portName[256];dwSize = sizeof(portName);if (RegQueryValueExA(hDeviceKey, "PortName", NULL, &dwType, (LPBYTE)portName, &dwSize) == ERROR_SUCCESS) {if (dwType == REG_SZ) {char deviceName[256];if (SetupDiGetDeviceRegistryPropertyA(deviceInfoSet, &deviceInfoData, SPDRP_DEVICEDESC, NULL, (PBYTE)deviceName, sizeof(deviceName), NULL)) {printf("%s (%s)\n", deviceName, portName);}}}RegCloseKey(hDeviceKey);}}SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
这篇关于Windows上 C语言枚举com串口(serial_port),打印值和其编号(port)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!