elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Duda]¿Como detectar los usb con vb 2013?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Duda]¿Como detectar los usb con vb 2013?  (Leído 6,593 veces)
josiko12

Desconectado Desconectado

Mensajes: 3


Ver Perfil
[Duda]¿Como detectar los usb con vb 2013?
« en: 28 Enero 2014, 20:37 pm »

Queria saber como puedo hacer que un programa me detecte los puertos usb del pc vereis estoy haciendo un proyecto llamado proyecto porque no esta terminado bueno el caso esque lo que tengo es:
Bastantes CheckBoxes:Lo tengo para que al ser marcados sean copiados los archivos al USB con la instruccion "Filecopy" de vb mas o menos el codigo yo creo que seria:
Código
  1. If (CheckBox2.Checked = True) Then
  2.            FileCopy("\Pack Instalador de FreeMC Boot 1.93\APPS\OPNPS2Loader 0.9.2 +GSM.ELF"),("Aqui iria la variable que se crearia para el USB no¿?")
  3.        End If
Label:Que tengo escrito "Seleccione su Unidad USB"
Button:Que lo tengo para formatear el USB con el comando "Format" del vb
el codigo creo que seria:

Código
  1. Format(IO.DriveInfo.GetDrives)
No se si estaria bien ya que yo soy un iniciado empece hace poco en vb

ComboBox:Con todas las posibles letras de un USB o memoria extraible y yo lo que quiero hacer es que detecte su USB y que al pulsar el Button se formatee en fat32(Aqui el codigo no lo puedo mostrar porque os lo estoy preguntando a vosotros)

P.D Si hiciese falta un .dll me gustaria que me ayudarais  ;D ;D ;D ;D

GRACIAS


En línea

Car0nte

Desconectado Desconectado

Mensajes: 21


Ver Perfil
Re: [Duda]¿Como detectar los usb con vb 2013?
« Respuesta #1 en: 16 Febrero 2014, 14:32 pm »

Buenas,

Creo que para eso tan concreto deberías utilizar el shell de Windows y de ahí a DISKPART. El usuario debería escoger la letra correspondiente al dispositivo USB y a partir de ahí ponerte a trabajar.

Si no te suena nada de esto "empóllate" Process (hay un montón de información sobre el tema). Podías redireccionar los datos de la shell para recogerlos en tu aplicación, empezando por ej ..

Código:
Dim MiProceso as Process
MiProceso.UseShellExecute = False
MiProceso.StartInfo.RedirectStandardOutput = True
MiProceso.StartInfo.RedirectStandardError = True
MiProceso.StartInfo.CreateNoWindow = True
MiProceso.StartInfo.FileName = "diskpart"
MiProceso.StartInfo.Arguments = "losquesean"

No es una respuesta exacta pero para lo que tú buscas puede servir y es un lugar por donde empezar

Saludos

Editado:

Para listar, aunque requiere permisos administrativos, existe otra forma:
Código:
Fsutil fsinfo drives

Ah! antes se me olvido que la función Format no sirve para formatear unidades. Es para dar formato a ciertos tipos de datos (por ejemplo para dar un determinado formato fechas, números, etc)

Para lo que quieres tú, la manera más sencilla es utiliza la shell de Windows.. es decir, si lo puedes hacer desde la cmd lo podrás hacer desde tu aplicación con todas las ventajas que conlleva


« Última modificación: 16 Febrero 2014, 16:55 pm por Car0nte » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [Duda]¿Como detectar los usb con vb 2013?
« Respuesta #2 en: 17 Febrero 2014, 21:53 pm »

Hola

Citar
Código:
...FileCopy...
1er consejo:
Sé que lo más facil cuando uno se introduce a un lenguaje nuevo es copiar códigos de Internet, pero es que es lo peor que puedes hacer, porque el 90% de lo que vas a encontrar es morralla de VB6.
Podrías dejar de utilizar métodos poco eficientes de VB6 (técnicas de programación de hace una década), pues estamos en VB.NET.
Infórmate sobre los métodos de la Class System.IO.File, tiene todo lo que necesitas para esa y las demás tareas que precisas :P.

Citar
Código:
...Format(IO.DriveInfo.GetDrives)...
2ndo consejo:
Acostúmbrate a usar MSDN para buscar información sencilla o como mínimo haz uso de la característica Intellisense en VisualStudio... y así verías (como ya te han dicho) que el método format es para formatear un string.

