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:
If (CheckBox2.Checked = True) Then
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¿?")
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:
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
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 ..
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:
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
Hola
Citar...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 (http://msdn.microsoft.com/en-us/library/system.io.file_methods%28v=vs.110%29.aspx), tiene todo lo que necesitas para esa y las demás tareas que precisas :P.
Citar...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 (http://msdn.microsoft.com/en-us/library/59bz1f0h%28v=vs.90%29.aspx).
CitarComboBox: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.
CitarPara 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?:
' GetDrivesOfType
' ( By Elektro )
'
' Usage Examples:
'
' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
'
' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
' MsgBox(Drive.Name)
' Next Drive
'
''' <summary>
''' Get all the connected drives of the given type.
''' </summary>
''' <param name="DriveType">Indicates the type of the drive.</param>
''' <returns>System.IO.DriveInfo[].</returns>
Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
Where Drive.DriveType = DriveType).ToArray
End Function
EDITO:Código de regalo para que optimices ese combobox :)...
Dim Removables As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Removable)
ComboBox1.DataSource = Removables
¿Como formatear una unidad?:
Puedes hacerlo con la WinAPI, el método
SHFormatDrive (http://msdn.microsoft.com/en-us/library/bb762169%28VS.85%29.aspx),
o bien puedes recurrir al comando Format de la CMD...,
o puedes usar WMI para invocar el método
Format (http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx) de la Class
Win32_Volume (http://msdn.microsoft.com/en-us/library/gg196703%28v=vs.85%29.aspx)
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 )
' Format Drive
' ( By Elektro )
'
' Usage Examples:
' FormatDrive("Z")
' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
''' <summary>
''' Indicates the possible partition filesystem for Windows OS.
''' </summary>
Public Enum DriveFileSystem As Integer
' The numeric values indicates the max volume-label character-length for each filesystem.
''' <summary>
''' NTFS FileSystem.
''' </summary>
NTFS = 32
''' <summary>
''' FAT16 FileSystem.
''' </summary>
FAT16 = 11
''' <summary>
''' FAT32 FileSystem.
''' </summary>
FAT32 = FAT16
End Enum
''' <summary>
''' Formats a drive.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
''' </summary>
''' <param name="DriveLetter">
''' Indicates the drive letter to format.
''' </param>
''' <param name="FileSystem">
''' Indicates the filesystem format to use for this volume.
''' The default is "NTFS".
''' </param>
''' <param name="QuickFormat">
''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
''' without scanning the disk for bad sectors.
''' Use this option only if the disk has been previously formatted,
''' and you know that the disk is not damaged.
''' The default is <c>true</c>.
''' </param>
''' <param name="ClusterSize">
''' Disk allocation unit size—cluster size.
''' All of the filesystems organizes the hard disk based on cluster size,
''' which represents the smallest amount of disk space that can be allocated to hold a file.
''' The smaller the cluster size you use, the more efficiently your disk stores information.
''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
''' For general use, the default settings are strongly recommended.
''' </param>
''' <param name="VolumeLabel">
''' Indicates the Label to use for the new volume.
''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
''' and up to 32 characters for NTFS filesystem volumes.
''' </param>
''' <param name="EnableCompression">Not implemented.</param>
''' <returns>
''' 0 = Success.
''' 1 = Unsupported file system.
''' 2 = Incompatible media in drive.
''' 3 = Access denied.
''' 4 = Call canceled.
''' 5 = Call cancellation request too late.
''' 6 = Volume write protected.
''' 7 = Volume lock failed.
''' 8 = Unable to quick format.
''' 9 = Input/Output (I/O) error.
''' 10 = Invalid volume label.
''' 11 = No media in drive.
''' 12 = Volume is too small.
''' 13 = Volume is too large.
''' 14 = Volume is not mounted.
''' 15 = Cluster size is too small.
''' 16 = Cluster size is too large.
''' 17 = Cluster size is beyond 32 bits.
''' 18 = Unknown error.
''' </returns>
Public Function FormatDrive(ByVal DriveLetter As Char,
Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
Optional ByVal QuickFormat As Boolean = True,
Optional ByVal ClusterSize As Integer = Nothing,
Optional ByVal VolumeLabel As String = Nothing,
Optional ByVal EnableCompression As Boolean = False) As Integer
' Volume-label error check.
If Not String.IsNullOrEmpty(VolumeLabel) Then
If VolumeLabel.Length > FileSystem Then
Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
FileSystem.ToString, CStr(FileSystem)))
End If
End If
Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
Convert.ToString(DriveLetter))
Using WMI As New ManagementObjectSearcher(Query)
Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
InvokeMethod("Format",
New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
End Using
Return 18 ' Unknown error.
End Function
( 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 (http://msdn.microsoft.com/library/windows/apps/br225446) 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.
' ***********************************************************************
' Author : Elektro
' Modified : 02-17-2014
' ***********************************************************************
' <copyright file="DriveWatcher.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
' ''' <summary>
' ''' The DriveWatcher instance to monitor USB devices.
' ''' </summary>
'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
' ''' <summary>
' ''' Handles the DriveInserted event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE CONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
' ''' <summary>
' ''' Handles the DriveRemoved event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE DISCONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
#End Region
#Region " Imports "
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.ComponentModel
#End Region
''' <summary>
''' Device insertion/removal monitor.
''' </summary>
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
#Region " Objects "
''' <summary>
''' The current connected drives.
''' </summary>
Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
''' <summary>
''' Indicates the drive letter of the current device.
''' </summary>
Private DriveLetter As Char = Nothing
''' <summary>
''' Indicates the current Drive information.
''' </summary>
Private CurrentDrive As DriveWatcherInfo = Nothing
''' <summary>
''' The form to manage their Windows Messages.
''' </summary>
Private WithEvents form As Form = Nothing
#End Region
#Region " Events "
''' <summary>
''' Occurs when a drive is inserted.
''' </summary>
Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
''' <summary>
''' Occurs when a drive is removed.
''' </summary>
Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
#End Region
#Region " Enumerations "
''' <summary>
''' Notifies an application of a change to the hardware configuration of a device or the computer.
''' A window receives this message through its WindowProc function.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
''' </summary>
Private Enum DeviceEvents As Integer
''' <summary>
''' The current configuration has changed, due to a dock or undock.
''' </summary>
Change = &H219
''' <summary>
''' A device or piece of media has been inserted and becomes available.
''' </summary>
Arrival = &H8000
''' <summary>
''' Request permission to remove a device or piece of media.
''' This message is the last chance for applications and drivers to prepare for this removal.
''' However, any application can deny this request and cancel the operation.
''' </summary>
QueryRemove = &H8001
''' <summary>
''' A request to remove a device or piece of media has been canceled.
''' </summary>
QueryRemoveFailed = &H8002
''' <summary>
''' A device or piece of media is being removed and is no longer available for use.
''' </summary>
RemovePending = &H8003
''' <summary>
''' A device or piece of media has been removed.
''' </summary>
RemoveComplete = &H8004
''' <summary>
''' The type volume
''' </summary>
TypeVolume = &H2
End Enum
#End Region
#Region " Structures "
''' <summary>
''' Indicates information related of a Device.
''' ( Replic of System.IO.DriveInfo )
''' </summary>
Public Structure DriveWatcherInfo
''' <summary>
''' Indicates the name of a drive, such as 'C:\'.
''' </summary>
Public Name As String
''' <summary>
''' Indicates the amount of available free space on a drive, in bytes.
''' </summary>
Public AvailableFreeSpace As Long
''' <summary>
''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
''' </summary>
Public DriveFormat As String
''' <summary>
''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
''' </summary>
Public DriveType As DriveType
''' <summary>
''' Indicates whether a drive is ready.
''' </summary>
Public IsReady As Boolean
''' <summary>
''' Indicates the root directory of a drive.
''' </summary>
Public RootDirectory As String
''' <summary>
''' Indicates the total amount of free space available on a drive, in bytes.
''' </summary>
Public TotalFreeSpace As Long
''' <summary>
''' Indicates the total size of storage space on a drive, in bytes.
''' </summary>
Public TotalSize As Long
''' <summary>
''' Indicates the volume label of a drive.
''' </summary>
Public VolumeLabel As String
''' <summary>
''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
''' </summary>
''' <param name="e">The e.</param>
Public Sub New(ByVal e As DriveInfo)
Name = e.Name
Select Case e.IsReady
Case True ' Drive is formatted and ready.
IsReady = True
DriveFormat = e.DriveFormat
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = e.VolumeLabel
TotalSize = e.TotalSize
TotalFreeSpace = e.TotalFreeSpace
AvailableFreeSpace = e.AvailableFreeSpace
Case False ' Drive is not formatted so can't retrieve data.
IsReady = False
DriveFormat = Nothing
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = Nothing
TotalSize = 0
TotalFreeSpace = 0
AvailableFreeSpace = 0
End Select ' e.IsReady
End Sub
End Structure
''' <summary>
''' Contains information about a logical volume.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
''' </summary>
<StructLayout(LayoutKind.Sequential)>
Private Structure DEV_BROADCAST_VOLUME
''' <summary>
''' The size of this structure, in bytes.
''' </summary>
Public Size As UInteger
''' <summary>
''' Set to DBT_DEVTYP_VOLUME (2).
''' </summary>
Public Type As UInteger
''' <summary>
''' Reserved parameter; do not use this.
''' </summary>
Public Reserved As UInteger
''' <summary>
''' The logical unit mask identifying one or more logical units.
''' Each bit in the mask corresponds to one logical drive.
''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
''' </summary>
Public Mask As UInteger
''' <summary>
''' This parameter can be one of the following values:
''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
''' '0x0002': Indicated logical volume is a network volume.
''' </summary>
Public Flags As UShort
End Structure
#End Region
#Region " Constructor "
''' <summary>
''' Initializes a new instance of this class.
''' </summary>
''' <param name="form">The form to assign.</param>
Public Sub New(ByVal form As Form)
' Assign the Formulary.
Me.form = form
End Sub
#End Region
#Region " Event Handlers "
''' <summary>
''' Assign the handle of the target Form to this NativeWindow,
''' necessary to override target Form's WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated, form.Load, form.Shown
If Not MyBase.Handle.Equals(Me.form.Handle) Then
MyBase.AssignHandle(Me.form.Handle)
End If
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
MyBase.ReleaseHandle()
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
''' </summary>
''' <param name="Device">
''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
''' </param>
''' <returns>System.Char.</returns>
Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
Dim DriveLetters As Char() =
{
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
}
Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
For X As Integer = 0 To DeviceID.Length
If DeviceID(X) Then
Return DriveLetters(X)
End If
Next X
Return Nothing
End Function
#End Region
#Region " WndProc"
''' <summary>
''' Invokes the default window procedure associated with this window to process messages for this Window.
''' </summary>
''' <param name="m">
''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
''' </param>
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case DeviceEvents.Change ' The hardware has changed.
' Transform the LParam pointer into the data structure.
Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
Select Case m.WParam.ToInt32
Case DeviceEvents.Arrival ' The device is connected.
' Get the drive letter of the connected device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Get the drive information of the connected device.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' If it's an storage device then...
If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
' Inform that the device is connected by raising the 'DriveConnected' event.
RaiseEvent DriveInserted(Me, CurrentDrive)
' Add the connected device to the dictionary, to retrieve info.
If Not CurrentDrives.ContainsKey(DriveLetter) Then
CurrentDrives.Add(DriveLetter, CurrentDrive)
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
' Get the letter of the current device being removed.
DriveLetter = GetDriveLetter(CurrentWDrive)
' If the current device being removed is not in the dictionary then...
If Not CurrentDrives.ContainsKey(DriveLetter) Then
' Get the device information of the current device being removed.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' Add the current device to the dictionary,
' to retrieve info before lost it after fully-removal.
CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
Case DeviceEvents.RemoveComplete
' Get the letter of the removed device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
RaiseEvent DriveRemoved(Me, CurrentDrive)
' If the removed device is in the dictionary then...
If CurrentDrives.ContainsKey(DriveLetter) Then
' Remove the device from the dictionary.
CurrentDrives.Remove(DriveLetter)
End If ' CurrentDrives.ContainsKey(DriveLetter)
End Select ' m.WParam.ToInt32
End Select ' m.Msg
MyBase.WndProc(m) ' Return Message to base message handler.
End Sub
#End Region
#Region " Hidden methods "
' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
' NOTE: The methods can be re-enabled at any-time if needed.
''' <summary>
''' Assigns a handle to this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub AssignHandle()
End Sub
''' <summary>
''' Creates a window and its handle with the specified creation parameters.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateHandle()
End Sub
''' <summary>
''' Creates an object that contains all the relevant information required
''' to generate a proxy used to communicate with a remote object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateObjRef()
End Sub
''' <summary>
''' Invokes the default window procedure associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DefWndProc()
End Sub
''' <summary>
''' Destroys the window and its handle.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DestroyHandle()
End Sub
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub Equals()
End Sub
''' <summary>
''' Serves as the default hash function.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetHashCode()
End Sub
''' <summary>
''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetLifetimeService()
End Sub
''' <summary>
''' Obtains a lifetime service object to control the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub InitializeLifetimeService()
End Sub
''' <summary>
''' Releases the handle associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub ReleaseHandle()
End Sub
''' <summary>
''' Gets the handle for this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Property Handle()
#End Region
#Region " IDisposable "
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
Private IsDisposed As Boolean = False
''' <summary>
''' Prevent calls to methods after disposing.
''' </summary>
''' <exception cref="System.ObjectDisposedException"></exception>
Private Sub DisposedCheck()
If Me.IsDisposed Then
Throw New ObjectDisposedException(Me.GetType().FullName)
End If
End Sub
''' <summary>
''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
''' <summary>
''' Releases unmanaged and - optionally - managed resources.
''' </summary>
''' <param name="IsDisposing">
''' <c>true</c> to release both managed and unmanaged resources;
''' <c>false</c> to release only unmanaged resources.
''' </param>
Protected Sub Dispose(ByVal IsDisposing As Boolean)
If Not Me.IsDisposed Then
If IsDisposing Then
Me.form = Nothing
MyBase.ReleaseHandle()
MyBase.DestroyHandle()
End If
End If
Me.IsDisposed = True
End Sub
#End Region
End Class
Saludos.
CitarCitar
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í (http://foro.elhacker.net/programacion_general/anadir_a_favoritos_del_panel_de_navegacion_del_explorer-t408871.0.html) 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:
Citarel 90% de lo que vas a encontrar es morralla de VB6.
Creo que no es muy justo tratar de morralla (http://lema.rae.es/drae/?val=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.
Has justificado bien todo lo que has dicho y te doy la razón, solo quiero comentar una cosa:
CitarCreo 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!