来源:http://www.cnblogs.com/hshuzhao/p/4028856.html?utm_source=tuicool&utm_medium=referral

、情境:

做项目的时候要打开串口然后进行一些库函数的调用来操作目标板。串口使用的是usb转串口,板子插进拔出的,每次都使用不一样的usb口,debug的时候懒得每次改com口,又不想在UI上加上一个选择

com口的combox,于是就使用了下面这个方法。

2、环境:

win7 64、vs2010

3、目标:

获取下图的设备到底使用的是com几。

4、source codery>

  1         /// <summary>
2 /// Get the target com num.
3 /// </summary>
4 /// <returns></returns>
5 public static int GetComNum()
6 {
7 int comNum = -1;
8 string[] strArr = GetHarewareInfo(HardwareEnum.Win32_PnPEntity, "Name");
9 foreach (string s in strArr)
10 {
11 Debug.WriteLine(s);
12
13 if (s.Length >= 23 && s.Contains("CH340"))
14 {
15 int start = s.IndexOf("(") + 3;
16 int end = s.IndexOf(")");
17 comNum = Convert.ToInt32(s.Substring(start + 1, end - start - 1));
18 }
19 }
20
21 return comNum;
22
23 }
24
25 /// <summary>
26 /// Get the system devices information with windows api.
27 /// </summary>
28 /// <param name="hardType">Device type.</param>
29 /// <param name="propKey">the property of the device.</param>
30 /// <returns></returns>
31 private static string[] GetHarewareInfo(HardwareEnum hardType, string propKey)
32 {
33
34 List<string> strs = new List<string>();
35 try
36 {
37 using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
38 {
39 var hardInfos = searcher.Get();
40 foreach (var hardInfo in hardInfos)
41 {
42 if (hardInfo.Properties[propKey].Value != null)
43 {
44 String str = hardInfo.Properties[propKey].Value.ToString();
45 strs.Add(str);
46 }
47
48 }
49 }
50 return strs.ToArray();
51 }
52 catch
53 {
54 return null;
55 }
56 finally
57 {
58 strs = null;
59 }
60 }//end of func GetHarewareInfo().
61
62 /// <summary>
63 /// 枚举win32 api
64 /// </summary>
65 public enum HardwareEnum
66 {
67 // 硬件
68 Win32_Processor, // CPU 处理器
69 Win32_PhysicalMemory, // 物理内存条
70 Win32_Keyboard, // 键盘
71 Win32_PointingDevice, // 点输入设备,包括鼠标。
72 Win32_FloppyDrive, // 软盘驱动器
73 Win32_DiskDrive, // 硬盘驱动器
74 Win32_CDROMDrive, // 光盘驱动器
75 Win32_BaseBoard, // 主板
76 Win32_BIOS, // BIOS 芯片
77 Win32_ParallelPort, // 并口
78 Win32_SerialPort, // 串口
79 Win32_SerialPortConfiguration, // 串口配置
80 Win32_SoundDevice, // 多媒体设置,一般指声卡。
81 Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
82 Win32_USBController, // USB 控制器
83 Win32_NetworkAdapter, // 网络适配器
84 Win32_NetworkAdapterConfiguration, // 网络适配器设置
85 Win32_Printer, // 打印机
86 Win32_PrinterConfiguration, // 打印机设置
87 Win32_PrintJob, // 打印机任务
88 Win32_TCPIPPrinterPort, // 打印机端口
89 Win32_POTSModem, // MODEM
90 Win32_POTSModemToSerialPort, // MODEM 端口
91 Win32_DesktopMonitor, // 显示器
92 Win32_DisplayConfiguration, // 显卡
93 Win32_DisplayControllerConfiguration, // 显卡设置
94 Win32_VideoController, // 显卡细节。
95 Win32_VideoSettings, // 显卡支持的显示模式。
96
97 // 操作系统
98 Win32_TimeZone, // 时区
99 Win32_SystemDriver, // 驱动程序
100 Win32_DiskPartition, // 磁盘分区
101 Win32_LogicalDisk, // 逻辑磁盘
102 Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
103 Win32_LogicalMemoryConfiguration, // 逻辑内存配置
104 Win32_PageFile, // 系统页文件信息
105 Win32_PageFileSetting, // 页文件设置
106 Win32_BootConfiguration, // 系统启动配置
107 Win32_ComputerSystem, // 计算机信息简要
108 Win32_OperatingSystem, // 操作系统信息
109 Win32_StartupCommand, // 系统自动启动程序
110 Win32_Service, // 系统安装的服务
111 Win32_Group, // 系统管理组
112 Win32_GroupUser, // 系统组帐号
113 Win32_UserAccount, // 用户帐号
114 Win32_Process, // 系统进程
115 Win32_Thread, // 系统线程
116 Win32_Share, // 共享
117 Win32_NetworkClient, // 已安装的网络客户端
118 Win32_NetworkProtocol, // 已安装的网络协议
119 Win32_PnPEntity,//all device
120 }