Citar
ComboBox:Con todas las posibles letras de un USB o memoria extraible
3er consejo:
Intenta hacer soluciones eficientes, no sencillas.
Por ejemplo: ¿Porque mostrar todas las letras de unidades si solo habrá 3 o 4 ocupadas, y solo 1 o 2 de ellas serán USB? ...pues entonces muestra sólamente las letras ocupadas por dispositivos extraibles.



Citar
Para lo que quieres tú, la manera más sencilla es utiliza la shell de Windows.. es decir, si lo puedes hacer desde la cmd lo podrás hacer desde tu aplicación con todas las ventajas que conlleva

Car0nte, me parece una pena esa forma de pensar.

Si ustedes quieren usar la CMD para las tareas, ¿porque no están programando sus aplicaicones en Batch? :P





¿Como obtener los dispositivos extraibles que están conectados al sistema?
:

Código
  1.    ' GetDrivesOfType
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
  7.    '
  8.    ' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
  9.    '     MsgBox(Drive.Name)
  10.    ' Next Drive
  11.    '
  12.    ''' <summary>
  13.    ''' Get all the connected drives of the given type.
  14.    ''' </summary>
  15.    ''' <param name="DriveType">Indicates the type of the drive.</param>
  16.    ''' <returns>System.IO.DriveInfo[].</returns>
  17.    Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
  18.  
  19.        Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
  20.                Where Drive.DriveType = DriveType).ToArray
  21.  
  22.    End Function

EDITO:
Código de regalo para que optimices ese combobox :)...
Código
  1.        Dim Removables As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Removable)
  2.        ComboBox1.DataSource = Removables





¿Como formatear una unidad?:

Puedes hacerlo con la WinAPI, el método SHFormatDrive,
o bien puedes recurrir al comando Format de la CMD...,
o puedes usar WMI para invocar el método Format de la Class Win32_Volume

Yo he preferido hacer el siguiente código utilizando WMI en lugar de P/Invokear, por estas razones:
1. Permite especificar el tamaño del cluster.
2. Permite especificar la nueva etiqueta del disco formateado.
3. El método retorna mayor información de errores.

( Pero lo cierto es que no he testeado mi código en profundidad para formatear, solo en una VM, por eso no puedo asegurar que funcione corréctamente )

Código
  1.    ' Format Drive
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' FormatDrive("Z")
  6.    ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
  7.  
  8.    ''' <summary>
  9.    ''' Indicates the possible partition filesystem for Windows OS.
  10.    ''' </summary>
  11.    Public Enum DriveFileSystem As Integer
  12.  
  13.        ' The numeric values indicates the max volume-label character-length for each filesystem.
  14.  
  15.        ''' <summary>
  16.        ''' NTFS FileSystem.
  17.        ''' </summary>
  18.        NTFS = 32
  19.  
  20.        ''' <summary>
  21.        ''' FAT16 FileSystem.
  22.        ''' </summary>
  23.        FAT16 = 11
  24.  
  25.        ''' <summary>
  26.        ''' FAT32 FileSystem.
  27.        ''' </summary>
  28.        FAT32 = FAT16
  29.  
  30.    End Enum
  31.  
  32.    ''' <summary>
  33.    ''' Formats a drive.
  34.    ''' For more info see here:
  35.    ''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
  36.    ''' </summary>
  37.    ''' <param name="DriveLetter">
  38.    ''' Indicates the drive letter to format.
  39.    ''' </param>
  40.    ''' <param name="FileSystem">
  41.    ''' Indicates the filesystem format to use for this volume.
  42.    ''' The default is "NTFS".
  43.    ''' </param>
  44.    ''' <param name="QuickFormat">
  45.    ''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
  46.    ''' without scanning the disk for bad sectors.
  47.    ''' Use this option only if the disk has been previously formatted,
  48.    ''' and you know that the disk is not damaged.
  49.    ''' The default is <c>true</c>.
  50.    ''' </param>
  51.    ''' <param name="ClusterSize">
  52.    ''' Disk allocation unit size—cluster size.
  53.    ''' All of the filesystems organizes the hard disk based on cluster size,
  54.    ''' which represents the smallest amount of disk space that can be allocated to hold a file.
  55.    ''' The smaller the cluster size you use, the more efficiently your disk stores information.
  56.    ''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
  57.    ''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
  58.    ''' For general use, the default settings are strongly recommended.
  59.    ''' </param>
  60.    ''' <param name="VolumeLabel">
  61.    ''' Indicates the Label to use for the new volume.
  62.    ''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
  63.    ''' and up to 32 characters for NTFS filesystem volumes.
  64.    ''' </param>
  65.    ''' <param name="EnableCompression">Not implemented.</param>
  66.    ''' <returns>
  67.    ''' 0  = Success.
  68.    ''' 1  = Unsupported file system.
  69.    ''' 2  = Incompatible media in drive.
  70.    ''' 3  = Access denied.
  71.    ''' 4  = Call canceled.
  72.    ''' 5  = Call cancellation request too late.
  73.    ''' 6  = Volume write protected.
  74.    ''' 7  = Volume lock failed.
  75.    ''' 8  = Unable to quick format.
  76.    ''' 9  = Input/Output (I/O) error.
  77.    ''' 10 = Invalid volume label.
  78.    ''' 11 = No media in drive.
  79.    ''' 12 = Volume is too small.
  80.    ''' 13 = Volume is too large.
  81.    ''' 14 = Volume is not mounted.
  82.    ''' 15 = Cluster size is too small.
  83.    ''' 16 = Cluster size is too large.
  84.    ''' 17 = Cluster size is beyond 32 bits.
  85.    ''' 18 = Unknown error.
  86.    ''' </returns>
  87.    Public Function FormatDrive(ByVal DriveLetter As Char,
  88.                                Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
  89.                                Optional ByVal QuickFormat As Boolean = True,
  90.                                Optional ByVal ClusterSize As Integer = Nothing,
  91.                                Optional ByVal VolumeLabel As String = Nothing,
  92.                                Optional ByVal EnableCompression As Boolean = False) As Integer
  93.  
  94.        ' Volume-label error check.
  95.        If Not String.IsNullOrEmpty(VolumeLabel) Then
  96.  
  97.            If VolumeLabel.Length > FileSystem Then
  98.                Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
  99.                                                  FileSystem.ToString, CStr(FileSystem)))
  100.            End If
  101.  
  102.        End If
  103.  
  104.        Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
  105.                                            Convert.ToString(DriveLetter))
  106.  
  107.        Using WMI As New ManagementObjectSearcher(Query)
  108.  
  109.            Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
  110.                        InvokeMethod("Format",
  111.                                     New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
  112.  
  113.        End Using
  114.  
  115.        Return 18 ' Unknown error.
  116.  
  117.    End Function

« Última modificación: 18 Febrero 2014, 08:38 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [Duda]¿Como detectar los usb con vb 2013?
« Respuesta #3 en: 17 Febrero 2014, 21:55 pm »

( Escribo este doble post justificado porque no cabía el siguiente código, maldito límite de caracteres  :rolleyes: )

¿Como monitorizar la inserción/extracción de dispositivos USB's?:

Si estás corriendo Windows 8 o Win server 2012 entonces puedes usar la Class DeviceWatcher que prácticamente te hace todo el trabajo sucio xD, eso si, es para apps de Metro así que debes referenciar la librería 'WindowsRuntime.dll' y 'Windows.Foundation' en caso de que tu proyecto sea un WinForms/WPF.

De todas formas he ideado este ayudante (bueno, en realidad es un código antiguo que escribí hace tiempo, pero lo he actualizado y mejorado) que no necesita el uso de Windows 8, y en el cual solo tienes que manejar dos eventos, 'DriveInserted' y 'DriveRemoved', más sencillo imposible.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DriveWatcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' ''' <summary>
  13. ' ''' The DriveWatcher instance to monitor USB devices.
  14. ' ''' </summary>
  15. 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
  16.  
  17. ' ''' <summary>
  18. ' ''' Handles the DriveInserted event of the USBMonitor object.
  19. ' ''' </summary>
  20. ' ''' <param name="sender">The source of the event.</param>
  21. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  22. 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
  23.  
  24. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  25.  
  26. '        Dim sb As New System.Text.StringBuilder
  27.  
  28. '        sb.AppendLine("DRIVE CONNECTED!")
  29. '        sb.AppendLine()
  30. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  31. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  32. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  33. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  34. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  35. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  36. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  37. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  38. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  39.  
  40. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  41.  
  42. '    End If
  43.  
  44. 'End Sub
  45.  
  46. ' ''' <summary>
  47. ' ''' Handles the DriveRemoved event of the USBMonitor object.
  48. ' ''' </summary>
  49. ' ''' <param name="sender">The source of the event.</param>
  50. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  51. 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
  52.  
  53. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  54.  
  55. '        Dim sb As New System.Text.StringBuilder
  56.  
  57. '        sb.AppendLine("DRIVE DISCONNECTED!")
  58. '        sb.AppendLine()
  59. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  60. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  61. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  62. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  63. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  64. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  65. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  66. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  67. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  68.  
  69. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  70.  
  71. '    End If
  72.  
  73. 'End Sub
  74.  
  75. #End Region
  76.  
  77. #Region " Imports "
  78.  
  79. Imports System.IO
  80. Imports System.Runtime.InteropServices
  81. Imports System.ComponentModel
  82.  
  83. #End Region
  84.  
  85. ''' <summary>
  86. ''' Device insertion/removal monitor.
  87. ''' </summary>
  88. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  89.  
  90. #Region " Objects "
  91.  
  92.    ''' <summary>
  93.    ''' The current connected drives.
  94.    ''' </summary>
  95.    Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
  96.  
  97.    ''' <summary>
  98.    ''' Indicates the drive letter of the current device.
  99.    ''' </summary>
  100.    Private DriveLetter As Char = Nothing
  101.  
  102.    ''' <summary>
  103.    ''' Indicates the current Drive information.
  104.    ''' </summary>
  105.    Private CurrentDrive As DriveWatcherInfo = Nothing
  106.  
  107.    ''' <summary>
  108.    ''' The form to manage their Windows Messages.
  109.    ''' </summary>
  110.    Private WithEvents form As Form = Nothing
  111.  
  112. #End Region
  113.  
  114. #Region " Events "
  115.  
  116.    ''' <summary>
  117.    ''' Occurs when a drive is inserted.
  118.    ''' </summary>
  119.    Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  120.  
  121.    ''' <summary>
  122.    ''' Occurs when a drive is removed.
  123.    ''' </summary>
  124.    Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  125.  
  126. #End Region
  127.  
  128. #Region " Enumerations "
  129.  
  130.    ''' <summary>
  131.    ''' Notifies an application of a change to the hardware configuration of a device or the computer.
  132.    ''' A window receives this message through its WindowProc function.
  133.    ''' For more info, see here:
  134.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
  135.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
  136.    ''' </summary>
  137.    Private Enum DeviceEvents As Integer
  138.  
  139.        ''' <summary>
  140.        ''' The current configuration has changed, due to a dock or undock.
  141.        ''' </summary>
  142.        Change = &H219
  143.  
  144.        ''' <summary>
  145.        ''' A device or piece of media has been inserted and becomes available.
  146.        ''' </summary>
  147.        Arrival = &H8000
  148.  
  149.        ''' <summary>
  150.        ''' Request permission to remove a device or piece of media.
  151.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  152.        ''' However, any application can deny this request and cancel the operation.
  153.        ''' </summary>
  154.        QueryRemove = &H8001
  155.  
  156.        ''' <summary>
  157.        ''' A request to remove a device or piece of media has been canceled.
  158.        ''' </summary>
  159.        QueryRemoveFailed = &H8002
  160.  
  161.        ''' <summary>
  162.        ''' A device or piece of media is being removed and is no longer available for use.
  163.        ''' </summary>
  164.        RemovePending = &H8003
  165.  
  166.        ''' <summary>
  167.        ''' A device or piece of media has been removed.
  168.        ''' </summary>
  169.        RemoveComplete = &H8004
  170.  
  171.        ''' <summary>
  172.        ''' The type volume
  173.        ''' </summary>
  174.        TypeVolume = &H2
  175.  
  176.    End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.    ''' <summary>
  183.    ''' Indicates information related of a Device.
  184.    ''' ( Replic of System.IO.DriveInfo )
  185.    ''' </summary>
  186.    Public Structure DriveWatcherInfo
  187.  
  188.        ''' <summary>
  189.        ''' Indicates the name of a drive, such as 'C:\'.
  190.        ''' </summary>
  191.        Public Name As String
  192.  
  193.        ''' <summary>
  194.        ''' Indicates the amount of available free space on a drive, in bytes.
  195.        ''' </summary>
  196.        Public AvailableFreeSpace As Long
  197.  
  198.        ''' <summary>
  199.        ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
  200.        ''' </summary>
  201.        Public DriveFormat As String
  202.  
  203.        ''' <summary>
  204.        ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
  205.        ''' </summary>
  206.        Public DriveType As DriveType
  207.  
  208.        ''' <summary>
  209.        ''' Indicates whether a drive is ready.
  210.        ''' </summary>
  211.        Public IsReady As Boolean
  212.  
  213.        ''' <summary>
  214.        ''' Indicates the root directory of a drive.
  215.        ''' </summary>
  216.        Public RootDirectory As String
  217.  
  218.        ''' <summary>
  219.        ''' Indicates the total amount of free space available on a drive, in bytes.
  220.        ''' </summary>
  221.        Public TotalFreeSpace As Long
  222.  
  223.        ''' <summary>
  224.        ''' Indicates the total size of storage space on a drive, in bytes.
  225.        ''' </summary>
  226.        Public TotalSize As Long
  227.  
  228.        ''' <summary>
  229.        ''' Indicates the volume label of a drive.
  230.        ''' </summary>
  231.        Public VolumeLabel As String
  232.  
  233.        ''' <summary>
  234.        ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
  235.        ''' </summary>
  236.        ''' <param name="e">The e.</param>
  237.        Public Sub New(ByVal e As DriveInfo)
  238.  
  239.            Name = e.Name
  240.  
  241.            Select Case e.IsReady
  242.  
  243.                Case True ' Drive is formatted and ready.
  244.                    IsReady = True
  245.                    DriveFormat = e.DriveFormat
  246.                    DriveType = e.DriveType
  247.                    RootDirectory = e.RootDirectory.FullName
  248.                    VolumeLabel = e.VolumeLabel
  249.                    TotalSize = e.TotalSize
  250.                    TotalFreeSpace = e.TotalFreeSpace
  251.                    AvailableFreeSpace = e.AvailableFreeSpace
  252.  
  253.                Case False ' Drive is not formatted so can't retrieve data.
  254.                    IsReady = False
  255.                    DriveFormat = Nothing
  256.                    DriveType = e.DriveType
  257.                    RootDirectory = e.RootDirectory.FullName
  258.                    VolumeLabel = Nothing
  259.                    TotalSize = 0
  260.                    TotalFreeSpace = 0
  261.                    AvailableFreeSpace = 0
  262.  
  263.            End Select ' e.IsReady
  264.  
  265.        End Sub
  266.  
  267.    End Structure
  268.  
  269.    ''' <summary>
  270.    ''' Contains information about a logical volume.
  271.    ''' For more info, see here:
  272.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
  273.    ''' </summary>
  274.    <StructLayout(LayoutKind.Sequential)>
  275.    Private Structure DEV_BROADCAST_VOLUME
  276.  
  277.        ''' <summary>
  278.        ''' The size of this structure, in bytes.
  279.        ''' </summary>
  280.        Public Size As UInteger
  281.  
  282.        ''' <summary>
  283.        ''' Set to DBT_DEVTYP_VOLUME (2).
  284.        ''' </summary>
  285.        Public Type As UInteger
  286.  
  287.        ''' <summary>
  288.        ''' Reserved parameter; do not use this.
  289.        ''' </summary>
  290.        Public Reserved As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' The logical unit mask identifying one or more logical units.
  294.        ''' Each bit in the mask corresponds to one logical drive.
  295.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  296.        ''' </summary>
  297.        Public Mask As UInteger
  298.  
  299.        ''' <summary>
  300.        ''' This parameter can be one of the following values:
  301.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  302.        ''' '0x0002': Indicated logical volume is a network volume.
  303.        ''' </summary>
  304.        Public Flags As UShort
  305.  
  306.    End Structure
  307.  
  308. #End Region
  309.  
  310. #Region " Constructor "
  311.  
  312.    ''' <summary>
  313.    ''' Initializes a new instance of this class.
  314.    ''' </summary>
  315.    ''' <param name="form">The form to assign.</param>
  316.    Public Sub New(ByVal form As Form)
  317.  
  318.        ' Assign the Formulary.
  319.        Me.form = form
  320.  
  321.    End Sub
  322.  
  323. #End Region
  324.  
  325. #Region " Event Handlers "
  326.  
  327.    ''' <summary>
  328.    ''' Assign the handle of the target Form to this NativeWindow,
  329.    ''' necessary to override target Form's WndProc.
  330.    ''' </summary>
  331.    Private Sub SetFormHandle() _
  332.    Handles form.HandleCreated, form.Load, form.Shown
  333.  
  334.        If Not MyBase.Handle.Equals(Me.form.Handle) Then
  335.            MyBase.AssignHandle(Me.form.Handle)
  336.        End If
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Releases the Handle.
  342.    ''' </summary>
  343.    Private Sub OnHandleDestroyed() _
  344.    Handles form.HandleDestroyed
  345.  
  346.        MyBase.ReleaseHandle()
  347.  
  348.    End Sub
  349.  
  350. #End Region
  351.  
  352. #Region " Private Methods "
  353.  
  354.    ''' <summary>
  355.    ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
  356.    ''' </summary>
  357.    ''' <param name="Device">
  358.    ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
  359.    ''' </param>
  360.    ''' <returns>System.Char.</returns>
  361.    Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
  362.  
  363.        Dim DriveLetters As Char() =
  364.            {
  365.            "A", "B", "C", "D", "E", "F", "G", "H", "I",
  366.            "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  367.            "S", "T", "U", "V", "W", "X", "Y", "Z"
  368.            }
  369.  
  370.        Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
  371.  
  372.        For X As Integer = 0 To DeviceID.Length
  373.  
  374.            If DeviceID(X) Then
  375.                Return DriveLetters(X)
  376.            End If
  377.  
  378.        Next X
  379.  
  380.        Return Nothing
  381.  
  382.    End Function
  383.  
  384. #End Region
  385.  
  386. #Region " WndProc"
  387.  
  388.    ''' <summary>
  389.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  390.    ''' </summary>
  391.    ''' <param name="m">
  392.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  393.    ''' </param>
  394.    Protected Overrides Sub WndProc(ByRef m As Message)
  395.  
  396.        Select Case m.Msg
  397.  
  398.            Case DeviceEvents.Change ' The hardware has changed.
  399.  
  400.                ' Transform the LParam pointer into the data structure.
  401.                Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
  402.                    CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
  403.  
  404.                Select Case m.WParam.ToInt32
  405.  
  406.                    Case DeviceEvents.Arrival ' The device is connected.
  407.  
  408.                        ' Get the drive letter of the connected device.
  409.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  410.  
  411.                        ' Get the drive information of the connected device.
  412.                        CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  413.  
  414.                        ' If it's an storage device then...
  415.                        If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
  416.  
  417.                            ' Inform that the device is connected by raising the 'DriveConnected' event.
  418.                            RaiseEvent DriveInserted(Me, CurrentDrive)
  419.  
  420.                            ' Add the connected device to the dictionary, to retrieve info.
  421.                            If Not CurrentDrives.ContainsKey(DriveLetter) Then
  422.  
  423.                                CurrentDrives.Add(DriveLetter, CurrentDrive)
  424.  
  425.                            End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  426.  
  427.                        End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
  428.  
  429.                    Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
  430.  
  431.                        ' Get the letter of the current device being removed.
  432.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  433.  
  434.                        ' If the current device being removed is not in the dictionary then...
  435.                        If Not CurrentDrives.ContainsKey(DriveLetter) Then
  436.  
  437.                            ' Get the device information of the current device being removed.
  438.                            CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  439.  
  440.                            ' Add the current device to the dictionary,
  441.                            ' to retrieve info before lost it after fully-removal.
  442.                            CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
  443.  
  444.                        End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  445.  
  446.                    Case DeviceEvents.RemoveComplete
  447.  
  448.                        ' Get the letter of the removed device.
  449.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  450.  
  451.                        ' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
  452.                        RaiseEvent DriveRemoved(Me, CurrentDrive)
  453.  
  454.                        ' If the removed device is in the dictionary then...
  455.                        If CurrentDrives.ContainsKey(DriveLetter) Then
  456.  
  457.                            ' Remove the device from the dictionary.
  458.                            CurrentDrives.Remove(DriveLetter)
  459.  
  460.                        End If ' CurrentDrives.ContainsKey(DriveLetter)
  461.  
  462.                End Select ' m.WParam.ToInt32
  463.  
  464.        End Select ' m.Msg
  465.  
  466.        MyBase.WndProc(m) ' Return Message to base message handler.
  467.  
  468.    End Sub
  469.  
  470. #End Region
  471.  
  472. #Region " Hidden methods "
  473.  
  474.    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
  475.    ' NOTE: The methods can be re-enabled at any-time if needed.
  476.  
  477.    ''' <summary>
  478.    ''' Assigns a handle to this window.
  479.    ''' </summary>
  480.    <EditorBrowsable(EditorBrowsableState.Never)>
  481.    Public Shadows Sub AssignHandle()
  482.    End Sub
  483.  
  484.    ''' <summary>
  485.    ''' Creates a window and its handle with the specified creation parameters.
  486.    ''' </summary>
  487.    <EditorBrowsable(EditorBrowsableState.Never)>
  488.    Public Shadows Sub CreateHandle()
  489.    End Sub
  490.  
  491.    ''' <summary>
  492.    ''' Creates an object that contains all the relevant information required
  493.    ''' to generate a proxy used to communicate with a remote object.
  494.    ''' </summary>
  495.    <EditorBrowsable(EditorBrowsableState.Never)>
  496.    Public Shadows Sub CreateObjRef()
  497.    End Sub
  498.  
  499.    ''' <summary>
  500.    ''' Invokes the default window procedure associated with this window.
  501.    ''' </summary>
  502.    <EditorBrowsable(EditorBrowsableState.Never)>
  503.    Public Shadows Sub DefWndProc()
  504.    End Sub
  505.  
  506.    ''' <summary>
  507.    ''' Destroys the window and its handle.
  508.    ''' </summary>
  509.    <EditorBrowsable(EditorBrowsableState.Never)>
  510.    Public Shadows Sub DestroyHandle()
  511.    End Sub
  512.  
  513.    ''' <summary>
  514.    ''' Determines whether the specified object is equal to the current object.
  515.    ''' </summary>
  516.    <EditorBrowsable(EditorBrowsableState.Never)>
  517.    Public Shadows Sub Equals()
  518.    End Sub
  519.  
  520.    ''' <summary>
  521.    ''' Serves as the default hash function.
  522.    ''' </summary>
  523.    <EditorBrowsable(EditorBrowsableState.Never)>
  524.    Public Shadows Sub GetHashCode()
  525.    End Sub
  526.  
  527.    ''' <summary>
  528.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  529.    ''' </summary>
  530.    <EditorBrowsable(EditorBrowsableState.Never)>
  531.    Public Shadows Sub GetLifetimeService()
  532.    End Sub
  533.  
  534.    ''' <summary>
  535.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  536.    ''' </summary>
  537.    <EditorBrowsable(EditorBrowsableState.Never)>
  538.    Public Shadows Sub InitializeLifetimeService()
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Releases the handle associated with this window.
  543.    ''' </summary>
  544.    <EditorBrowsable(EditorBrowsableState.Never)>
  545.    Public Shadows Sub ReleaseHandle()
  546.    End Sub
  547.  
  548.    ''' <summary>
  549.    ''' Gets the handle for this window.
  550.    ''' </summary>
  551.    <EditorBrowsable(EditorBrowsableState.Never)>
  552.    Public Shadows Property Handle()
  553.  
  554. #End Region
  555.  
  556. #Region " IDisposable "
  557.  
  558.    ''' <summary>
  559.    ''' To detect redundant calls when disposing.
  560.    ''' </summary>
  561.    Private IsDisposed As Boolean = False
  562.  
  563.    ''' <summary>
  564.    ''' Prevent calls to methods after disposing.
  565.    ''' </summary>
  566.    ''' <exception cref="System.ObjectDisposedException"></exception>
  567.    Private Sub DisposedCheck()
  568.        If Me.IsDisposed Then
  569.            Throw New ObjectDisposedException(Me.GetType().FullName)
  570.        End If
  571.    End Sub
  572.  
  573.    ''' <summary>
  574.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  575.    ''' </summary>
  576.    Public Sub Dispose() Implements IDisposable.Dispose
  577.        Dispose(True)
  578.        GC.SuppressFinalize(Me)
  579.    End Sub
  580.  
  581.    ''' <summary>
  582.    ''' Releases unmanaged and - optionally - managed resources.
  583.    ''' </summary>
  584.    ''' <param name="IsDisposing">
  585.    ''' <c>true</c> to release both managed and unmanaged resources;
  586.    ''' <c>false</c> to release only unmanaged resources.
  587.    ''' </param>
  588.  
  589.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  590.  
  591.        If Not Me.IsDisposed Then
  592.  
  593.            If IsDisposing Then
  594.                Me.form = Nothing
  595.                MyBase.ReleaseHandle()
  596.                MyBase.DestroyHandle()
  597.            End If
  598.  
  599.        End If
  600.  
  601.        Me.IsDisposed = True
  602.  
  603.    End Sub
  604.  
  605. #End Region
  606.  
  607. End Class

Saludos.
« Última modificación: 18 Febrero 2014, 08:40 am por Eleкtro » En línea

Car0nte

Desconectado Desconectado

Mensajes: 21


Ver Perfil
Re: [Duda]¿Como detectar los usb con vb 2013?
« Respuesta #4 en: 18 Febrero 2014, 04:04 am »

Citar
Citar
Para lo que quieres tú, la manera más sencilla es utiliza la shell de Windows.. es decir, si lo puedes hacer desde la cmd lo podrás hacer desde tu aplicación con todas las ventajas que conlleva

Car0nte, me parece una pena esa forma de pensar.

Si ustedes quieren usar la CMD para las tareas, ¿porque no están programando sus aplicaicones en Batch? :P

Por supuesto que hay mejores maneras de hacer las cosas. Está claro. Pero dado el nivel de la persona que pregunta, pienso que empezar a usar NET o lenguaje que sea aprovechándose de los pocos (o muchos) conocimientos que tenga de MSDOS, es una buena manera de empezar y de que se pique. Cuando aprenda un poco ya tendrá tiempo de liarse con System.IO, librerías y todo lo demás. Para empezar a hacer casas es mejor empezar por la caseta del perro que por el Museo Guggenheim. Le puede pasar como a Santiago Calatrava y caérsele a pedazos xD

Además, aunque éste no es el caso, NET tiene algunas deficiencias (cada vez menos) especialemnte trabajando a bajo nivel. Hay veces que no te queda más remedio que tirar de shell de Windows o WSS, no entiendo por qué, pero es un hecho.

Por ejemplo, (y tiene que ver con esto), la creación de shortcuts, hasta no hace mucho no estaba incluido y tocaba tirar de WSS  sin IntelliSense y con todas sus desventajas  (creo que por eso me daba error, en este equipo tengo VS2010 y tú lo habías hecho con el 12 ó 13, además suelo trabajar con Framework 3.5 por tema de compatibilidades. Lo sé porque me he bajado algunos de tus trabajos y no puedo ver la source (los hay realmente buenos) El que quiera saber por qué que pinche aquí y vea la relación con este post)

Dicho esto esto, está claro que siempre será más eficaz utilizar los recursos propios de NET por mil razones (eficiencia, rapidez, gestión de memoria, etc, etc) (aunque no lo parezca leyendo mis últimos post)  ;D

Saludos

EDITADO:

Citar
el 90% de lo que vas a encontrar es morralla de VB6.

Creo que no es muy justo tratar de morralla al trabajo que han hecho otros con el mismo trabajo (o más) y que conste que no tengo prácticamente ni idea de VB6 (yo soy del paleolítico.. cuando dejé el Basic se llamaba BASICA, no había Internet ni casi documentación y los foros se hacían con señales de humo  :laugh:). Piensa que dentrode unos años lo que tú con mucho esfuerzo has hecho, aunque sea antiguo, no será basura.
« Última modificación: 18 Febrero 2014, 04:39 am por Car0nte » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [Duda]¿Como detectar los usb con vb 2013?
« Respuesta #5 en: 18 Febrero 2014, 05:00 am »

Has justificado bien todo lo que has dicho y te doy la razón, solo quiero comentar una cosa:

Citar
Creo que no es muy justo tratar de morralla al trabajo que han hecho otros con el mismo trabajo (o más)

Claro que no, mi intención no era dar a pensar eso, si un trabajo está echo en vb5/vb6 con los métodos de vb, a mi me parece perfecto.

Pero, en VB.NET, la diferencia entre algo que está echo en 5 minutos copiando códigos de VB6, y algo que está echo en horas, dias, semanas o meses se aprecia la diferencia.

Creo que has visto muy pocos source-codes desarrollados en VB.NET que básicamente todos los métodos usados son de VB6 (por desgracia yo he visto más de los que quisiera), te aseguro que hay demasiados, he visto gente muy experta que siguen mal acostumbrados a esas prácticas,
e incluso el tipo de declaración de APIS que usan (Declare function...), eso me parece lamentable hacerlo en VB.NET porque no aprovechan ninguna ventaja de .NET Framework como el tipo de declaraciones de APIS que he comentado (dllimport),
así pues, una persona que trabaja duro y le pone ganas no haría esas cosas, es puro copy/paste de VB6, a eso me refiero con morralla,
es una mania que yo tengo, pero lo llevo mal ver códigos de .NET vb6-stylized (como se suele decir por ahí...).

Saludos!
« Última modificación: 18 Febrero 2014, 05:05 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines