Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#7261
No creo que exista un software dedicado a una tarea tan "singular", pero de todas formas no es dificil conseguirlo escribiendo un Script/Programa, partiendo cada linea de texto usando como delimitador el caracter de 'espacio'.

Slaudos!
#7262
         [RichTextBox] Colorize Words

         Busca coincidencias de texto y las colorea.


Código (vbnet) [Seleccionar]
    ' Colorize Words
    ' ( By Elektro )
    '
    ' Usage Examples:
    '
    ' ColorizeWord(RichTextBox1, "Hello", True,
    '              Color.Red, Color.Black,
    '              New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic))
    '
    ' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False,
    '               ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing)

    ''' <summary>
    ''' Find a word on a RichTextBox and colorizes each match.
    ''' </summary>
    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
    ''' <param name="Word">Indicates the word to colorize.</param>
    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
    ''' <param name="ForeColor">Indicates the text color.</param>
    ''' <param name="BackColor">Indicates the background color.</param>
    ''' <param name="Font">Indicates the text font.</param>
    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
    Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox,
                                  ByVal Word As String,
                                  Optional ByVal IgnoreCase As Boolean = False,
                                  Optional ByVal ForeColor As Color = Nothing,
                                  Optional ByVal BackColor As Color = Nothing,
                                  Optional ByVal [Font] As Font = Nothing) As Boolean

        ' Find all the word matches.
        Dim Matches As System.Text.RegularExpressions.MatchCollection =
            System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word,
                                                         If(IgnoreCase,
                                                            System.Text.RegularExpressions.RegexOptions.IgnoreCase,
                                                            System.Text.RegularExpressions.RegexOptions.None))

        ' If no matches then return.
        If Not Matches.Count <> 0 Then
            Return False
        End If

        ' Set the passed Parameter values.
        If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor
        If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor
        If [Font] Is Nothing Then [Font] = [RichTextBox].Font

        ' Store the current caret position to restore it at the end.
        Dim CaretPosition As Integer = [RichTextBox].SelectionStart

        ' Suspend the control layout to work quicklly.
        [RichTextBox].SuspendLayout()

        ' Colorize each match.
        For Each Match As System.Text.RegularExpressions.Match In Matches

            [RichTextBox].Select(Match.Index, Match.Length)
            [RichTextBox].SelectionColor = ForeColor
            [RichTextBox].SelectionBackColor = BackColor
            [RichTextBox].SelectionFont = [Font]

        Next Match

        ' Restore the caret position.
        [RichTextBox].Select(CaretPosition, 0)

        ' Restore the control layout.
        [RichTextBox].ResumeLayout()

        ' Return successfully
        Return True

    End Function

    ''' <summary>
    ''' Find multiple words on a RichTextBox and colorizes each match.
    ''' </summary>
    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
    ''' <param name="Words">Indicates the words to colorize.</param>
    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
    ''' <param name="ForeColor">Indicates the text color.</param>
    ''' <param name="BackColor">Indicates the background color.</param>
    ''' <param name="Font">Indicates the text font.</param>
    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
    Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox,
                                   ByVal Words As String(),
                                   Optional ByVal IgnoreCase As Boolean = False,
                                   Optional ByVal ForeColor As Color = Nothing,
                                   Optional ByVal BackColor As Color = Nothing,
                                   Optional ByVal [Font] As Font = Nothing) As Boolean

        Dim Success As Boolean = False

        For Each Word As String In Words
            Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font])
        Next Word

        Return Success

    End Function





[ListView] Remove Duplicates

Elimina Items duplicados de un Listview, comparando un índice de subitem específico.