6、结果:

正确获得对应的com口号,达到了随便插哪个口程序都可以跑的目的。

C# .net中获取台式电脑中串口设备的名称的更多相关文章

  1. 记录一次bug解决过程:velocity中获取url中的参数

    一.总结 在Webx的Velocity中获取url中参数:$rundata.getRequest().getParameter('userId') 在Webx项目中,防止CSRF攻击(Cross-si ...

  2. 在SQL SERVER中获取表中的第二条数据

    在SQL SERVER中获取表中的第二条数据, 思路:先根据时间逆排序取出前2条数据作为一个临时表,再按顺时排序在临时表中取出第一条数据 sql语句如下: select top 1 * from(se ...

  3. js中获取URL中指定的查询字符串

    js中获取URL中指定的搜索字符串,主要利用location对象实现,废话少说,上代码. function getSearchString(key) { // 获取URL中?之后的字符 var str ...

  4. Flex中获取RadioButtonGroup中的RadioButton的值

    Flex中获取RadioButtonGroup中的RadioButton的值 1.设计源码 <?xml version="1.0" encoding="utf-8& ...

  5. Sql中获取表结构(字段名称,类型,长度,说明)

    Sql中获取表结构(字段名称,类型,长度,说明) SELECT TableName = OBJECT_NAME(c.object_id), ColumnsName = c.name, Descript ...

  6. 父窗口中获取iframe中的元素

    js 在父窗口中获取iframe中的元素 1. 格式:window.frames["iframe的name值"].document.getElementById("ifr ...

  7. 在iframe窗体内 获取父级的元素;;在父窗口中获取iframe中的元素

    在iframe中获取父窗口的元素 $(‘#父窗口中的元素ID’, parent.document).click(); 在父窗口中获取iframe中的元素 $(“#iframe的ID”).content ...

  8. 在弹框中获取foreach中遍历的id值,并传递给地址栏(方法2)

    1.php有时候我们需要再弹框中获取foreach中遍历的数据(例如id),在弹框中点击按钮并传递给地址栏跳转.那么应该怎么做呢.第二种方法. 2. 可以在弹框中给出一个input hidden 点击 ...

  9. 在弹框中获取foreach中遍历的id值,并传递给地址栏。

    1.php有时候我们需要再弹框中获取foreach中遍历的数据(例如id),在弹框中点击按钮并传递给地址栏跳转.那么应该怎么做呢. 2. 点击取现按钮,如果没有设置密码->弹框 3. 点击去设置 ...

随机推荐

  1. python多进程

    一.多进程池 from multiprocessing import Pool import time pool = Pool(processes=3) result=[];lr=range(t);a ...

  2. OA项目之导入

    内容显示页: protected void btnIMP_Click(object sender, EventArgs e)         {             Response.Redire ...

  3. Android.技术站点

    总结Android相关的技术站点和blog 1. http://android-developers.blogspot.com/ 首推这个blog,有时间需要每篇blog读一遍. 2. nlopez ...

  4. sql常用语法

    --在表中添加字段if col_length('JX_DomesticStudy','XL') is null begin alter table JX_DomesticStudy add PXlev ...

  5. hd2066一个人的旅行

    Problem Description 虽然草儿是个路痴(就是在杭电待了一年多,居然还会在校园里迷路的人,汗~),但是草儿仍然很喜欢旅行,因为在旅途中 会遇见很多人(白马王子,^0^),很多事,还能丰 ...

  6. chmod和fchmod函数 /chown ,fchown,lchown函数

    这两个函数使我们可以更改现有文件的访问权限: #include <sys/stat.h> int chmod( const char *pathname, mode_t mode ); i ...

  7. iOS 设置navigationBar背景

    - (void)viewWillAppear:(BOOL)animated {    [superviewWillAppear:animated];    [self.navigationContro ...

  8. 5.3 Static

    相信很多人都遇到过App 莫名其妙就崩溃的情况,尤其是一些配置很低的手机,重现场景就是在App 切换到后台,闲置了一段时间后再继续使用时,就会崩溃.导致上述崩溃发生的罪魁祸首就是全局变量. 在内存不足 ...

  9. (Gym 100685G) Gadget Hackwrench(LCA在线ST)

    Gadget Hackwrench time limit per test 2 seconds memory limit per test 64 megabytes input standard in ...

  10. 数据库知识整理<四>

    使用DML语句更改数据: 所谓DML语句是指数据库操作语句,其中包括的是对数据库数据的修改.删除.插入. 4.1添加新数据: 插入单行的记录:基本的SQL语句为-insert into <表明& ...