C#:DeviceNotifier USB裝置插拔監聽方法
阿新 • • 發佈:2019-02-12
裝置變化通知函式
1、為監聽裝置事件建立一個DeviceNotifier例項
2、當有鍵值按下後顯示裝置
using System; using LibUsbDotNet.DeviceNotify; namespace LibUsbDotNet_Learn { class Program { public static IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier(); static void Main(string[] args) { //裝置的監聽事件 UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent; //鍵盤有任意鍵按下將結束 Console.Clear(); Console.WriteLine(); Console.WriteLine("Waiting for system level device events.."); Console.Write("[Press any key to exit]"); while(!Console.KeyAvailable) { // Application.DoEvents(); } UsbDeviceNotifier.Enabled = false; UsbDeviceNotifier.OnDeviceNotify -= OnDeviceNotifyEvent; } private static void OnDeviceNotifyEvent(object sender,DeviceNotifyEventArgs e) { //事件發生 //設定游標的位置 Console.SetCursorPosition(0, Console.CursorTop); Console.WriteLine(e.ToString());//將事件輸出 Console.WriteLine(); Console.Write("[Press any key to exit]"); } } }