Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

C# 查看串口


方法介绍

  1. 在WPF中,每一个窗口都拥有一个Loaded事件传入接口,可以将函数传入该接口(即把函数委托给Loaded事件)。Loaded事件在元素即将要被渲染时触发。

  2. 在Loaded时定义拦截Windows消息拦截事件。事件函数(DeviceChanged)被委托给HwndSource的Hook。

  3. 在DeviceChanged函数中过滤串口插拔事件,并执行串口插拔后需要完善的逻辑操作。

  4. 事件序号:0x219 移动设备改变事件。0x8000设备插入事件。0x8004设备拔出事件。

具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

public MainWindow()
{
Loaded+=MainWindow_Loaded;
}

void MainWindow_Loaded(object sender,RoutedEventArgs e)
{
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if(null!=hwndSource)
hwndSource.AddHook(new HwndSourceHook(DevieceChanged));
}

private IntPtr DeviceChanged(IntPtr hwnd,int msg,IntPtr wParam,IntPtr lParam,ref bool handled)
{
string[] PortNames;
if (msg == WM_DEVICECHANGE)
{
switch (wParam.ToInt32())
{
case DBT_DEVICEARRIVAL://设备插入
PortNames = SerialPort.GetPortNames();
if (IsWorking == true && PortNames.Contains(ConfigInfo.Port))
{
if (serialPortUtil != null)
{
serialPortUtil.OpenPort();
MsgBox.Show("串口连接成功!");
}
}
break;
case DBT_DEVICEREMOVECOMPLETE: //设备卸载
PortNames = SerialPort.GetPortNames();
if (IsWorking == true && !PortNames.Contains(ConfigInfo.Port))
{
MsgBox.Show("串口连接断开!");
}
break;
default:
break;
}
}
return IntPtr.Zero;
}

通过该方法可以实现对串口插拔事件的监听。

参考内容

C#获取串口列表

评论