【问题标题】:How to make my application run automatically when USB drive is plugged in?如何让我的应用程序在插入 USB 驱动器时自动运行?
【发布时间】:2016-09-21 07:39:31
【问题描述】:

我目前正在为我的学校项目申请。 当用户将 USB 驱动器插入时,我如何制作应用程序 usb 端口,登录表单会自动弹出询问用户 首先登录,如果成功,用户可以使用 USB 驱动器(将启用 USB 端口)。 我使用的是 windows 7,vb.net 2010,我的应用程序名称是 PutLock 和这个应用程序 将安装在C盘。谢谢^^

【问题讨论】:

  • 您可以使用代码来检测 USB 是否已连接并从那里开始:link
  • 这篇文章读起来很有趣,可能会有所帮助:link

标签: vb.net visual-studio-2010 usb-drive


【解决方案1】:

我在互联网上找到了这个解决方案,这个代码不是我的! 但是该死的,它真的很好用:

Imports System.Runtime.InteropServices

公开课表1

Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = &H8000
Private Const DBT_DEVTYP_VOLUME As Integer = &H2

'Device information structure
Public Structure DEV_BROADCAST_HDR
    Public dbch_size As Int32
    Public dbch_devicetype As Int32
    Public dbch_reserved As Int32
End Structure

'Volume information Structure
Private Structure DEV_BROADCAST_VOLUME
    Public dbcv_size As Int32
    Public dbcv_devicetype As Int32
    Public dbcv_reserved As Int32
    Public dbcv_unitmask As Int32
    Public dbcv_flags As Int16
End Structure

'Function that gets the drive letter from the unit mask
Private Function GetDriveLetterFromMask(ByRef Unit As Int32) As Char
    For i As Integer = 0 To 25
        If Unit = (2 ^ i) Then
            Return Chr(Asc("A") + i)
        End If
    Next
End Function

'Override message processing to check for the DEVICECHANGE message
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_DEVICECHANGE Then
        If CInt(m.WParam) = DBT_DEVICEARRIVAL Then
            Dim DeviceInfo As DEV_BROADCAST_HDR
            DeviceInfo = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_HDR)), DEV_BROADCAST_HDR)
            If DeviceInfo.dbch_devicetype = DBT_DEVTYP_VOLUME Then
                Dim Volume As DEV_BROADCAST_VOLUME
                Volume = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
                Dim DriveLetter As String = (GetDriveLetterFromMask(Volume.dbcv_unitmask) & ":\")
                If IO.File.Exists(IO.Path.Combine(DriveLetter, "test.txt")) Then
                    '<<<< The test file has been found >>>>
                    MessageBox.Show("Found test file")
                Else
                    '<<<< Test file has not been found >>>>
                    MessageBox.Show("Could not find test file")
                End If
            End If
        End If
    End If
    'Process all other messages as normal
    MyBase.WndProc(m)
End Sub

结束类

【讨论】:

  • 显然这里程序会检查插入 USB 驱动器上的现有“测试”文件。您需要根据需要更改代码
  • 非常感谢您提供的代码。我当然会改变它^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2013-12-03
相关资源
最近更新 更多