110,534
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
private Stopwatch stopwatch = new Stopwatch();
private VSPortAxClass[] vports = new VSPortAxClass[10]; //10个虚拟串口
IntPtr handle = IntPtr.Zero;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//添加所有串口
ComListcomboBox.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//新建
for (int i = 0; i < 10; i++)
{
vports[i] = new VSPortAxClass();
vports[i].DeleteOnExit = false;
}
}
//创建虚拟虚拟串口
private void button1_Click(object sender, EventArgs e)
{
int i=50;
stopwatch.Restart();
foreach (var vp in vports)
{
if (!ComListcomboBox.Items.Contains(string.Format("COM{0}", i)))
{
if (!vp.CreatePort(string.Format("COM{0}", i++)))
{
MessageBox.Show(string.Format("COM{0}创建不成功", i - 1));
break;
}
}
else
{
if ( !vp.Attach(string.Format("COM{0}", i++)))
{
MessageBox.Show(string.Format("COM{0}适配不成功", i - 1));
break;
}
}
}
stopwatch.Stop();
MessageBox.Show(string.Format("共消耗时间:{0}MS", stopwatch.ElapsedMilliseconds));
ComListcomboBox.Items.Clear();
ComListcomboBox.Items.AddRange(SerialPort.GetPortNames());
}
//删除串口
private void button2_Click(object sender, EventArgs e)
{
int i = 50;
stopwatch.Restart();
foreach (var vp in vports)
{
if (!vp.Delete())
{
MessageBox.Show(string.Format("COM{0}删除不成功", i++));
break;
}
}
stopwatch.Stop();
MessageBox.Show(string.Format("共消耗时间:{0}MS", stopwatch.ElapsedMilliseconds));
ComListcomboBox.Items.Clear();
ComListcomboBox.Items.AddRange(SerialPort.GetPortNames());
}
}