在vc中如何检测那几个串口可用?

解决方案 »

  1.   

    http://search.csdn.net/Expert/topic/773/773547.xml?temp=.9784967
    里面有段可用的代码,是VB的,翻译成VC即可
      

  2.   

    转贴一篇,希望对你有用//检测本机的Com口的个数
    主        题:  如何检测本机的Com口的个数?我的情况比较特殊。 
    作        者:  sks (可子) 
    描述:
    手机,用usb连电脑,没连的时候,电脑只有两个com口,连了手机后,有4个。拔下来,又剩两个。我需要访问com3控制手机,如果我把手机插上,再连,没问题。
    如果我不插手机,用程序连接com3,会报告连接失败,如果这时候把手机连接到电脑上,再试图连接com3,无论如何也不能成功的创建连接。必须重新启动计算机。
    我想,有两个方法能解决
    1,有什么方法能把连接失败的后果清掉。
    2,在连接之前判断一下有哪些com口,这个过程绝对不能用尝试连接的方法来确定。应该有专门的函数吧。
    请高人指点。
    谢谢。
    回复人: cqiu2000(算死草)
    ClearCommError
    回复人: zhangnanonnet(pizizhang)
    检查注册表这个位置就行了
    HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
    所有的串口注册信息都在这
    回复人: masterz()
    #include "stdafx.h"
    #include <stdio.h>
    #include <windows.h>
    #include <setupapi.h>
    #include <devguid.h>
    #include <regstr.h>
    #pragma comment(lib,"Setupapi.lib")
    void printdata(LPVOID pdata,DWORD datalen,DWORD type);
    int main( int argc, char *argv[ ], char *envp[ ] )
    {
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    DWORD i;
    // Create a HDEVINFO with all present devices.
    hDevInfo = SetupDiGetClassDevs(NULL, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES );
    if (hDevInfo == INVALID_HANDLE_VALUE)
    {
    return 1;
    }
    // Enumerate through all devices in Set.
    int nComCount = 0;
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,
    &DeviceInfoData);i++)
    {
    DWORD DataT;
    LPTSTR buffer = NULL;
    DWORD buffersize = 0;
    //
    // Call function with null to begin with, 
    // then use the returned buffer size 
    // to Alloc the buffer. Keep calling until
    // success or an unknown failure.
    // 
    while (!SetupDiGetDeviceRegistryProperty(
    hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC, &DataT, (PBYTE)buffer, buffersize, &buffersize))
    {
    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
    // Change the buffer size.
    if (buffer) LocalFree(buffer);
    buffer = (char*)LocalAlloc(LPTR,buffersize);
    }
    else
    {
    // Insert error handling here.
    break;
    }
    }        
    if(strcmp(buffer,"Communications Port")==0)
    nComCount++;//printf("SPDRP_DEVICEDESC:[%s]\n",buffer);
    if (buffer) LocalFree(buffer);
    continue;
    }
    if ( GetLastError()!=NO_ERROR &&GetLastError()!=ERROR_NO_MORE_ITEMS )
    {
    // Insert error handling here.
    return 1;
    }
    printf("Communications Port count:%d by masterz\n",nComCount );
    //  Cleanup
    SetupDiDestroyDeviceInfoList(hDevInfo);
    return 0;

    //HOWTO: Force Reenumeration of a Device Tree From an Application Q259697
    版主点评:
    Wonderful, 这个API 真的没听过,更别说用过了,相关API 已经记录在案,呵呵,佩服一下!
      

  3.   

    首先感谢 alon21(飘一族.Alon)
    但是你给那段程序不行啊,怎么死循环?
    检测注册表我想过,但是我想动态的得到,建立了检测线程,问题是程序不行。
    呵呵,麻烦你了!
      

  4.   

    oyljerry,谢谢,线程可以,但是检测的方法?