如何获取正在使用的RS232端口? [英] How do I get the RS232 ports that are being used?
本文介绍了如何获取正在使用的RS232端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取正在使用的RS232端口?这是我提出的代码。
How do I get the RS232 ports that are being used? This is the code that I came up with.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Management;
namespace Detect_USB2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SerialPort ComPort = new SerialPort();
chkSP();
}
private void chkSP()
{
ManagementObjectSearcher searchType = new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
foreach (ManagementObject moDiskete in searchType.Get())
{
if (!listBox1.Items.Contains(moDiskete["Name"]))
{
listBox1.Items.Add(moDiskete["Name"].ToString());
}
}
}
private void MyTimer_Tick(object sender, EventArgs e)
{
listBox1.Items.Clear();
chkSP();
}
private void Form1_Load(object sender, EventArgs e)
{
Timer MyTimer = new Timer();
MyTimer.Interval = (5 * 1000); // 1 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
}
}
推荐答案
以SerialPort.GetPortNames(v=vs.110).aspx [< a href =http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames(v=vs.110).aspx\"target =_ blanktitle =New Window > ^ ]要找到系统的所有可用端口,那么你几乎必须尝试在try ... catch块中打开每个端口并仅使用那些没有失败的端口。对于comport没有IsFree属性,IsOpen只跟踪当前应用程序中的端口 - 如果它在不同的应用程序中打开(因此不是免费的),IsOpen仍将返回false。
Start with SerialPort.GetPortNames(v=vs.110).aspx[^] to find all available ports to the system, then you pretty much have to try to Open each one in a try...catch block and use only those that don't fail. There is no "IsFree" property for a comport and "IsOpen" only tracks ports within the current app - if it's open in a different application (and thus not free) IsOpen will still return false.
这篇关于如何获取正在使用的RS232端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文