Santana Posted September 29, 2012 at 11:55 PM Report #477100 Posted September 29, 2012 at 11:55 PM Como faço para que o meu programa faça backup de uma pasta para o pendrive imediatamente ao detectar o pendrive?
apocsantos Posted September 30, 2012 at 12:19 AM Report #477107 Posted September 30, 2012 at 12:19 AM Boa noite, Aqui fica um exemplo de como detectar um mass storage device (pen-drive, cartão de memória, etc...) Imports System.Management Public Class MeuForm Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher Public USBDriveName As String Public USBDriveLetter As String Private Sub MeuForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load StartDetection() End Sub Private Sub MeuForm_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed m_MediaConnectWatcher.Stop() m_MediaConnectWatcher.Dispose() End Sub Public Sub StartDetection() Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'") m_MediaConnectWatcher = New ManagementEventWatcher m_MediaConnectWatcher.Query = query2 m_MediaConnectWatcher.Start() End Sub Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived Dim mbo As ManagementBaseObject Dim obj As ManagementBaseObject mbo = CType(e.NewEvent, ManagementBaseObject) obj = CType(mbo("TargetInstance"), ManagementBaseObject) Select Case mbo.ClassPath.ClassName Case "__InstanceCreationEvent" If obj.Item("InterfaceType").ToString = "USB" Then USBDriveName = obj.Item("Caption").ToString USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString) MessageBox.Show(USBDriveName & " (Drive " & USBDriveLetter & ") foi ligada aà porta USB") End If Case "__InstanceDeletionEvent" If obj.Item("InterfaceType").ToString = "USB" Then MessageBox.Show(USBDriveName & " foi removida. " & USBDriveLetter & " encontra-se inacessivel.") If obj.Item("Caption").ToString = USBDriveName Then USBDriveLetter = "" USBDriveName = "" End If End If Case Else MessageBox.Show("Não: " & obj.Item("Caption").ToString) End Select End Sub Private Function GetDriveLetterFromDisk(ByVal Name As String) As String Dim oq_part, oq_disk As ObjectQuery Dim mos_part, mos_disk As ManagementObjectSearcher Dim obj_part, obj_disk As ManagementObject Dim ans As String = "" Name = Replace(Name, "\", "\\") oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition") mos_part = New ManagementObjectSearcher(oq_part) For Each obj_part In mos_part.Get() oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition") mos_disk = New ManagementObjectSearcher(oq_disk) For Each obj_disk In mos_disk.Get() ans &= obj_disk.Item("Name").ToString & "," Next Next Return ans.Trim(","c) End Function 'thanks my friend, It was nice of you to help out at this time in the night! May the cofee be with you! Cordiais cumprimentos, Apocsantos "A paciência é uma das coisas que se aprendeu na era do 48k" O respeito é como a escrita de código, uma vez perdido, dificilmente se retoma o habito"
Santana Posted September 30, 2012 at 12:53 PM Author Report #477159 Posted September 30, 2012 at 12:53 PM Tá dando erro acerca do "ManagementEventWatcher": Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
apocsantos Posted October 1, 2012 at 04:26 PM Report #477328 Posted October 1, 2012 at 04:26 PM Boa tarde, Que erro ?? Podes transcrever para aqui o erro ? Cordiais cumprimentos, Apocsantos "A paciência é uma das coisas que se aprendeu na era do 48k" O respeito é como a escrita de código, uma vez perdido, dificilmente se retoma o habito"
Santana Posted October 1, 2012 at 08:24 PM Author Report #477349 Posted October 1, 2012 at 08:24 PM Pois então! Aqui estão todos os erros mostrados, lembrando que alguns repetiram algumas vezes: => Error 1 Type 'ManagementEventWatcher' is not defined. => Error 2 Character is not valid. => Error 4 'query2' is not declared. It may be inaccessible due to its protection level. => Error 5 Type 'System.Management.EventArrivedEventArgs' is not defined. => Error 10 'amp' is not declared. It may be inaccessible due to its protection level. => Error 16 Type 'ObjectQuery' is not defined. => Error 17 Type 'ManagementObjectSearcher' is not defined. => Error 18 Type 'ManagementObject' is not defined. => Error 24 Method arguments must be enclosed in parentheses. Ansioso pela vossa ajuda! Saudações: Ailton Morais
apocsantos Posted October 2, 2012 at 11:17 AM Report #477424 Posted October 2, 2012 at 11:17 AM Bom dia, Que versão da .netFramework estás a usar ? Acabei de testar com VS 2012 FrameWork 4.5 sem qualquer problema. Apenas tive de completar o end class que faltava. Imports System.Management Public Class MeuForm Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher Public USBDriveName As String Public USBDriveLetter As String Private Sub MeuForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load StartDetection() End Sub Private Sub MeuForm_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed m_MediaConnectWatcher.Stop() m_MediaConnectWatcher.Dispose() End Sub Public Sub StartDetection() Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'") m_MediaConnectWatcher = New ManagementEventWatcher m_MediaConnectWatcher.Query = query2 m_MediaConnectWatcher.Start() End Sub Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived Dim mbo As ManagementBaseObject Dim obj As ManagementBaseObject mbo = CType(e.NewEvent, ManagementBaseObject) obj = CType(mbo("TargetInstance"), ManagementBaseObject) Select Case mbo.ClassPath.ClassName Case "__InstanceCreationEvent" If obj.Item("InterfaceType").ToString = "USB" Then USBDriveName = obj.Item("Caption").ToString USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString) MessageBox.Show(USBDriveName & " (Drive " & USBDriveLetter & ") foi ligada aà porta USB") End If Case "__InstanceDeletionEvent" If obj.Item("InterfaceType").ToString = "USB" Then MessageBox.Show(USBDriveName & " foi removida. " & USBDriveLetter & " encontra-se inacessivel.") If obj.Item("Caption").ToString = USBDriveName Then USBDriveLetter = "" USBDriveName = "" End If End If Case Else MessageBox.Show("Não: " & obj.Item("Caption").ToString) End Select End Sub Private Function GetDriveLetterFromDisk(ByVal Name As String) As String Dim oq_part, oq_disk As ObjectQuery Dim mos_part, mos_disk As ManagementObjectSearcher Dim obj_part, obj_disk As ManagementObject Dim ans As String = "" Name = Replace(Name, "\", "\\") oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition") mos_part = New ManagementObjectSearcher(oq_part) For Each obj_part In mos_part.Get() oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition") mos_disk = New ManagementObjectSearcher(oq_disk) For Each obj_disk In mos_disk.Get() ans &= obj_disk.Item("Name").ToString & "," Next Next Return ans.Trim(","c) End Function 'thanks my friend, It was nice of you to help out at this time in the night! May the cofee be with you! End Class Cordiais cumprimentos, Apocsantos "A paciência é uma das coisas que se aprendeu na era do 48k" O respeito é como a escrita de código, uma vez perdido, dificilmente se retoma o habito"
Santana Posted October 2, 2012 at 02:53 PM Author Report #477440 Posted October 2, 2012 at 02:53 PM Desculpe!!! Eu estava usando VB.NET 2010, mas depois testei em um outro PC com VS 2012 e deu exatamente os mesmos erros. Desculpe eu sou iniciante e não esplicar bem o problema, so sei que esta mostrando erro acerca do ManagementEventWatcher. 😞
Hitmanpt Posted October 2, 2012 at 09:11 PM Report #477489 Posted October 2, 2012 at 09:11 PM (edited) De facto há aqui algum problema... Pk eu no VS2012 .NET4.5 dá-me este erro "Type 'ManagementEventWatcher' is not defined. " Tenta antes este... Não está tão organizado mas é o que eu uso e funciona Imports System.IO Imports System.Threading Imports System.Runtime.InteropServices Imports System.Management Public Class Form1 #Region "Const" Private Const WM_DEVICECHANGE As Integer = &H219 Private Const DBT_DEVICEARRIVAL As Integer = &H8000 Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004 Private Const DBT_DEVTYP_VOLUME As Integer = &H2 #End Region Private Structure DEV_BROADCAST_VOLUME Dim Dbcv_Size As Integer Dim Dbcv_Devicetype As Integer Dim Dbcv_Reserved As Integer Dim Dbcv_Unitmask As Integer Dim Dbcv_Flags As Short End Structure Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message) On Error Resume Next If M.Msg = WM_DEVICECHANGE Then Select Case M.WParam Case DBT_DEVICEARRIVAL Dim DevType As Integer = Marshal.ReadInt32(M.LParam, 4) If DevType = DBT_DEVTYP_VOLUME Then Dim Vol As New DEV_BROADCAST_VOLUME Vol = Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME)) If Vol.Dbcv_Flags = 0 Then For i As Integer = 0 To 20 If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then Dim Usb As String = Chr(65 + i) + ":\" 'Faz o que quiseres quando ligas uma pen Exit For End If Next End If End If Case DBT_DEVICEREMOVECOMPLETE Dim DevType As Integer = Marshal.ReadInt32(M.LParam, 4) If DevType = DBT_DEVTYP_VOLUME Then Dim Vol As New DEV_BROADCAST_VOLUME Vol = Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME)) If Vol.Dbcv_Flags = 0 Then For i As Integer = 0 To 20 If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then Dim Usb As String = Chr(65 + i) + ":\" 'Pen Desligada Coloca o que queres que o programa faça Exit For End If Next End If End If End Select End If MyBase.WndProc(M) End Sub End Class a variável USB dá-te a letra atribuída á unidade Edited October 2, 2012 at 09:12 PM by Windows Dragon
Santana Posted October 2, 2012 at 09:59 PM Author Report #477495 Posted October 2, 2012 at 09:59 PM Pôôwww!!! Muito obrigado cara, deu certo e obrigado tb ao apocsantos. Valeuuuu
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now