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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


  Mostrar Mensajes
Páginas: 1 ... 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 [741] 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 ... 1236
7401  Programación / Programación General / Re: Batch y Registros en: 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
  1. @Echo OFF
  2.  
  3. Set "Output=%HomeDrive%\Registros\Cliente.reg"
  4. Set "Key=HKCU\Software\SimonTatham\PuTTY\Sessions\CIA%%20-%%20Cliente"
  5.  
  6. Reg Export "%Key%" "%Output%"
  7.  
  8. Pause&Exit

Saludos
7402  Programación / .NET (C#, VB.NET, ASP) / Re: Vb.net simular presion tecla INSERT en: 18 Febrero 2014, 08:31 am
No 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
  1.    Private Sub Test() Handles Button1.Click
  2.  
  3.        AppActivate(Process.GetProcessesByName("notepad").First.Id)
  4.        Dim Result As Integer = SendInputs.SendKeys(Keys.Insert,  BlockInput:=False)
  5.  
  6.        ' Dim Result2 As Integer = SendInputs.SendKey(Convert.ToChar(Keys.Enter))
  7.        ' Dim Result2 As Integer = SendInputs.SendKey("x"c)
  8.  
  9. #If DEBUG Then
  10.        MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
  11. #End If
  12.  
  13.    End Sub

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SendInputs.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Runtime.InteropServices
  13. Imports System.ComponentModel
  14.  
  15. #End Region
  16.  
  17. ''' <summary>
  18. '''
  19. ''' </summary>
  20. Public Class SendInputs
  21.  
  22. #Region " P/Invoke "
  23.  
  24.    Friend Class NativeMethods
  25.  
  26. #Region " Methods "
  27.  
  28.        ''' <summary>
  29.        ''' Blocks keyboard and mouse input events from reaching applications.
  30.        ''' For more info see here:
  31.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
  32.        ''' </summary>
  33.        ''' <param name="fBlockIt">
  34.        ''' The function's purpose.
  35.        ''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
  36.        ''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
  37.        ''' </param>
  38.        ''' <returns>
  39.        ''' If the function succeeds, the return value is nonzero.
  40.        ''' If input is already blocked, the return value is zero.
  41.        ''' </returns>
  42.        ''' <remarks>
  43.        ''' Note that only the thread that blocked input can successfully unblock input.
  44.        ''' </remarks>
  45.        <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
  46.        SetLastError:=True)>
  47.        Friend Shared Function BlockInput(
  48.               ByVal fBlockIt As Boolean
  49.        ) As Integer
  50.        End Function
  51.  
  52.        ''' <summary>
  53.        ''' Synthesizes keystrokes, mouse motions, and button clicks.
  54.        ''' For more info see here:
  55.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
  56.        ''' </summary>
  57.        ''' <param name="nInputs">
  58.        ''' Indicates the number of structures in the pInputs array.
  59.        ''' </param>
  60.        ''' <param name="pInputs">
  61.        ''' Indicates an Array of 'INPUT' structures.
  62.        ''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
  63.        ''' </param>
  64.        ''' <param name="cbSize">
  65.        ''' The size, in bytes, of an 'INPUT' structure.
  66.        ''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
  67.        ''' </param>
  68.        ''' <returns>
  69.        ''' The function returns the number of events that it successfully
  70.        ''' inserted into the keyboard or mouse input stream.
  71.        ''' If the function returns zero, the input was already blocked by another thread.
  72.        ''' </returns>
  73.        <DllImport("user32.dll", SetLastError:=True)>
  74.        Friend Shared Function SendInput(
  75.               ByVal nInputs As Integer,
  76.               <MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
  77.               ByVal cbSize As Integer
  78.        ) As Integer
  79.        End Function
  80.  
  81. #End Region
  82.  
  83. #Region " Enumerations "
  84.  
  85.        ''' <summary>
  86.        ''' VirtualKey codes.
  87.        ''' </summary>
  88.        Friend Enum VirtualKeys As Short
  89.  
  90.            ''' <summary>
  91.            ''' The Shift key.
  92.            ''' VK_SHIFT
  93.            ''' </summary>
  94.            SHIFT = &H10S
  95.  
  96.            ''' <summary>
  97.            ''' The DEL key.
  98.            ''' VK_DELETE
  99.            ''' </summary>
  100.            DELETE = 46S
  101.  
  102.            ''' <summary>
  103.            ''' The ENTER key.
  104.            ''' VK_RETURN
  105.            ''' </summary>
  106.            [RETURN] = 13S
  107.  
  108.        End Enum
  109.  
  110.        ''' <summary>
  111.        ''' The type of the input event.
  112.        ''' For more info see here:
  113.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  114.        ''' </summary>
  115.        <Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
  116.        Friend Enum InputType As Integer
  117.  
  118.            ''' <summary>
  119.            ''' The event is a mouse event.
  120.            ''' Use the mi structure of the union.
  121.            ''' </summary>
  122.            Mouse = 0
  123.  
  124.            ''' <summary>
  125.            ''' The event is a keyboard event.
  126.            ''' Use the ki structure of the union.
  127.            ''' </summary>
  128.            Keyboard = 1
  129.  
  130.            ''' <summary>
  131.            ''' The event is a hardware event.
  132.            ''' Use the hi structure of the union.
  133.            ''' </summary>
  134.            Hardware = 2
  135.  
  136.        End Enum
  137.  
  138.        ''' <summary>
  139.        ''' Specifies various aspects of a keystroke.
  140.        ''' This member can be certain combinations of the following values.
  141.        ''' For more info see here:
  142.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  143.        ''' </summary>
  144.        <Description("Enumeration used for 'dwFlags' parameter of 'KEYBDINPUT ' structure")>
  145.        <Flags>
  146.        Friend Enum KeyboardInput_Flags As Integer
  147.  
  148.            ''' <summary>
  149.            ''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
  150.            ''' </summary>
  151.            ExtendedKey = &H1
  152.  
  153.            ''' <summary>
  154.            ''' If specified, the key is being pressed.
  155.            ''' </summary>
  156.            KeyDown = &H0
  157.  
  158.            ''' <summary>
  159.            ''' If specified, the key is being released.
  160.            ''' If not specified, the key is being pressed.
  161.            ''' </summary>
  162.            KeyUp = &H2
  163.  
  164.            ''' <summary>
  165.            ''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
  166.            ''' </summary>
  167.            ScanCode = &H8
  168.  
  169.            ''' <summary>
  170.            ''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
  171.            ''' The 'wVk' parameter must be '0'.
  172.            ''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
  173.            ''' </summary>
  174.            Unicode = &H4
  175.  
  176.        End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.        ''' <summary>
  183.        ''' Used by 'SendInput' function
  184.        ''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
  185.        ''' For more info see here:
  186.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  187.        ''' </summary>
  188.        <Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
  189.        <StructLayout(LayoutKind.Explicit)>
  190.        Friend Structure INPUT
  191.  
  192.            ' ******
  193.            '  NOTE
  194.            ' ******
  195.            ' Field offset for 32 bit machine: 4
  196.            ' Field offset for 64 bit machine: 8
  197.  
  198.            ''' <summary>
  199.            ''' The type of the input event.
  200.            ''' </summary>
  201.            <FieldOffset(0)>
  202.            Public type As InputType
  203.  
  204.            ''' <summary>
  205.            ''' The information about a simulated mouse event.
  206.            ''' </summary>
  207.            <FieldOffset(8)>
  208.            Public mi As MOUSEINPUT
  209.  
  210.            ''' <summary>
  211.            ''' The information about a simulated keyboard event.
  212.            ''' </summary>
  213.            <FieldOffset(8)>
  214.            Public ki As KEYBDINPUT
  215.  
  216.            ''' <summary>
  217.            ''' The information about a simulated hardware event.
  218.            ''' </summary>
  219.            <FieldOffset(8)>
  220.            Public hi As HARDWAREINPUT
  221.  
  222.        End Structure
  223.  
  224.        ''' <summary>
  225.        ''' Contains information about a simulated mouse event.
  226.        ''' For more info see here:
  227.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
  228.        ''' </summary>
  229.        <Description("Structure used for 'mi' parameter of 'INPUT' structure")>
  230.        Friend Structure MOUSEINPUT
  231.  
  232.            ''' <summary>
  233.            '''
  234.            ''' </summary>
  235.            Public dx As Integer
  236.  
  237.            ''' <summary>
  238.            '''
  239.            ''' </summary>
  240.            Public dy As Integer
  241.  
  242.            ''' <summary>
  243.            '''
  244.            ''' </summary>
  245.            Public mouseData As Integer
  246.  
  247.            ''' <summary>
  248.            '''
  249.            ''' </summary>
  250.            Public dwFlags As Integer
  251.  
  252.            ''' <summary>
  253.            '''
  254.            ''' </summary>
  255.            Public time As Integer
  256.  
  257.            ''' <summary>
  258.            '''
  259.            ''' </summary>
  260.            Public dwExtraInfo As IntPtr
  261.  
  262.        End Structure
  263.  
  264.        ''' <summary>
  265.        ''' Contains information about a simulated keyboard event.
  266.        ''' For more info see here:
  267.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  268.        ''' </summary>
  269.        <Description("Structure used for 'ki' parameter of 'INPUT' structure")>
  270.        Friend Structure KEYBDINPUT
  271.  
  272.            ''' <summary>
  273.            ''' A virtual-key code.
  274.            ''' The code must be a value in the range '1' to '254'.
  275.            ''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
  276.            ''' </summary>
  277.            Public wVk As Short
  278.  
  279.            ''' <summary>
  280.            ''' A hardware scan code for the key.
  281.            ''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
  282.            ''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
  283.            ''' </summary>
  284.            Public wScan As Short
  285.  
  286.            ''' <summary>
  287.            ''' Specifies various aspects of a keystroke.
  288.            ''' </summary>
  289.            Public dwFlags As KeyboardInput_Flags
  290.  
  291.            ''' <summary>
  292.            ''' The time stamp for the event, in milliseconds.
  293.            ''' If this parameter is '0', the system will provide its own time stamp.
  294.            ''' </summary>
  295.            Public time As Integer
  296.  
  297.            ''' <summary>
  298.            ''' An additional value associated with the keystroke.
  299.            ''' Use the 'GetMessageExtraInfo' function to obtain this information.
  300.            ''' </summary>
  301.            Public dwExtraInfo As IntPtr
  302.  
  303.        End Structure
  304.  
  305.        ''' <summary>
  306.        ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
  307.        ''' For more info see here:
  308.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
  309.        ''' </summary>
  310.        <Description("Structure used for 'hi' parameter of 'INPUT' structure")>
  311.        Friend Structure HARDWAREINPUT
  312.  
  313.            ''' <summary>
  314.            ''' The message generated by the input hardware.
  315.            ''' </summary>
  316.            Public uMsg As Integer
  317.  
  318.            ''' <summary>
  319.            ''' The low-order word of the lParam parameter for uMsg.
  320.            ''' </summary>
  321.            Public wParamL As Short
  322.  
  323.            ''' <summary>
  324.            ''' The high-order word of the lParam parameter for uMsg.
  325.            ''' </summary>
  326.            Public wParamH As Short
  327.  
  328.        End Structure
  329.  
  330. #End Region
  331.  
  332.    End Class
  333.  
  334. #End Region
  335.  
  336. #Region " Public Methods "
  337.  
  338.    ''' <summary>
  339.    ''' Sends a keystroke.
  340.    ''' </summary>
  341.    ''' <param name="key">
  342.    ''' Indicates the keystroke to simulate.
  343.    ''' </param>
  344.    ''' <param name="BlockInput">
  345.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  346.    ''' </param>
  347.    ''' <returns>
  348.    ''' The function returns the number of events that it successfully
  349.    ''' inserted into the keyboard or mouse input stream.
  350.    ''' If the function returns zero, the input was already blocked by another thread.
  351.    ''' </returns>
  352.    Public Shared Function SendKey(ByVal key As Char,
  353.                                   Optional BlockInput As Boolean = False) As Integer
  354.  
  355.        ' Block Keyboard and mouse.
  356.        If BlockInput Then NativeMethods.BlockInput(True)
  357.  
  358.        ' The inputs structures to send.
  359.        Dim Inputs As New List(Of NativeMethods.INPUT)
  360.  
  361.        ' The current input to add into the Inputs list.
  362.        Dim CurrentInput As New NativeMethods.INPUT
  363.  
  364.        ' Determines whether a character is an alphabetic letter.
  365.        Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)
  366.  
  367.        ' Determines whether a character is an uppercase alphabetic letter.
  368.        Dim IsUpperCase As Boolean =
  369.            (key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)
  370.  
  371.        ' Determines whether the CapsLock key is pressed down.
  372.        Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock
  373.  
  374.        ' Set the passed key to upper-case.
  375.        If IsAlphabetic AndAlso Not IsUpperCase Then
  376.            key = Convert.ToChar(key.ToString.ToUpper)
  377.        End If
  378.  
  379.        ' If character is UpperCase and CapsLock is pressed down,
  380.        ' OrElse character is not UpperCase and CapsLock is not pressed down.
  381.        If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
  382.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
  383.        OrElse (Not IsAlphabetic) Then
  384.  
  385.            ' Hold the character key.
  386.            With CurrentInput
  387.                .type = NativeMethods.InputType.Keyboard
  388.                .ki.wVk = Convert.ToInt16(CChar(key))
  389.                .ki.dwFlags = 0
  390.            End With : Inputs.Add(CurrentInput)
  391.  
  392.            ' Release the character key.
  393.            With CurrentInput
  394.                .type = NativeMethods.InputType.Keyboard
  395.                .ki.wVk = Convert.ToInt16(CChar(key))
  396.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  397.            End With : Inputs.Add(CurrentInput)
  398.  
  399.            ' If character is UpperCase and CapsLock is not pressed down,
  400.            ' OrElse character is not UpperCase and CapsLock is pressed down.
  401.        ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
  402.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then
  403.  
  404.            ' Hold the Shift key.
  405.            With CurrentInput
  406.                .type = NativeMethods.InputType.Keyboard
  407.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  408.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  409.            End With : Inputs.Add(CurrentInput)
  410.  
  411.            ' Hold the character key.
  412.            With CurrentInput
  413.                .type = NativeMethods.InputType.Keyboard
  414.                .ki.wVk = Convert.ToInt16(CChar(key))
  415.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  416.            End With : Inputs.Add(CurrentInput)
  417.  
  418.            ' Release the character key.
  419.            With CurrentInput
  420.                .type = NativeMethods.InputType.Keyboard
  421.                .ki.wVk = Convert.ToInt16(CChar(key))
  422.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  423.            End With : Inputs.Add(CurrentInput)
  424.  
  425.            ' Release the Shift key.
  426.            With CurrentInput
  427.                .type = NativeMethods.InputType.Keyboard
  428.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  429.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  430.            End With : Inputs.Add(CurrentInput)
  431.  
  432.        End If ' UpperCase And My.Computer.Keyboard.CapsLock is...
  433.  
  434.        ' Send the input key.
  435.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  436.                                       Marshal.SizeOf(GetType(NativeMethods.INPUT)))
  437.  
  438.        ' Unblock Keyboard and mouse.
  439.        If BlockInput Then NativeMethods.BlockInput(False)
  440.  
  441.    End Function
  442.  
  443.    ''' <summary>
  444.    ''' Sends a keystroke.
  445.    ''' </summary>
  446.    ''' <param name="key">
  447.    ''' Indicates the keystroke to simulate.
  448.    ''' </param>
  449.    ''' <param name="BlockInput">
  450.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  451.    ''' </param>
  452.    ''' <returns>
  453.    ''' The function returns the number of events that it successfully
  454.    ''' inserted into the keyboard or mouse input stream.
  455.    ''' If the function returns zero, the input was already blocked by another thread.
  456.    ''' </returns>
  457.    Public Shared Function SendKey(ByVal key As Keys,
  458.                                   Optional BlockInput As Boolean = False) As Integer
  459.  
  460.        Return SendKey(Convert.ToChar(key), BlockInput)
  461.  
  462.    End Function
  463.  
  464.    ''' <summary>
  465.    ''' Sends a string.
  466.    ''' </summary>
  467.    ''' <param name="String">
  468.    ''' Indicates the string to send.
  469.    ''' </param>
  470.    ''' <param name="BlockInput">
  471.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  472.    ''' </param>
  473.    ''' <returns>
  474.    ''' The function returns the number of events that it successfully
  475.    ''' inserted into the keyboard or mouse input stream.
  476.    ''' If the function returns zero, the input was already blocked by another thread.
  477.    ''' </returns>
  478.    Public Shared Function SendKeys(ByVal [String] As String,
  479.                                    Optional BlockInput As Boolean = False) As Integer
  480.  
  481.        Dim SuccessCount As Integer = 0
  482.  
  483.        ' Block Keyboard and mouse.
  484.        If BlockInput Then NativeMethods.BlockInput(True)
  485.  
  486.        For Each c As Char In [String]
  487.            SuccessCount += SendKey(c, BlockInput:=False)
  488.        Next c
  489.  
  490.        ' Unblock Keyboard and mouse.
  491.        If BlockInput Then NativeMethods.BlockInput(False)
  492.  
  493.        Return SuccessCount
  494.  
  495.    End Function
  496.  
  497. #End Region
  498.  
  499. End Class