Código (vbnet) [Seleccionar]
    ' Remove ListView Duplicates
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1)
    ' RemoveListViewDuplicates(Items, 0)   
    '
    ''' <summary>
    ''' Removes duplicated items from a Listview.
    ''' </summary>
    ''' <param name="Items">
    ''' Indicates the items collection.
    ''' </param>
    ''' <param name="SubitemCompare">
    ''' Indicates the subitem column to compare duplicates.
    ''' </param>
    Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
                                         ByVal SubitemCompare As Integer)

        ' Suspend the layout on the Control that owns the Items collection.
        Items.Item(0).ListView.SuspendLayout()

        ' Get the duplicated Items.
        Dim Duplicates As ListViewItem() =
            Items.Cast(Of ListViewItem)().
            GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
            Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
            SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
            Skip(1).
            ToArray()

        ' Delete the duplicated Items.
        For Each Item As ListViewItem In Duplicates
            Items.Remove(Item)
        Next Item

        ' Resume the layout on the Control that owns the Items collection.
        Items.Item(0).ListView.ResumeLayout()

        Duplicates = Nothing

    End Sub





Formatea un dispositivo

Código (vbnet) [Seleccionar]
    ' Format Drive
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' FormatDrive("Z")
    ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))

    ''' <summary>
    ''' Indicates the possible HardDisk filesystem's for Windows OS.
    ''' </summary>
    Public Enum DriveFileSystem As Integer

        ' NOTE:
        ' *****
        ' The numeric values just indicates the max harddisk 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
#7263
Porfavor, usa las etiquetas de código... respeta las normas del foro.

PD: Sobre el código, no se Java.

Saludos!
#7264
Programación General / Re: Batch y Registros
18 Febrero 2014, 20:59 PM
El caracter "%" es un símbolo reservado por el sistema (para las %variables%), pero, además de esto, el espacio escrito en la ruta del regedit (%20) entra en conflicto con la variable especial "%2" de Batch, por eso te da error.

Para corregirlo, encierra el string y escapa el caracter conflictivo (duplicándolo):

Código (dos) [Seleccionar]
@Echo OFF

Set "Output=%HomeDrive%\Registros\Cliente.reg"
Set "Key=HKCU\Software\SimonTatham\PuTTY\Sessions\CIA%%20-%%20Cliente"

Reg Export "%Key%" "%Output%"

Pause&Exit


Saludos
#7265
Cita de: rapbyone en 15 Febrero 2014, 20:00 PMNo entiendo cual será el problema

El método SendKeys.Send envía las pulsaciones del teclado a la ventana activa, ¿has tenido eso en cuenta?.

Muestra el código restante, es imposible poder ayudarte sin ver donde cometes el fallo (si hubiera alguno) o como estás usándolo.






De todas formas una alternativa para esta tarea que requieres quizás podría ser usando el método SendInput

He estado haciendo mi implementación de SendInput, todavía está muy verde, no lo he acabado, falta documentación por añadir y mucho código que escribir, y quizás bugs que corregir, pero para lo que tu precisas puedes testear este código.

Modo de empleo:
Código (vbnet) [Seleccionar]

   Private Sub Test() Handles Button1.Click

       AppActivate(Process.GetProcessesByName("notepad").First.Id)
       Dim Result As Integer = SendInputs.SendKeys(Keys.Insert,  BlockInput:=False)

       ' Dim Result2 As Integer = SendInputs.SendKey(Convert.ToChar(Keys.Enter))
       ' Dim Result2 As Integer = SendInputs.SendKey("x"c)

#If DEBUG Then
       MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
#End If

   End Sub


Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 02-17-2014
' ***********************************************************************
' <copyright file="SendInputs.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Imports "

Imports System.Runtime.InteropServices
Imports System.ComponentModel

#End Region

