看看下面这哥们的回复,如果只是在WIN32平台下,可以简单使用GetDefaultCommConfig()这个API。
Why don't you simply call the Win32 API GetDefaultCommConfig() to figure out whether a specific port exists. Optionally followed by CreateFile() if you like to know if another process currently has opened that port.
Works on all Win32 platforms and is much simpler.
Attention:
COM10 or greater must be preceeded with "\\.\" for calls to CreateFile(). See Q115831 for details. WinCE needs a trailing ":" for both GetDefaultCommConfig() and CreateFile().
上面提供免费下载的代码,直接调用就行了,刚好是解决这问题的。
Introduction
You might think that determining which serial ports are present on a Windows PC would be an easy task. It seems like a reasonable enough thing for the OS to support. Unfortunately, there was no support for it at all (short of reading the registry yourself) before Win2K, and even then, the API is a bit cumbersome.
The attached serial port enumeration code first determines which operating system it is running under, and then runs the appropriate routine to enumerate the serial ports. In Win 9x (and Me) it uses the registry. In W2K and later it uses the SetupAPI that was included in that version of the WinSDK. It also has support for "brute force" enumeration of serial ports under NT4.
Unfortunately, I statically linked with setupapi.lib, so the provided executable won't actually run under 95 and nt4 (I didn't really need to support those OS's for my application.) This could be finagled by replacing the SetupDi* function calls with dynamic binding via LoadLibrary if needed.
To use the EnumSerial code, simply include EnumSerial.cpp and .h in your project, and link with setupapi.lib in the win32 sdk (this is under "additional dependencies" in the project link settings in Visual Studio).
All you have to do now is #include "EnumSerial.h" in your source code, allocate an empty CArray of SSerInfo structs, and make a call to EnumSerialPorts. It will populate your array with filled-out SSerInfo structs which contain the following information:
CString strDevPath; // Device path for use with CreateFile()
CString strPortName; // Simple name (i.e. COM1)
CString strFriendlyName; // Full name to be displayed to a user
BOOL bUsbDevice; // Provided through a USB connection?
CString strPortDesc; // friendly name without the COMx
Example
CArray<SSerInfo,SSerInfo&> asi;
EnumSerialPorts(asi,FALSE/*include all*/);