Saludos
7403  Programación / .NET (C#, VB.NET, ASP) / Re: [Duda]¿Como detectar los usb con vb 2013? en: 18 Febrero 2014, 05:00 am
Has justificado bien todo lo que has dicho y te doy la razón, solo quiero comentar una cosa:

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

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

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

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

Saludos!
7404  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 17 Febrero 2014, 22:16 pm
obtener los dispositivos extraibles que están conectados al sistema

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



monitorizar la inserción/extracción de dispositivos

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

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

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

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

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

Saludos.
7406  Programación / .NET (C#, VB.NET, ASP) / Re: [Duda]¿Como detectar los usb con vb 2013? en: 17 Febrero 2014, 21:53 pm
Hola

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

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

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



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

Car0nte, me parece una pena esa forma de pensar.

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





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

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

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





¿Como formatear una unidad?:

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

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

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

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

7407  Programación / Programación General / Re: Añadir a Favoritos del panel de navegación del explorer en: 16 Febrero 2014, 18:33 pm
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.

PD: 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!
7408  Programación / Programación General / Re: Modificar EXE creado en Visual Basic y volver a compilar en: 16 Febrero 2014, 14:31 pm
Madre mía, no se como pueden faltar tantas instrucciones en el exe modificado, lo único que hice fue nopear la variable "Var_30" que produce el String que quieres eliminar.

La instrucción era algo así (no tengo el exe aquí para volver a comprobarlo, quizás los números no son correctos):
Código:
VAR_24 = Var_30 + "\EspabilaDat.mbd"

...lo siento, no puedo ayudar más con este tema, mis conocimientos no son suficientes!

Mejor postealo en el subforo de Ingenieria Inversa, allí manejan estos temas mejor.

saludos
7409  Programación / Programación General / Re: Añadir a Favoritos del panel de navegación del explorer en: 16 Febrero 2014, 14:23 pm
Hola

Las preguntas sobre .NET van en el subforo .NET.

Supongo que te refieres a las ubicaciones favoritas?:



No se hace mediante el registro, símplemente son accesos directos que se guardan en el directorio del perfil del usuario actual, en C:\Users\USUARIO\Links

Solo necesitas crear un acceso directo.

Te hice este ejemplo (en VB.NET) para crear un acceso directo de la aplicación actual en el directorio de los favoritos del panel de navegación:

Código
  1. Imports System.IO
  2.  
  3. Public Class Form1
  4.  
  5.    ''' <summary>
  6.    ''' La ruta del directorio del acceso directo que quieres crear.
  7.    ''' </summary>
  8.    ReadOnly ShortcutDir As String =
  9.        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Links")
  10.  
  11.    ''' <summary>
  12.    ''' El nombre del archivo de acceso directo.
  13.    ''' </summary>
  14.    ReadOnly ShortcutName As String =
  15.        "MyProgram.lnk"
  16.  
  17.    ReadOnly FileInfo As FileInfo =
  18.        New FileInfo(Path.Combine(My.Application.Info.DirectoryPath(),
  19.                                  Process.GetCurrentProcess().MainModule.ModuleName))
  20.  
  21.    Private Shadows Sub Load() Handles MyBase.Load
  22.  
  23.        Dim Shortcut As New ShortcutManager.ShortcutInfo
  24.  
  25.        With Shortcut
  26.  
  27.            .ShortcutFile = Path.Combine(ShortcutDir, ShortcutName)
  28.            .Target = FileInfo.FullName
  29.            .Arguments = Nothing
  30.            .WorkingDir = FileInfo.DirectoryName
  31.            .Description = "MyProgram"
  32.            .Icon = FileInfo.FullName
  33.            .IconIndex = 0
  34.            .WindowState = ShortcutManager.ShortcutWindowState.Normal
  35.  
  36.        End With
  37.  
  38.        ShortcutManager.CreateShortcut(Shortcut)
  39.  
  40.    End Sub
  41.  
  42. End Class

...Usando el ayudante que escribí:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-16-2014
  4. ' ***********************************************************************
  5. ' <copyright file="ShortcutManager.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Runtime.InteropServices
  13. Imports System.Text
  14. Imports System.IO
  15.  
  16. #End Region
  17.  
  18. #Region " ShortcutManager "
  19.  
  20. ''' <summary>
  21. ''' Performs Shortcut related operations.
  22. ''' </summary>
  23. Public Class ShortcutManager
  24.  
  25. #Region " Variables "
  26.  
  27.    Private Shared lnk As New ShellLink()
  28.    Private Shared lnk_data As New WIN32_FIND_DATAW()
  29.  
  30.    Private Shared lnk_arguments As New StringBuilder(260)
  31.    Private Shared lnk_description As New StringBuilder(260)
  32.    Private Shared lnk_target As New StringBuilder(260)
  33.    Private Shared lnk_workingdir As New StringBuilder(260)
  34.    Private Shared lnk_iconpath As New StringBuilder(260)
  35.    Private Shared lnk_iconindex As Integer = -1
  36.    Private Shared lnk_hotkey As Short = -1
  37.    Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal
  38.  
  39. #End Region
  40.  
  41. #Region " P/Invoke "
  42.  
  43.    <DllImport("shfolder.dll", CharSet:=CharSet.Auto)>
  44.    Private Shared Function SHGetFolderPath(
  45.           ByVal hwndOwner As IntPtr,
  46.           ByVal nFolder As Integer,
  47.           ByVal hToken As IntPtr,
  48.           ByVal dwFlags As Integer,
  49.           ByVal lpszPath As StringBuilder
  50.    ) As Integer
  51.    End Function
  52.  
  53.    <Flags()>
  54.    Private Enum SLGP_FLAGS
  55.  
  56.        ''' <summary>
  57.        ''' Retrieves the standard short (8.3 format) file name.
  58.        ''' </summary>
  59.        SLGP_SHORTPATH = &H1
  60.  
  61.        ''' <summary>
  62.        ''' Retrieves the Universal Naming Convention (UNC) path name of the file.
  63.        ''' </summary>
  64.        SLGP_UNCPRIORITY = &H2
  65.  
  66.        ''' <summary>
  67.        ''' Retrieves the raw path name.
  68.        ''' A raw path is something that might not exist and may include environment variables that need to be expanded.
  69.        ''' </summary>
  70.        SLGP_RAWPATH = &H4
  71.  
  72.    End Enum
  73.  
  74.    <Flags()>
  75.    Private Enum SLR_FLAGS
  76.  
  77.        ''' <summary>
  78.        ''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
  79.        ''' the high-order word of fFlags can be set to a time-out value that specifies the
  80.        ''' maximum amount of time to be spent resolving the link. The function returns if the
  81.        ''' link cannot be resolved within the time-out duration. If the high-order word is set
  82.        ''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
  83.        ''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
  84.        ''' duration, in milliseconds.
  85.        ''' </summary>
  86.        SLR_NO_UI = &H1
  87.  
  88.        ''' <summary>
  89.        ''' If the link object has changed, update its path and list of identifiers.
  90.        ''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
  91.        ''' whether or not the link object has changed.
  92.        ''' </summary>
  93.        SLR_UPDATE = &H4
  94.  
  95.        ''' <summary>
  96.        ''' Do not update the link information
  97.        ''' </summary>
  98.        SLR_NOUPDATE = &H8
  99.  
  100.        ''' <summary>
  101.        ''' Do not execute the search heuristics
  102.        ''' </summary>
  103.        SLR_NOSEARCH = &H10
  104.  
  105.        ''' <summary>
  106.        ''' Do not use distributed link tracking
  107.        ''' </summary>
  108.        SLR_NOTRACK = &H20
  109.  
  110.        ''' <summary>
  111.        ''' Disable distributed link tracking.
  112.        ''' By default, distributed link tracking tracks removable media,
  113.        ''' across multiple devices based on the volume name.
  114.        ''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
  115.        ''' whose drive letter has changed.
  116.        ''' Setting SLR_NOLINKINFO disables both types of tracking.
  117.        ''' </summary>
  118.        SLR_NOLINKINFO = &H40
  119.  
  120.        ''' <summary>
  121.        ''' Call the Microsoft Windows Installer
  122.        ''' </summary>
  123.        SLR_INVOKE_MSI = &H80
  124.  
  125.    End Enum
  126.  
  127.    ''' <summary>
  128.    ''' Stores information about a shortcut file.
  129.    ''' </summary>
  130.    Public Class ShortcutInfo
  131.  
  132.        ''' <summary>
  133.        ''' Shortcut file full path.
  134.        ''' </summary>
  135.        Public Property ShortcutFile As String
  136.  
  137.        ''' <summary>
  138.        ''' Shortcut Comment/Description.
  139.        ''' </summary>
  140.        Public Property Description As String
  141.  
  142.        ''' <summary>
  143.        ''' Shortcut Target Arguments.
  144.        ''' </summary>
  145.        Public Property Arguments As String
  146.  
  147.        ''' <summary>
  148.        ''' Shortcut Target.
  149.        ''' </summary>
  150.        Public Property Target As String
  151.  
  152.        ''' <summary>
  153.        ''' Shortcut Working Directory.
  154.        ''' </summary>
  155.        Public Property WorkingDir As String
  156.  
  157.        ''' <summary>
  158.        ''' Shortcut Icon Location.
  159.        ''' </summary>
  160.        Public Property Icon As String
  161.  
  162.        ''' <summary>
  163.        ''' Shortcut Icon Index.
  164.        ''' </summary>
  165.        Public Property IconIndex As Integer
  166.  
  167.        ''' <summary>
  168.        ''' Shortcut Hotkey combination.
  169.        ''' Is represented as Hexadecimal.
  170.        ''' </summary>
  171.        Public Property Hotkey As Short
  172.  
  173.        ''' <summary>
  174.        ''' Shortcut Hotkey modifiers.
  175.        ''' </summary>
  176.        Public Property Hotkey_Modifier As HotkeyModifiers
  177.  
  178.        ''' <summary>
  179.        ''' Shortcut Hotkey Combination.
  180.        ''' </summary>
  181.        Public Property Hotkey_Key As Keys
  182.  
  183.        ''' <summary>
  184.        ''' Shortcut Window State.
  185.        ''' </summary>
  186.        Public Property WindowState As ShortcutWindowState
  187.  
  188.        ''' <summary>
  189.        ''' Indicates if the target is a file.
  190.        ''' </summary>
  191.        Public Property IsFile As Boolean
  192.  
  193.        ''' <summary>
  194.        ''' Indicates if the target is a directory.
  195.        ''' </summary>
  196.        Public Property IsDirectory As Boolean
  197.  
  198.        ''' <summary>
  199.        ''' Shortcut target drive letter.
  200.        ''' </summary>
  201.        Public Property DriveLetter As String
  202.  
  203.        ''' <summary>
  204.        ''' Shortcut target directory name.
  205.        ''' </summary>
  206.        Public Property DirectoryName As String
  207.  
  208.        ''' <summary>
  209.        ''' Shortcut target filename.
  210.        ''' (File extension is not included in name)
  211.        ''' </summary>
  212.        Public Property FileName As String
  213.  
  214.        ''' <summary>
  215.        ''' Shortcut target file extension.
  216.        ''' </summary>
  217.        Public Property FileExtension As String
  218.  
  219.    End Class
  220.  
  221.    ''' <summary>
  222.    ''' Hotkey modifiers for a shortcut file.
  223.    ''' </summary>
  224.    <Flags()>
  225.    Public Enum HotkeyModifiers As Short
  226.  
  227.        ''' <summary>
  228.        ''' The SHIFT key.
  229.        ''' </summary>
  230.        SHIFT = 1
  231.  
  232.        ''' <summary>
  233.        ''' The CTRL key.
  234.        ''' </summary>
  235.        CONTROL = 2
  236.  
  237.        ''' <summary>
  238.        ''' The ALT key.
  239.        ''' </summary>
  240.        ALT = 4
  241.  
  242.        ''' <summary>
  243.        ''' None.
  244.        ''' Specifies any hotkey modificator.
  245.        ''' </summary>
  246.        NONE = 0
  247.  
  248.    End Enum
  249.  
  250.    ''' <summary>
  251.    ''' The Window States for a shortcut file.
  252.    ''' </summary>
  253.    Public Enum ShortcutWindowState As Integer
  254.  
  255.        ''' <summary>
  256.        ''' Shortcut Window is at normal state.
  257.        ''' </summary>
  258.        Normal = 1
  259.  
  260.        ''' <summary>
  261.        ''' Shortcut Window is Maximized.
  262.        ''' </summary>
  263.        Maximized = 3
  264.  
  265.        ''' <summary>
  266.        ''' Shortcut Window is Minimized.
  267.        ''' </summary>
  268.        Minimized = 7
  269.  
  270.    End Enum
  271.  
  272.    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
  273.    Private Structure WIN32_FIND_DATAW
  274.        Public dwFileAttributes As UInteger
  275.        Public ftCreationTime As Long
  276.        Public ftLastAccessTime As Long
  277.        Public ftLastWriteTime As Long
  278.        Public nFileSizeHigh As UInteger
  279.        Public nFileSizeLow As UInteger
  280.        Public dwReserved0 As UInteger
  281.        Public dwReserved1 As UInteger
  282.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
  283.        Public cFileName As String
  284.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
  285.        Public cAlternateFileName As String
  286.    End Structure
  287.  
  288.    ''' <summary>
  289.    ''' The IShellLink interface allows Shell links to be created, modified, and resolved
  290.    ''' </summary>
  291.    <ComImport(),
  292.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
  293.    Guid("000214F9-0000-0000-C000-000000000046")>
  294.    Private Interface IShellLinkW
  295.  
  296.        ''' <summary>
  297.        ''' Retrieves the path and file name of a Shell link object.
  298.        ''' </summary>
  299.        Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  300.                    ByVal pszFile As StringBuilder,
  301.                    ByVal cchMaxPath As Integer,
  302.                    ByRef pfd As WIN32_FIND_DATAW,
  303.                    ByVal fFlags As SLGP_FLAGS)
  304.  
  305.        ''' <summary>
  306.        ''' Retrieves the list of item identifiers for a Shell link object.
  307.        ''' </summary>
  308.        Sub GetIDList(ByRef ppidl As IntPtr)
  309.  
  310.        ''' <summary>
  311.        ''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
  312.        ''' </summary>
  313.        Sub SetIDList(ByVal pidl As IntPtr)
  314.  
  315.        ''' <summary>
  316.        ''' Retrieves the description string for a Shell link object.
  317.        ''' </summary>
  318.        Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  319.                           ByVal pszName As StringBuilder,
  320.                           ByVal cchMaxName As Integer)
  321.  
  322.        ''' <summary>
  323.        ''' Sets the description for a Shell link object.
  324.        ''' The description can be any application-defined string.
  325.        ''' </summary>
  326.        Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
  327.                           ByVal pszName As String)
  328.  
  329.        ''' <summary>
  330.        ''' Retrieves the name of the working directory for a Shell link object.
  331.        ''' </summary>
  332.        Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  333.                                ByVal pszDir As StringBuilder,
  334.                                ByVal cchMaxPath As Integer)
  335.  
  336.        ''' <summary>
  337.        ''' Sets the name of the working directory for a Shell link object.
  338.        ''' </summary>
  339.        Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
  340.                                ByVal pszDir As String)
  341.  
  342.        ''' <summary>
  343.        ''' Retrieves the command-line arguments associated with a Shell link object.
  344.        ''' </summary>
  345.        Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  346.                         ByVal pszArgs As StringBuilder,
  347.                         ByVal cchMaxPath As Integer)
  348.  
  349.        ''' <summary>
  350.        ''' Sets the command-line arguments for a Shell link object.
  351.        ''' </summary>
  352.        Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
  353.                         ByVal pszArgs As String)
  354.  
  355.        ''' <summary>
  356.        ''' Retrieves the hot key for a Shell link object.
  357.        ''' </summary>
  358.        Sub GetHotkey(ByRef pwHotkey As Short)
  359.  
  360.        ''' <summary>
  361.        ''' Sets a hot key for a Shell link object.
  362.        ''' </summary>
  363.        Sub SetHotkey(ByVal wHotkey As Short)
  364.  
  365.        ''' <summary>
  366.        ''' Retrieves the show command for a Shell link object.
  367.        ''' </summary>
  368.        Sub GetShowCmd(ByRef piShowCmd As Integer)
  369.  
  370.        ''' <summary>
  371.        ''' Sets the show command for a Shell link object.
  372.        ''' The show command sets the initial show state of the window.
  373.        ''' </summary>
  374.        Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)
  375.  
  376.        ''' <summary>
  377.        ''' Retrieves the location (path and index) of the icon for a Shell link object.
  378.        ''' </summary>
  379.        Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  380.                            ByVal pszIconPath As StringBuilder,
  381.                            ByVal cchIconPath As Integer,
  382.                            ByRef piIcon As Integer)
  383.  
  384.        ''' <summary>
  385.        ''' Sets the location (path and index) of the icon for a Shell link object.
  386.        ''' </summary>
  387.        Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
  388.                            ByVal pszIconPath As String,
  389.                            ByVal iIcon As Integer)
  390.  
  391.        ''' <summary>
  392.        ''' Sets the relative path to the Shell link object.
  393.        ''' </summary>
  394.        Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
  395.                            ByVal pszPathRel As String,
  396.                            ByVal dwReserved As Integer)
  397.  
  398.        ''' <summary>
  399.        ''' Attempts to find the target of a Shell link,
  400.        ''' even if it has been moved or renamed.
  401.        ''' </summary>
  402.        Sub Resolve(ByVal hwnd As IntPtr,
  403.                    ByVal fFlags As SLR_FLAGS)
  404.  
  405.        ''' <summary>
  406.        ''' Sets the path and file name of a Shell link object
  407.        ''' </summary>
  408.        Sub SetPath(ByVal pszFile As String)
  409.  
  410.    End Interface
  411.  
  412.    <ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
  413.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  414.    Private Interface IPersist
  415.  
  416.        <PreserveSig()>
  417.        Sub GetClassID(ByRef pClassID As Guid)
  418.  
  419.    End Interface
  420.  
  421.    <ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
  422.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  423.    Private Interface IPersistFile
  424.        Inherits IPersist
  425.  
  426.        Shadows Sub GetClassID(ByRef pClassID As Guid)
  427.  
  428.        <PreserveSig()>
  429.        Function IsDirty() As Integer
  430.  
  431.        <PreserveSig()>
  432.        Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  433.                 pszFileName As String,
  434.                 dwMode As UInteger)
  435.  
  436.        <PreserveSig()>
  437.        Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  438.                 pszFileName As String,
  439.                 <[In](), MarshalAs(UnmanagedType.Bool)>
  440.                 fRemember As Boolean)
  441.  
  442.        <PreserveSig()>
  443.        Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  444.                          pszFileName As String)
  445.  
  446.        <PreserveSig()>
  447.        Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  448.                       ppszFileName As String)
  449.  
  450.    End Interface
  451.  
  452.    ' "CLSID_ShellLink" from "ShlGuid.h"
  453.    <ComImport(),
  454.    Guid("00021401-0000-0000-C000-000000000046")>
  455.    Private Class ShellLink
  456.    End Class
  457.  
  458. #End Region
  459.  
  460. #Region " Public Methods "
  461.  
  462.    ''' <summary>
  463.    ''' Resolves the target of a shortcut.
  464.    ''' If shortcut can't be resolved, an error message would be displayed.
  465.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  466.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  467.    ''' </summary>
  468.    ''' <param name="ShortcutFile">
  469.    ''' The shortcut file to resolve.
  470.    ''' </param>
  471.    ''' <param name="hwnd">
  472.    ''' The new handle pointer that would be generated
  473.    ''' for the window which should display the error message (if any).
  474.    ''' </param>
  475.    Public Shared Sub ResolveUi(ShortcutFile As String, hwnd As IntPtr)
  476.        LoadShortcut(ShortcutFile)
  477.        DirectCast(lnk, IShellLinkW).Resolve(hwnd, SLR_FLAGS.SLR_UPDATE)
  478.    End Sub
  479.  
  480.    ''' <summary>
  481.    ''' Resolves the target of a shortcut.
  482.    ''' If shortcut can't be resolved, any error message would be displayed.
  483.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  484.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  485.    ''' </summary>
  486.    ''' <param name="ShortcutFile">
  487.    ''' The shortcut file to resolve.
  488.    ''' </param>
  489.    Public Shared Sub ResolveNoUi(ByVal ShortcutFile As String)
  490.        LoadShortcut(ShortcutFile)
  491.        DirectCast(lnk, IShellLinkW).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_UPDATE Or SLR_FLAGS.SLR_NO_UI)
  492.    End Sub
  493.  
  494.    ''' <summary>
  495.    ''' Returns the description of a shortcut file.
  496.    ''' </summary>
  497.    ''' <param name="ShortcutFile">
  498.    ''' The shortcut file to retrieve the info.
  499.    ''' </param>
  500.    Public Shared Function GetDescription(ByVal ShortcutFile As String) As String
  501.        LoadShortcut(ShortcutFile)
  502.        lnk_description.Clear()
  503.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  504.        Return lnk_description.ToString()
  505.    End Function
  506.  
  507.    ''' <summary>
  508.    ''' Returns the Arguments of a shortcut file.
  509.    ''' </summary>
  510.    ''' <param name="ShortcutFile">
  511.    ''' The shortcut file to retrieve the info.
  512.    ''' </param>
  513.    Public Shared Function GetArguments(ByVal ShortcutFile As String) As String
  514.        LoadShortcut(ShortcutFile)
  515.        lnk_arguments.Clear()
  516.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  517.        Return lnk_arguments.ToString()
  518.    End Function
  519.  
  520.    ''' <summary>
  521.    ''' Returns the path and filename of a shortcut file.
  522.    ''' </summary>
  523.    ''' <param name="ShortcutFile">
  524.    ''' The shortcut file to retrieve the info.
  525.    ''' </param>
  526.    Public Shared Function GetFullPath(ByVal ShortcutFile As String) As String
  527.        LoadShortcut(ShortcutFile)
  528.        lnk_target.Clear()
  529.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  530.        Return lnk_target.ToString()
  531.    End Function
  532.  
  533.    ''' <summary>
  534.    ''' Returns the working directory of a shortcut file.
  535.    ''' </summary>
  536.    ''' <param name="ShortcutFile">
  537.    ''' The shortcut file to retrieve the info.
  538.    ''' </param>
  539.    Public Shared Function GetWorkingDir(ByVal ShortcutFile As String) As String
  540.        LoadShortcut(ShortcutFile)
  541.        lnk_workingdir.Clear()
  542.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  543.        Return lnk_workingdir.ToString()
  544.    End Function
  545.  
  546.    ''' <summary>
  547.    ''' Returns the Hotkey of a shortcut file.
  548.    ''' </summary>
  549.    ''' <param name="ShortcutFile">
  550.    ''' The shortcut file to retrieve the info.
  551.    ''' </param>
  552.    Public Shared Function GetHotkey(ByVal ShortcutFile As String) As Short
  553.        LoadShortcut(ShortcutFile)
  554.        lnk_hotkey = -1
  555.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  556.        Return lnk_hotkey
  557.    End Function
  558.  
  559.    ''' <summary>
  560.    ''' Returns the Window State of a shortcut file.
  561.    ''' </summary>
  562.    ''' <param name="ShortcutFile">
  563.    ''' The shortcut file to retrieve the info.
  564.    ''' </param>
  565.    Public Shared Function GetWindowStyle(ByVal ShortcutFile As String) As ShortcutWindowState
  566.        LoadShortcut(ShortcutFile)
  567.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  568.        Return lnk_windowstate
  569.    End Function
  570.  
  571.    ''' <summary>
  572.    ''' Returns the Icon location of a shortcut file.
  573.    ''' </summary>
  574.    ''' <param name="ShortcutFile">
  575.    ''' The shortcut file to retrieve the info.
  576.    ''' </param>
  577.    ''' <param name="IconIndex">
  578.    ''' Optional Integer type variable to store the IconIndex.
  579.    ''' </param>
  580.    Public Shared Function GetIconLocation(ByVal ShortcutFile As String,
  581.                                            Optional ByRef IconIndex As Integer = 0) As String
  582.        LoadShortcut(ShortcutFile)
  583.        lnk_iconpath.Clear()
  584.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, IconIndex)
  585.        Return lnk_iconpath.ToString()
  586.    End Function
  587.  
  588.    ''' <summary>
  589.    ''' Retrieves all the information about a shortcut file.
  590.    ''' </summary>
  591.    ''' <param name="ShortcutFile">
  592.    ''' The shortcut file to retrieve the info.
  593.    ''' </param>
  594.    Public Shared Function GetInfo(ByVal ShortcutFile As String) As ShortcutInfo
  595.  
  596.        ' Load Shortcut
  597.        LoadShortcut(ShortcutFile)
  598.  
  599.        ' Clean objects
  600.        Clean()
  601.  
  602.        ' Retrieve Shortcut Info
  603.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  604.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  605.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  606.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  607.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, lnk_iconindex)
  608.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  609.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  610.  
  611.        ' Return Shortcut Info
  612.        Return New ShortcutInfo With {
  613.            .ShortcutFile = ShortcutFile,
  614.            .Description = lnk_description.ToString,
  615.            .Arguments = lnk_arguments.ToString,
  616.            .Target = lnk_target.ToString,
  617.            .Icon = lnk_iconpath.ToString,
  618.            .IconIndex = lnk_iconindex,
  619.            .WorkingDir = lnk_workingdir.ToString,
  620.            .Hotkey = Hex(lnk_hotkey),
  621.            .Hotkey_Modifier = [Enum].Parse(GetType(HotkeyModifiers), GetHiByte(lnk_hotkey)),
  622.            .Hotkey_Key = [Enum].Parse(GetType(Keys), GetLoByte(lnk_hotkey)),
  623.            .WindowState = lnk_windowstate,
  624.            .IsFile = File.Exists(lnk_target.ToString),
  625.            .IsDirectory = Directory.Exists(lnk_target.ToString),
  626.            .DriveLetter = lnk_target.ToString.Substring(0, 1),
  627.            .DirectoryName = lnk_target.ToString.Substring(0, lnk_target.ToString.LastIndexOf("\")),
  628.            .FileName = lnk_target.ToString.Split("\").LastOrDefault.Split(".").FirstOrDefault,
  629.            .FileExtension = lnk_target.ToString.Split(".").LastOrDefault
  630.        }
  631.  
  632.    End Function
  633.  
  634.    ''' <summary>
  635.    ''' Creates a shortcut file.
  636.    ''' </summary>
  637.    ''' <param name="FilePath">
  638.    ''' The filepath to create the shortcut.
  639.    ''' </param>
  640.    ''' <param name="Target">
  641.    ''' The target file or directory.
  642.    ''' </param>
  643.    ''' <param name="WorkingDirectory">
  644.    ''' The working directory os the shortcut.
  645.    ''' </param>
  646.    ''' <param name="Description">
  647.    ''' The shortcut description.
  648.    ''' </param>
  649.    ''' <param name="Arguments">
  650.    ''' The target file arguments.
  651.    ''' This value only should be set when target is an executable file.
  652.    ''' </param>
  653.    ''' <param name="Icon">
  654.    ''' The icon location of the shortcut.
  655.    ''' </param>
  656.    ''' <param name="IconIndex">
  657.    ''' The icon index of the icon file.
  658.    ''' </param>
  659.    ''' <param name="HotKey_Modifier">
  660.    ''' The hotkey modifier(s) which should be used for the hotkey combination.
  661.    ''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
  662.    ''' </param>
  663.    ''' <param name="HotKey_Key">
  664.    ''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
  665.    ''' </param>
  666.    ''' <param name="WindowState">
  667.    ''' The Window state for the target.
  668.    ''' </param>
  669.    Public Shared Sub CreateShortcut(ByVal FilePath As String,
  670.                                     ByVal Target As String,
  671.                                     Optional ByVal WorkingDirectory As String = Nothing,
  672.                                     Optional ByVal Description As String = Nothing,
  673.                                     Optional ByVal Arguments As String = Nothing,
  674.                                     Optional ByVal Icon As String = Nothing,
  675.                                     Optional ByVal IconIndex As Integer = Nothing,
  676.                                     Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
  677.                                     Optional ByVal HotKey_Key As Keys = Nothing,
  678.                                     Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)
  679.  
  680.        ' Load Shortcut
  681.        LoadShortcut(FilePath)
  682.  
  683.        ' Clean objects
  684.        Clean()
  685.  
  686.        ' Set Shortcut Info
  687.        DirectCast(lnk, IShellLinkW).SetPath(Target)
  688.  
  689.        DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
  690.                                                            WorkingDirectory,
  691.                                                            Path.GetDirectoryName(Target)))
  692.  
  693.        DirectCast(lnk, IShellLinkW).SetDescription(Description)
  694.        DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
  695.        DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)
  696.  
  697.        DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
  698.                                                  Convert.ToInt16(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
  699.                                                  Nothing))
  700.  
  701.        DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)
  702.  
  703.        DirectCast(lnk, IPersistFile).Save(FilePath, True)
  704.        DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)
  705.  
  706.    End Sub
  707.  
  708.    ''' <summary>
  709.    ''' Creates a shortcut file.
  710.    ''' </summary>
  711.    ''' <param name="Shortcut">Indicates a ShortcutInfo object.</param>
  712.    Public Shared Sub CreateShortcut(ByVal Shortcut As ShortcutInfo)
  713.  
  714.        CreateShortcut(Shortcut.ShortcutFile,
  715.                       Shortcut.Target,
  716.                       Shortcut.WorkingDir,
  717.                       Shortcut.Description,
  718.                       Shortcut.Arguments,
  719.                       Shortcut.Icon,
  720.                       Shortcut.IconIndex,
  721.                       Shortcut.Hotkey_Modifier,
  722.                       Shortcut.Hotkey_Key,
  723.                       Shortcut.WindowState)
  724.  
  725.    End Sub
  726.  
  727.    ''' <summary>
  728.    ''' Modifies the atributes of an existing shortcut file.
  729.    ''' </summary>
  730.    ''' <param name="ShortcutFile">
  731.    ''' The existing .lnk file to modify.
  732.    ''' </param>
  733.    ''' <param name="Target">
  734.    ''' The target file or directory.
  735.    ''' </param>
  736.    ''' <param name="WorkingDirectory">
  737.    ''' The working directory os the shortcut.
  738.    ''' </param>
  739.    ''' <param name="Description">
  740.    ''' The shortcut description.
  741.    ''' </param>
  742.    ''' <param name="Arguments">
  743.    ''' The target file arguments.
  744.    ''' This value only should be set when target is an executable file.
  745.    ''' </param>
  746.    ''' <param name="Icon">
  747.    ''' The icon location of the shortcut.
  748.    ''' </param>
  749.    ''' <param name="IconIndex">
  750.    ''' The icon index of the icon file.
  751.    ''' </param>
  752.    ''' <param name="HotKey_Modifier">
  753.    ''' The hotkey modifier(s) which should be used for the hotkey combination.
  754.    ''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
  755.    ''' </param>
  756.    ''' <param name="HotKey_Key">
  757.    ''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
  758.    ''' </param>
  759.    ''' <param name="WindowState">
  760.    ''' The Window state for the target.
  761.    ''' </param>
  762.    Public Shared Sub ModifyShortcut(ByVal ShortcutFile As String,
  763.                                     Optional ByVal Target As String = Nothing,
  764.                                     Optional ByVal WorkingDirectory As String = Nothing,
  765.                                     Optional ByVal Description As String = Nothing,
  766.                                     Optional ByVal Arguments As String = Nothing,
  767.                                     Optional ByVal Icon As String = Nothing,
  768.                                     Optional ByVal IconIndex As Integer = -1,
  769.                                     Optional ByVal HotKey_Modifier As HotkeyModifiers = -1,
  770.                                     Optional ByVal HotKey_Key As Keys = -1,
  771.                                     Optional ByVal WindowState As ShortcutWindowState = -1)
  772.  
  773.        ' Load Shortcut
  774.        LoadShortcut(ShortcutFile)
  775.  
  776.        ' Clean objects
  777.        Clean()
  778.  
  779.        ' Retrieve Shortcut Info
  780.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  781.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  782.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  783.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  784.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, lnk_iconindex)
  785.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  786.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  787.  
  788.        ' Set Shortcut Info
  789.        DirectCast(lnk, IShellLinkW).SetPath(If(Target IsNot Nothing,
  790.                                                Target,
  791.                                                lnk_target.ToString))
  792.  
  793.        DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
  794.                                                            WorkingDirectory,
  795.                                                            lnk_workingdir.ToString))
  796.  
  797.        DirectCast(lnk, IShellLinkW).SetDescription(If(Description IsNot Nothing,
  798.                                                       Description,
  799.                                                       lnk_description.ToString))
  800.  
  801.        DirectCast(lnk, IShellLinkW).SetArguments(If(Arguments IsNot Nothing,
  802.                                                     Arguments,
  803.                                                     lnk_arguments.ToString))
  804.  
  805.        DirectCast(lnk, IShellLinkW).SetIconLocation(If(Icon IsNot Nothing, Icon, lnk_iconpath.ToString),
  806.                                                     If(IconIndex <> -1, IconIndex, lnk_iconindex))
  807.  
  808.        DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key > 0,
  809.                                                  Convert.ToInt16(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
  810.                                                  lnk_hotkey))
  811.  
  812.        DirectCast(lnk, IShellLinkW).SetShowCmd(If(WindowState <> -1,
  813.                                                   WindowState,
  814.                                                   lnk_windowstate))
  815.  
  816.        DirectCast(lnk, IPersistFile).Save(ShortcutFile, True)
  817.        DirectCast(lnk, IPersistFile).SaveCompleted(ShortcutFile)
  818.  
  819.  
  820.    End Sub
  821.  
  822. #End Region
  823.  
  824. #Region " Private Methods "
  825.  
  826.    ''' <summary>
  827.    ''' Loads the shortcut object to retrieve information.
  828.    ''' </summary>
  829.    ''' <param name="ShortcutFile">
  830.    ''' The shortcut file to retrieve the info.
  831.    ''' </param>
  832.    Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
  833.        DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
  834.    End Sub
  835.  
  836.    ''' <summary>
  837.    ''' Clean the shortcut info objects.
  838.    ''' </summary>
  839.    Private Shared Sub Clean()
  840.        lnk_description.Clear()
  841.        lnk_arguments.Clear()
  842.        lnk_target.Clear()
  843.        lnk_workingdir.Clear()
  844.        lnk_iconpath.Clear()
  845.        lnk_hotkey = -1
  846.        lnk_iconindex = -1
  847.    End Sub
  848.  
  849.    ''' <summary>
  850.    ''' Gets the low order byte of a number.
  851.    ''' </summary>
  852.    Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
  853.        Return Intg And &HFF&
  854.    End Function
  855.  
  856.    ''' <summary>
  857.    ''' Gets the high order byte of a number.
  858.    ''' </summary>
  859.    Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
  860.        Return (Intg And &HFF00&) / 256
  861.    End Function
  862.  
  863. #End Region
  864.  
  865. End Class
  866.  
  867. #End Region
7410  Programación / Programación General / Re: Modificar EXE creado en Visual Basic y volver a compilar en: 15 Febrero 2014, 23:36 pm
Eso es debido a que no sabes lo que hablas, el Visual Studio puede usarse como cualquier otro depurador (Windbg,Ollydbg,etc).

Y Pues deberias fijarte bien en los temas que respondes, Sólo recordar lo gracioso que fueron tus respuestas hablando
de un lenguaje de programación que ni siquiera conoces un poco. De todos modos, este dia no tengo tiempo para discutir
con el joven chico 'Bachero'.


si, muy gracioso, ¿acaso algo de lo que dije sobre C++ no fue cierto?, lo repito, eres patético, lo único que sabes hacer es intentar provocar con estupideces, y yo me dejo provocar porque gente como tu estaría mejor en la tumba intentando trollear a sus muertos enterrados.

PD: el karma es cruel, y espero que contigo no se apiade ;)



@MaX2

He estado examinando el executable y me he percatado de que... si que toma en cuenta la DB que hay en la misma carpeta de trabajo que el exe:




Así que no se porque tienes problemas con eso, es decir, en mi caso no es necesario meter el archivo en  "C:\EspabilaB\EspabilaDAT.mdb", el zip que me pasaste, están todos los archivos en la misma carpeta y no tengo problemas para abrir la base de datos y manipularla.

De todas formas si que ví el String que mencionaste "C:\EspabilaB\EspabilaDAT.mdb" y lo he modificado a "EspabilaDAT.mdb", aquí lo tienes:
~> (enlace eliminado a petición del usuario...)

Aunque no creo que deba haber ninguna diferencia entre la pequeña modificación que le hice y el exe que tu ya tienes, porque como ya dije, en mi caso no es necesario modificar el exe para que me acepte la DB en la misma carpeta d trabajo del exe.

espero que te funcione
Saludos

Páginas: 1 ... 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 [741] 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines