bestlong 怕失憶論壇

標題: 列出 windows 所有的 RS232 COM Port 列表 [打印本頁]

作者: bestlong    時間: 2011-3-14 16:17     標題: 列出 windows 所有的 RS232 COM Port 列表

機碼 HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM 就紀錄所有的 COM Port.

comportlist-2.png

所以可以使用讀取機碼的方式來取得 COM Port 列表
  1. unit Unit1;

  2. interface

  3. uses
  4.   Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  5.   Registry, StdCtrls;

  6. type
  7.   TForm1 = class(TForm)
  8.     Memo1: TMemo;
  9.     procedure FormCreate(Sender: TObject);
  10.   private
  11.     { Private declarations }
  12.   public
  13.     { Public declarations }
  14.   end;

  15. var
  16.   Form1: TForm1;

  17. implementation

  18. {$R *.DFM}

  19. procedure TForm1.FormCreate(Sender: TObject);
  20. var
  21.   reg : TRegistry;
  22.   sl: TStrings;
  23.   i: integer;
  24. begin
  25.   Memo1.Clear;
  26.   reg := TRegistry.Create;
  27.   try
  28.     reg.RootKey := HKEY_LOCAL_MACHINE;
  29.     reg.OpenKey('HARDWARE\DEVICEMAP\SERIALCOMM', false);
  30.     sl := TStringList.Create;
  31.     try
  32.       reg.GetValueNames(sl);
  33.       for i := 0 to sl.Count -1 do
  34.         Memo1.Lines.Add(reg.ReadString(sl.Strings[i]));
  35.     finally
  36.       sl.Free;
  37.     end;
  38.   finally
  39.     reg.CloseKey;
  40.     reg.free;
  41.   end;
  42. end;

  43. end.
複製代碼
comportlist.png

圖片附件: comportlist.png (2011-3-14 16:16, 7.11 KB) / 下載次數 104
http://www.bestlong.idv.tw/forum.php?mod=attachment&aid=MjU0fDM3MDBhOTNmfDE3MTQ2NjA2MzN8MA%3D%3D



圖片附件: comportlist-2.png (2011-3-14 16:21, 31.26 KB) / 下載次數 103
http://www.bestlong.idv.tw/forum.php?mod=attachment&aid=MjU1fDU3ZDIxMGEzfDE3MTQ2NjA2MzN8MA%3D%3D


作者: bestlong    時間: 2013-8-9 11:06

配合作業系統的安全性架構,在 Open Key 之前最好要設定存取等級

reg.RootKey := HKEY_LOCAL_MACHINE;
reg.Access := KEY_READ;
reg.OpenKey('HARDWARE\DEVICEMAP\SERIALCOMM', false);
作者: bestlong    時間: 2013-8-9 11:09

只有 COMn 的列表也不是很確定是對應到哪個設備,需要更友善的資訊

http://delphi.cjcsoft.net/viewthread.php?tid=45021

Enumerating available comm ports with friendly names.
Title: Enumerating available comm ports with friendly names.

Question: Serial (and virtual serial) PNP Devices (PCMCIA, USB, Bluetooth) get assigned "arbitrary" comm port numbers.
To help users to select the correct comm port it would be helpfull to list them with device friendly names.
The supplied function helps this goal.


