1、本文来介绍一下,利用 VB.Net 检测 U 盘插拔状态并读写的方法代码如下:Imports System.IOPublic Class Form1Public Const WM_DEVICECHANGE = &H219Public Const DBT_DEVICEARRIVAL = &H8000Public Const DBT_CONFIGCHANGECANCELED = &H19Public Const DBT_CONFIGCHANGED = &H18Public Const DBT_CUSTOMEVENT = &H8006Public Const DBT_DEVICEQUERYREMOV
2、E = &H8001Public Const DBT_DEVICEQUERYREMOVEFAILED = &H8002Public Const DBT_DEVICEREMOVECOMPLETE = &H8004Public Const DBT_DEVICEREMOVEPENDING = &H8003Public Const DBT_DEVICETYPESPECIFIC = &H8005Public Const DBT_DEVNODES_CHANGED = &H7Public Const DBT_QUERYCHANGECONFIG = &H17Public Const DBT_USERDEFIN
3、ED = &HFFFFProtected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)If m.Msg = WM_DEVICECHANGE ThenSelect Case m.WParamCase WM_DEVICECHANGECase DBT_DEVICEARRIVAL U 盘插入ComboBox1.Items.Clear()Dim s() As DriveInfo = DriveInfo.GetDrivesFor Each drive As DriveInfo In sIf drive.DriveType =
4、DriveType.Removable ThenListBox1.Items.Add(“U 盘已插入!盘符为:“ + drive.Name.ToString()ComboBox1.Items.Add(drive.Name)End IfNextBtnWrite.Enabled = TrueBtnRead.Enabled = TrueCase DBT_CONFIGCHANGECANCELEDCase DBT_CONFIGCHANGEDCase DBT_CUSTOMEVENTCase DBT_DEVICEQUERYREMOVECase DBT_DEVICEQUERYREMOVEFAILEDCase
5、DBT_DEVICEREMOVECOMPLETE U 盘卸载ListBox1.Items.Add(“U 盘卸载!“)BtnWrite.Enabled = FalseBtnRead.Enabled = FalseCase DBT_DEVICEREMOVEPENDINGCase DBT_DEVICETYPESPECIFICCase DBT_DEVNODES_CHANGEDCase DBT_QUERYCHANGECONFIGCase DBT_USERDEFINEDEnd SelectEnd IfMyBase.WndProc(m)End SubPrivate Sub Form1_Load(ByVal
6、sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadListBox1.Items.Add(“请您现在插入 U 盘至 USB 接口!“)End SubPrivate Sub BtnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnWrite.ClickIf ComboBox1.Text = “ ThenMsgBox(“请选择 U 盘盘符!“, MsgBoxStyle.Exclamation
7、, “Warn“)ElseDim Writer As StreamWriter = NothingTryDim fileName As String = ComboBox1.Text + “Test.txt“Writer = New StreamWriter(fileName)Writer.WriteLine(InputBox(“老四,请输入要保存的字符串“, “输入信息“, “Input then Test String! hehe!“)MsgBox(“Write to “ + fileName + “ Success!“)Catch ex As ExceptionMsgBox(ex.Mes
8、sage, MsgBoxStyle.Critical, “Write 失败“)FinallyIf Writer IsNot Nothing Then Writer.Close()End TryEnd IfEnd SubPrivate Sub BtnRead_Click(ByVal sender As System.Object, ByVale As System.EventArgs) Handles BtnRead.ClickIf ComboBox1.Text = “ ThenMsgBox(“请选择 U 盘盘符!“, MsgBoxStyle.Exclamation, “Warn“)ElseDi
9、m Reader As StreamReader = NothingTryDim fileName As String = ComboBox1.Text + “Test.txt“Reader = New StreamReader(fileName)MsgBox(“Read from “ + fileName + vbCrLf + Reader.ReadToEnd, MsgBoxStyle.Information, “Info“)Catch ex As ExceptionMsgBox(ex.Message, MsgBoxStyle.Critical, “Read 失败“)FinallyIf Reader IsNot Nothing Then Reader.Close()End TryEnd IfEnd SubEnd Class注意:Winform 需要两个 Button、一个 Combox、一个 ListBox 控件。