''' <summary>
'''
''' </summary>
Public Class SendInputs

#Region " P/Invoke "

   Friend Class NativeMethods

#Region " Methods "

       ''' <summary>
       ''' Blocks keyboard and mouse input events from reaching applications.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="fBlockIt">
       ''' The function's purpose.
       ''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
       ''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
       ''' </param>
       ''' <returns>
       ''' If the function succeeds, the return value is nonzero.
       ''' If input is already blocked, the return value is zero.
       ''' </returns>
       ''' <remarks>
       ''' Note that only the thread that blocked input can successfully unblock input.
       ''' </remarks>
       <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
       SetLastError:=True)>
       Friend Shared Function BlockInput(
              ByVal fBlockIt As Boolean
       ) As Integer
       End Function

       ''' <summary>
       ''' Synthesizes keystrokes, mouse motions, and button clicks.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="nInputs">
       ''' Indicates the number of structures in the pInputs array.
       ''' </param>
       ''' <param name="pInputs">
       ''' Indicates an Array of 'INPUT' structures.
       ''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
       ''' </param>
       ''' <param name="cbSize">
       ''' The size, in bytes, of an 'INPUT' structure.
       ''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
       ''' </param>
       ''' <returns>
       ''' The function returns the number of events that it successfully
       ''' inserted into the keyboard or mouse input stream.
       ''' If the function returns zero, the input was already blocked by another thread.
       ''' </returns>
       <DllImport("user32.dll", SetLastError:=True)>
       Friend Shared Function SendInput(
              ByVal nInputs As Integer,
              <MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
              ByVal cbSize As Integer
       ) As Integer
       End Function

#End Region

#Region " Enumerations "

       ''' <summary>
       ''' VirtualKey codes.
       ''' </summary>
       Friend Enum VirtualKeys As Short

           ''' <summary>
           ''' The Shift key.
           ''' VK_SHIFT
           ''' </summary>
           SHIFT = &H10S

           ''' <summary>
           ''' The DEL key.
           ''' VK_DELETE
           ''' </summary>
           DELETE = 46S

           ''' <summary>
           ''' The ENTER key.
           ''' VK_RETURN
           ''' </summary>
           [RETURN] = 13S

       End Enum

       ''' <summary>
       ''' The type of the input event.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
       Friend Enum InputType As Integer

           ''' <summary>
           ''' The event is a mouse event.
           ''' Use the mi structure of the union.
           ''' </summary>
           Mouse = 0

           ''' <summary>
           ''' The event is a keyboard event.
           ''' Use the ki structure of the union.
           ''' </summary>
           Keyboard = 1

           ''' <summary>
           ''' The event is a hardware event.
           ''' Use the hi structure of the union.
           ''' </summary>
           Hardware = 2

       End Enum

       ''' <summary>
       ''' Specifies various aspects of a keystroke.
       ''' This member can be certain combinations of the following values.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Enumeration used for 'dwFlags' parameter of 'KEYBDINPUT ' structure")>
       <Flags>
       Friend Enum KeyboardInput_Flags As Integer

           ''' <summary>
           ''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
           ''' </summary>
           ExtendedKey = &H1

           ''' <summary>
           ''' If specified, the key is being pressed.
           ''' </summary>
           KeyDown = &H0

           ''' <summary>
           ''' If specified, the key is being released.
           ''' If not specified, the key is being pressed.
           ''' </summary>
           KeyUp = &H2

           ''' <summary>
           ''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
           ''' </summary>
           ScanCode = &H8

           ''' <summary>
           ''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
           ''' The 'wVk' parameter must be '0'.
           ''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
           ''' </summary>
           Unicode = &H4

       End Enum

#End Region

#Region " Structures "

       ''' <summary>
       ''' Used by 'SendInput' function
       ''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
       <StructLayout(LayoutKind.Explicit)>
       Friend Structure INPUT

           ' ******
           '  NOTE
           ' ******
           ' Field offset for 32 bit machine: 4
           ' Field offset for 64 bit machine: 8

           ''' <summary>
           ''' The type of the input event.
           ''' </summary>
           <FieldOffset(0)>
           Public type As InputType

           ''' <summary>
           ''' The information about a simulated mouse event.
           ''' </summary>
           <FieldOffset(8)>
           Public mi As MOUSEINPUT

           ''' <summary>
           ''' The information about a simulated keyboard event.
           ''' </summary>
           <FieldOffset(8)>
           Public ki As KEYBDINPUT

           ''' <summary>
           ''' The information about a simulated hardware event.
           ''' </summary>
           <FieldOffset(8)>
           Public hi As HARDWAREINPUT

       End Structure

       ''' <summary>
       ''' Contains information about a simulated mouse event.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Structure used for 'mi' parameter of 'INPUT' structure")>
       Friend Structure MOUSEINPUT

           ''' <summary>
           '''
           ''' </summary>
           Public dx As Integer

           ''' <summary>
           '''
           ''' </summary>
           Public dy As Integer

           ''' <summary>
           '''
           ''' </summary>
           Public mouseData As Integer

           ''' <summary>
           '''
           ''' </summary>
           Public dwFlags As Integer

           ''' <summary>
           '''
           ''' </summary>
           Public time As Integer

           ''' <summary>
           '''
           ''' </summary>
           Public dwExtraInfo As IntPtr

       End Structure

       ''' <summary>
       ''' Contains information about a simulated keyboard event.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Structure used for 'ki' parameter of 'INPUT' structure")>
       Friend Structure KEYBDINPUT

           ''' <summary>
           ''' A virtual-key code.
           ''' The code must be a value in the range '1' to '254'.
           ''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
           ''' </summary>
           Public wVk As Short

           ''' <summary>
           ''' A hardware scan code for the key.
           ''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
           ''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
           ''' </summary>
           Public wScan As Short

           ''' <summary>
           ''' Specifies various aspects of a keystroke.
           ''' </summary>
           Public dwFlags As KeyboardInput_Flags

           ''' <summary>
           ''' The time stamp for the event, in milliseconds.
           ''' If this parameter is '0', the system will provide its own time stamp.
           ''' </summary>
           Public time As Integer

           ''' <summary>
           ''' An additional value associated with the keystroke.
           ''' Use the 'GetMessageExtraInfo' function to obtain this information.
           ''' </summary>
           Public dwExtraInfo As IntPtr

       End Structure

       ''' <summary>
       ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Structure used for 'hi' parameter of 'INPUT' structure")>
       Friend Structure HARDWAREINPUT

           ''' <summary>
           ''' The message generated by the input hardware.
           ''' </summary>
           Public uMsg As Integer

           ''' <summary>
           ''' The low-order word of the lParam parameter for uMsg.
           ''' </summary>
           Public wParamL As Short

           ''' <summary>
           ''' The high-order word of the lParam parameter for uMsg.
           ''' </summary>
           Public wParamH As Short

       End Structure

#End Region

   End Class

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Sends a keystroke.
   ''' </summary>
   ''' <param name="key">
   ''' Indicates the keystroke to simulate.
   ''' </param>
   ''' <param name="BlockInput">
   ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
   ''' </param>
   ''' <returns>
   ''' The function returns the number of events that it successfully
   ''' inserted into the keyboard or mouse input stream.
   ''' If the function returns zero, the input was already blocked by another thread.
   ''' </returns>
   Public Shared Function SendKey(ByVal key As Char,
                                  Optional BlockInput As Boolean = False) As Integer

       ' Block Keyboard and mouse.
       If BlockInput Then NativeMethods.BlockInput(True)

       ' The inputs structures to send.
       Dim Inputs As New List(Of NativeMethods.INPUT)

       ' The current input to add into the Inputs list.
       Dim CurrentInput As New NativeMethods.INPUT

       ' Determines whether a character is an alphabetic letter.
       Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)

       ' Determines whether a character is an uppercase alphabetic letter.
       Dim IsUpperCase As Boolean =
           (key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)

       ' Determines whether the CapsLock key is pressed down.
       Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock

       ' Set the passed key to upper-case.
       If IsAlphabetic AndAlso Not IsUpperCase Then
           key = Convert.ToChar(key.ToString.ToUpper)
       End If

       ' If character is UpperCase and CapsLock is pressed down,
       ' OrElse character is not UpperCase and CapsLock is not pressed down.
       If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
       OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
       OrElse (Not IsAlphabetic) Then

           ' Hold the character key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = Convert.ToInt16(CChar(key))
               .ki.dwFlags = 0
           End With : Inputs.Add(CurrentInput)

           ' Release the character key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = Convert.ToInt16(CChar(key))
               .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
           End With : Inputs.Add(CurrentInput)

           ' If character is UpperCase and CapsLock is not pressed down,
           ' OrElse character is not UpperCase and CapsLock is pressed down.
       ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
       OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then

           ' Hold the Shift key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = NativeMethods.VirtualKeys.SHIFT
               .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
           End With : Inputs.Add(CurrentInput)

           ' Hold the character key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = Convert.ToInt16(CChar(key))
               .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
           End With : Inputs.Add(CurrentInput)

           ' Release the character key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = Convert.ToInt16(CChar(key))
               .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
           End With : Inputs.Add(CurrentInput)

           ' Release the Shift key.
           With CurrentInput
               .type = NativeMethods.InputType.Keyboard
               .ki.wVk = NativeMethods.VirtualKeys.SHIFT
               .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
           End With : Inputs.Add(CurrentInput)

       End If ' UpperCase And My.Computer.Keyboard.CapsLock is...

       ' Send the input key.
       Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
                                      Marshal.SizeOf(GetType(NativeMethods.INPUT)))

       ' Unblock Keyboard and mouse.
       If BlockInput Then NativeMethods.BlockInput(False)

   End Function

   ''' <summary>
   ''' Sends a keystroke.
   ''' </summary>
   ''' <param name="key">
   ''' Indicates the keystroke to simulate.
   ''' </param>
   ''' <param name="BlockInput">
   ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
   ''' </param>
   ''' <returns>
   ''' The function returns the number of events that it successfully
   ''' inserted into the keyboard or mouse input stream.
   ''' If the function returns zero, the input was already blocked by another thread.
   ''' </returns>
   Public Shared Function SendKey(ByVal key As Keys,
                                  Optional BlockInput As Boolean = False) As Integer

       Return SendKey(Convert.ToChar(key), BlockInput)

   End Function

   ''' <summary>
   ''' Sends a string.
   ''' </summary>
   ''' <param name="String">
   ''' Indicates the string to send.
   ''' </param>
   ''' <param name="BlockInput">
   ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
   ''' </param>
   ''' <returns>
   ''' The function returns the number of events that it successfully
   ''' inserted into the keyboard or mouse input stream.
   ''' If the function returns zero, the input was already blocked by another thread.
   ''' </returns>
   Public Shared Function SendKeys(ByVal [String] As String,
                                   Optional BlockInput As Boolean = False) As Integer

       Dim SuccessCount As Integer = 0

       ' Block Keyboard and mouse.
       If BlockInput Then NativeMethods.BlockInput(True)

       For Each c As Char In [String]
           SuccessCount += SendKey(c, BlockInput:=False)
       Next c

       ' Unblock Keyboard and mouse.
       If BlockInput Then NativeMethods.BlockInput(False)

       Return SuccessCount

   End Function

