主要参考如下:下面这里也给出了串口助手开发的相关过程和USB热拔插检测相关。 https://blog.csdn.net/weixin_44547715/article/details/105958317?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164854319116780357276896%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164854319116780357276896&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-2-105958317.142v5pc_search_result_control_group,143v6control&utm_term=C%23%E4%B8%B2%E5%8F%A3%E6%8B%94%E5%87%BA%E5%90%8E%E6%8A%A5%E9%94%99&spm=1018.2226.3001.4187
测验代码部分如下:
protected override void WndProc(ref Message m)
{
String serialPortName;
serialPortName = cbx_commNo.Text;
if (m.Msg == 0x0219){
if (m.WParam.ToInt32() == 0x8004){
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
cbx_commNo.Items.Clear();
cbx_commNo.Items.AddRange(ports);
if (btn_comm.Text == "关闭串口")
{
if (!serialPort1.IsOpen){
btn_comm.Text = "打开串口";
serialPort1.Dispose();
cbx_commNo.SelectedIndex = cbx_commNo.Items.Count > 0 ? 0 : -1;
lbl_commStasData.Text = "已断开";
lbl_commStasData.ForeColor = Color.Red;
}
else{
cbx_commNo.Text = serialPortName;
}
}
else{
cbx_commNo.SelectedIndex = cbx_commNo.Items.Count > 0 ? 0 : -1;
}
}
else if (m.WParam.ToInt32() == 0x8000){
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
cbx_commNo.Items.Clear();
cbx_commNo.Items.AddRange(ports);
if (btn_comm.Text == "关闭串口")
{
cbx_commNo.Text = serialPortName;
}
else{
cbx_commNo.SelectedIndex = cbx_commNo.Items.Count > 0 ? 0 : -1;
}
}
}
base.WndProc(ref m);
}
上述代码已通过项目测试,能够正常使用!
|