Answer:
  1. (*

  2. The function below returns a list of available COM-ports
  3. (not open by this or an other process), with friendly names. The list is formatted as follows:

  4. COM1: = Communications Port (COM1)
  5. COM5: = NI Serial Port (Com5)
  6. COM6: = NI Serial Port (Com6)
  7. COM7: = USB Serial Port (COM7)
  8. COM8: = Bluetooth Communications Port (COM8)
  9. COM9: = Bluetooth Communications Port (COM9)



  10. The function uses the setupapi (setup api) unit that is available from
  11. "http://homepages.borland.com/jedi/cms/modules/apilib/visit.php?cid=4&lid=3".

  12. I have verified the code and it worked  for W2000, WXP, W98. It does not work for W95, and NT 4.0. I did not check WME but I guess it will work with WME too.


  13. *)

  14. function SetupEnumAvailableComPorts:TstringList;
  15. // Enumerates all serial communications ports that are available and ready to
  16. // be used.

  17. // For the setupapi unit see
  18. // http://homepages.borland.com/jedi/cms/modules/apilib/visit.php?cid=4&lid=3

  19. var
  20.   RequiredSize:             Cardinal;
  21.   Guid:                     TGUID;
  22.   DevInfoHandle:            HDEVINFO;
  23.   DeviceInfoData:           TSPDevInfoData;
  24.   MemberIndex:              Cardinal;
  25.   PropertyRegDataType:      DWord;
  26.   RegProperty:              Cardinal;
  27.   RegTyp:                   Cardinal;
  28.   Key:                      Hkey;
  29.   Info:                     TRegKeyInfo;
  30.   S1,S2:                    string;
  31.   hc:                       THandle;
  32. begin
  33.   Result:=Nil;
  34. //If we cannot access the setupapi.dll then we return a nil pointer.   
  35.   if not LoadsetupAPI then exit;
  36.   try
  37. // get 'Ports' class guid from name
  38.     if SetupDiClassGuidsFromName('Ports',@Guid,RequiredSize,RequiredSize) then begin
  39. //get object handle of 'Ports' class to interate all devices
  40.        DevInfoHandle:=SetupDiGetClassDevs(@Guid,Nil,0,DIGCF_PRESENT);
  41.        if Cardinal(DevInfoHandle)Invalid_Handle_Value then begin
  42.          try
  43.            MemberIndex:=0;
  44.            result:=TStringList.Create;
  45. //iterate device list
  46.            repeat
  47.              FillChar(DeviceInfoData,SizeOf(DeviceInfoData),0);
  48.              DeviceInfoData.cbSize:=SizeOf(DeviceInfoData);
  49. //get device info that corresponds to the next memberindex
  50.              if Not SetupDiEnumDeviceInfo(DevInfoHandle,MemberIndex,DeviceInfoData) then
  51.                break;
  52. //query friendly device name LIKE 'BlueTooth Communication Port (COM8)' etc
  53.              RegProperty:=SPDRP_FriendlyName;{SPDRP_Driver, SPDRP_SERVICE, SPDRP_ENUMERATOR_NAME,SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,SPDRP_FRIENDLYNAME,}
  54.              SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,
  55.                                                    RegProperty,
  56.                                                    @PropertyRegDataType,
  57.                                                    NIL,0,@RequiredSize);
  58.              SetLength(S1,RequiredSize);
  59.              if SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,
  60.                                                  RegProperty,
  61.                                                  @PropertyRegDataType,
  62.                                                  @S1[1],RequiredSize,@RequiredSize) then begin
  63.                KEY:=SetupDiOpenDevRegKey(DevInfoHandle,DeviceInfoData,DICS_FLAG_GLOBAL,0,DIREG_DEV,KEY_READ);
  64.                if keyINValid_Handle_Value then begin
  65.                  FillChar(Info, SizeOf(Info), 0);
  66. //query the real port name from the registry value 'PortName'
  67.                  if RegQueryInfoKey(Key, nil, nil, nil, @Info.NumSubKeys,@Info.MaxSubKeyLen, nil, @Info.NumValues, @Info.MaxValueLen,
  68.                                                         @Info.MaxDataLen, nil, @Info.FileTime) = ERROR_SUCCESS then begin
  69.                    RequiredSize:= Info.MaxValueLen + 1;
  70.                    SetLength(S2,RequiredSize);
  71.                    if RegQueryValueEx(KEY,'PortName',Nil,@Regtyp,@s2[1],@RequiredSize)=Error_Success then begin
  72.                      If (Pos('COM',S2)=1) then begin
  73. //Test if the device can be used
  74.                        hc:=CreateFile(pchar('\\.\'+S2+#0),
  75.                                       GENERIC_READ or GENERIC_WRITE,
  76.                                       0,
  77.                                       nil,
  78.                                       OPEN_EXISTING,
  79.                                       FILE_ATTRIBUTE_NORMAL,
  80.                                       0);
  81.                        if hc INVALID_HANDLE_VALUE then begin
  82.                          Result.Add(Strpas(PChar(S2))+': = '+StrPas(PChar(S1)));
  83.                          CloseHandle(hc);
  84.                        end;
  85.                      end;
  86.                    end;
  87.                  end;
  88.                  RegCloseKey(key);
  89.                end;
  90.              end;
  91.              Inc(MemberIndex);
  92.            until False;
  93. //If we did not found any free com. port we return a NIL pointer.
  94.            if Result.Count=0 then begin
  95.              Result.Free;
  96.              Result:=NIL;

  97.            end
  98.          finally
  99.            SetupDiDestroyDeviceInfoList(DevInfoHandle);
  100.          end;
  101.        end;
  102.     end;
  103.   finally
  104.     UnloadSetupApi;
  105.   end;
  106. end;
複製代碼





歡迎光臨 bestlong 怕失憶論壇 (http://www.bestlong.idv.tw/) Powered by Discuz! X1.5