#End Region

End Class


Saludos
#7266
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!
#7267
obtener los dispositivos extraibles que están conectados al sistema

Código (vbnet) [Seleccionar]
        ' 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





monitorizar la inserción/extracción de dispositivos

Código (vbnet) [Seleccionar]
' ***********************************************************************
' 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
#7268
( 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 (vbnet) [Seleccionar]
' ***********************************************************************
' 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.
#7269
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, 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.

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?
:

Código (vbnet) [Seleccionar]

   ' 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 :)...
Código (vbnet) [Seleccionar]

       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,
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 (vbnet) [Seleccionar]
   ' 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


#7270
La verdad es que si la intención es sólamente crear un shortcut pues no vale la pena añadir a tu proyecto una Class de 1.000 lineas de código y taladrarse la cabeza investigando en MSDN sobre esas interfaces y demás, lo típico es hacerlo como has mostrado tú, aunque prácticamente es lo mismo, pero el código lo escribí hace ya tiempo para manejar más que la creación de shortcuts, en realidad la idea fue resolver shortcuts y lo de la creación/modificación de shortcuts lo añadí como algo secundario y para evitar dependencias innecesarias de WScript.

Cita de: Car0nte en 16 Febrero 2014, 17:52 PMPD: Elektro, estoy probando tu código y me da problemas con ShortcutManager.ShortcutInfo Será cosa mía... echaré un vistazo en msdn.

Me resulta extraño porque el miembro 'ShortcutInfo' sólamente es una Class con propiedades públicas,
en cada propiedad debes especificar los valores del shortcut que quieres crear (aunque algunas de las propiedades como 'IsFile' o 'IsFolder' no importa lo que pongas porque las uso para otros métodos) que luego toma el método 'CreateShortcut', al que le añadí un 'Overload' para poder pasarle un objeto 'ShortcutInfo', pero si te da problemas, en lugar de pasarle un 'ShortcutInfo' puedes pasarle todos los parámetros del shortcut de forma manual: Shortcutmanager.createshortcut("C:\Nuevo link.lnk", etc...)

No me imagino que tipo de problema te puede causar la Class 'ShortcutInfo' porque como ya digo son propiedades y nada más,
si quieres mostrar el código para ver de que forma lo estás utilizando y detallar la excepción/error de compilación o en tiempo de ejecución (si es que hubiera alguna excepción)...

un saludo!