還可利用WM_DEVICECHANGE來攔截相關訊息
由於網路上多是C/C++的實作
真不容易找到C#的 但又沒有完整的用C#查Port Name
在Reference[2]有相關的教學,但沒有查Port Name
就看了MSDN的說明,依樣畫葫蘆做出來了
在Reference[2]裡有做了 Win32的class
[StructLayout(LayoutKind.Sequential)] public class DEV_BROADCAST_PORT {
public int dbcp_size;
public int dbcp_devicetype;
public int dbcp_reserved;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public char[] dbcp_name;
}
然後在DBT_DEVICEARRIVAL裡,再改成用剛寫的StructLayout DEV_BROADCAST_PORT
if (m.WParam.ToInt32() == DBT_DEVICEARRIVAL)
{
Marshal.PtrToStructure(m.LParam, typeof(Win32.DEV_BROADCAST_HDR));
int dbccSize = Marshal.ReadInt32(m.LParam, 0);
int devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == Win32.DBT_DEVTYP_PORT)
{
Win32.DEV_BROADCAST_PORT dip = (Win32.DEV_BROADCAST_PORT)
Marshal.PtrToStructure(m.LParam, typeof(Win32.DEV_BROADCAST_PORT));
string csTemp = "COM" + dip.dbcp_name[6].ToString(); //dbcp_name是一串字,在第6個是COM的Number
//MessageBox.Show(csTemp + " arrived/removed");
listBox1.Items.Add(csTemp + " arrived/removed");
}
}
Reference
1.MSDN WM_DEVICECHANGE Message MSDN的說明
2.Retrieving dbcc_name string from a DEV_BROADCAST_DEVICEINTERFACE structure 有VB及C#的實作
沒有留言:
張貼留言