2016-09-21 75 views
0

我目前正在爲我的學校項目做一個申請。 當用戶將USB驅動器插入 USB端口時,我怎樣才能使應用程序,登錄表將自動彈出詢問用戶登錄第一,如果成功,用戶可以使用USB驅動器(USB端口將啓用)。 即時通訊使用的是Windows 7,vb.net 2010年,我的應用程序名稱是PutLock和這個程序 將被安裝在驅動器C.謝謝^^如何讓我的應用程序在USB驅動器插入時自動運行?

+1

你可以使用代碼來檢測,如果USB連接,並從那裏:[鏈接]( http://stackoverflow.com/questions/23225170/failed-to-detect-usb) –

+1

這篇文章是一個有趣的閱讀,這可能是一些幫助:[鏈接](http://www.samlogic.net/articles /autorun-usb-flash-drive.htm) –

+0

非常感謝! – asa

回答

0

我在互聯網上找到這個解決方案,這個代碼是不是我的! 但該死的,它的作品真的很好:

Imports System.Runtime.InteropServices 

公共類Form1中

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 

末級

+0

顯然這裏程序檢查插入USB驅動器上現有的「測試」文件..你需要更改你的代碼爲你需要的 – Rovo93

+0

非常感謝你的代碼。當然我會改變它^^ – asa

相關問題