爱学习受.NET

www.icjyw.com 记录开发技术收藏天地
公告信息
www.icjyw.com 记录开发技术收藏天地
文章分类
文章档案
文章
使用serialport类枚举串口,并验证串口是否被占用
2011/6/25 21:29:49

使用System.IO.Ports.SerialPort.GetPortNames()枚举可用串口并验证是否被占用,空闲串口添加到comobox1控件中显示。IC交易网代码如下:

验证可用串口
1 public bool IsPortOpen()
2 {
3 //create vars for testing
4   bool _available = false;
5 SerialPort _tempPort;
6 String[] Portname = SerialPort.GetPortNames();
7
8 //create a loop for each string in SerialPort.GetPortNames
9   foreach (string str in Portname)
10 {
11 try
12 {
13 _tempPort = new SerialPort(str);
14 _tempPort.Open();
15
16 //if the port exist and we can open it
17 if (_tempPort.IsOpen)
18 {
19 comboBox1.Items.Add(str);
20 _tempPort.Close();
21 _available = true;
22 }
23 }
24
25 //else we have no ports or can't open them display the
26 //precise error of why we either don't have ports or can't open them
27 catch (Exception ex)
28 {
29 MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
30 _available = false;
31 }
32 }
33
34 //return the temp bool
35 return _available;
36 }
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"
 MyQBlog   浏览(3386)   评论(0)   关键字
  
Copyright © 2010-2020 power by CYQ.Blog - 秋色园 v2.0 All Rights Reserved