监听USB设备插拔动态

listbox1添加设备串口时出现多次触发通知,该怎么处理?


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Management;
using System.Threading;
using System.Diagnostics;
using System.Timers;


namespace Port_display
{
    public partial class Frm_Main : Form
   {
        public Frm_Main()
        {
            InitializeComponent();

        }

        private void Frm_Main_Load(object sender, EventArgs e)
        {
            //Control.CheckForIllegalCrossThreadCalls = false;
            this.BeginInvoke((EventHandler)(delegate { listBox1.Items.AddRange(SerialProtFindHelper.GetSerialPort()); }));//跨线程事件
        }

        private const int WM_DEVICECHANGE = 0x219; //设备改变
        private const int DBT_DEVICEARRIVAL = 0x8000; //检测到新设备
        private const int DBT_DEVICEREMOVECOMPLETE = 0x8004; //移除设备
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.Msg)
            {
                case WM_DEVICECHANGE://设备改变事件
                    switch ((int)m.WParam)
                    {
                        case DBT_DEVICEARRIVAL:
                            
                            this.BeginInvoke((EventHandler)(delegate { listBox1.Items.AddRange(SerialProtFindHelper.GetSerialPort()); }));//跨线程事件
                            break;
                        case DBT_DEVICEREMOVECOMPLETE:
                            //MessageBox.Show("USB串口拔出");
                            listBox1.Items.Clear();
                            break;
                    }
                    break;
            }
        }