No creo que exista un software dedicado a una tarea tan "singular", pero de todas formas no es dificil conseguirlo escribiendo un Script/Programa, partiendo cada linea de texto usando como delimitador el caracter de 'espacio'.
Slaudos!
Slaudos!
Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.
Mostrar Mensajes Menú ' Colorize Words
' ( By Elektro )
'
' Usage Examples:
'
' ColorizeWord(RichTextBox1, "Hello", True,
' Color.Red, Color.Black,
' New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic))
'
' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False,
' ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing)
''' <summary>
''' Find a word on a RichTextBox and colorizes each match.
''' </summary>
''' <param name="RichTextBox">Indicates the RichTextBox.</param>
''' <param name="Word">Indicates the word to colorize.</param>
''' <param name="IgnoreCase">Indicates the ignore case.</param>
''' <param name="ForeColor">Indicates the text color.</param>
''' <param name="BackColor">Indicates the background color.</param>
''' <param name="Font">Indicates the text font.</param>
''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox,
ByVal Word As String,
Optional ByVal IgnoreCase As Boolean = False,
Optional ByVal ForeColor As Color = Nothing,
Optional ByVal BackColor As Color = Nothing,
Optional ByVal [Font] As Font = Nothing) As Boolean
' Find all the word matches.
Dim Matches As System.Text.RegularExpressions.MatchCollection =
System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word,
If(IgnoreCase,
System.Text.RegularExpressions.RegexOptions.IgnoreCase,
System.Text.RegularExpressions.RegexOptions.None))
' If no matches then return.
If Not Matches.Count <> 0 Then
Return False
End If
' Set the passed Parameter values.
If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor
If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor
If [Font] Is Nothing Then [Font] = [RichTextBox].Font
' Store the current caret position to restore it at the end.
Dim CaretPosition As Integer = [RichTextBox].SelectionStart
' Suspend the control layout to work quicklly.
[RichTextBox].SuspendLayout()
' Colorize each match.
For Each Match As System.Text.RegularExpressions.Match In Matches
[RichTextBox].Select(Match.Index, Match.Length)
[RichTextBox].SelectionColor = ForeColor
[RichTextBox].SelectionBackColor = BackColor
[RichTextBox].SelectionFont = [Font]
Next Match
' Restore the caret position.
[RichTextBox].Select(CaretPosition, 0)
' Restore the control layout.
[RichTextBox].ResumeLayout()
' Return successfully
Return True
End Function
''' <summary>
''' Find multiple words on a RichTextBox and colorizes each match.
''' </summary>
''' <param name="RichTextBox">Indicates the RichTextBox.</param>
''' <param name="Words">Indicates the words to colorize.</param>
''' <param name="IgnoreCase">Indicates the ignore case.</param>
''' <param name="ForeColor">Indicates the text color.</param>
''' <param name="BackColor">Indicates the background color.</param>
''' <param name="Font">Indicates the text font.</param>
''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox,
ByVal Words As String(),
Optional ByVal IgnoreCase As Boolean = False,
Optional ByVal ForeColor As Color = Nothing,
Optional ByVal BackColor As Color = Nothing,
Optional ByVal [Font] As Font = Nothing) As Boolean
Dim Success As Boolean = False
For Each Word As String In Words
Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font])
Next Word
Return Success
End Function
' Remove ListView Duplicates
' ( By Elektro )
'
' Usage Examples:
' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1)
' RemoveListViewDuplicates(Items, 0)
'
''' <summary>
''' Removes duplicated items from a Listview.
''' </summary>
''' <param name="Items">
''' Indicates the items collection.
''' </param>
''' <param name="SubitemCompare">
''' Indicates the subitem column to compare duplicates.
''' </param>
Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
ByVal SubitemCompare As Integer)
' Suspend the layout on the Control that owns the Items collection.
Items.Item(0).ListView.SuspendLayout()
' Get the duplicated Items.
Dim Duplicates As ListViewItem() =
Items.Cast(Of ListViewItem)().
GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
Skip(1).
ToArray()
' Delete the duplicated Items.
For Each Item As ListViewItem In Duplicates
Items.Remove(Item)
Next Item
' Resume the layout on the Control that owns the Items collection.
Items.Item(0).ListView.ResumeLayout()
Duplicates = Nothing
End Sub
' Format Drive
' ( By Elektro )
'
' Usage Examples:
' FormatDrive("Z")
' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
''' <summary>
''' Indicates the possible HardDisk filesystem's for Windows OS.
''' </summary>
Public Enum DriveFileSystem As Integer
' NOTE:
' *****
' The numeric values just indicates the max harddisk volume-label character-length for each filesystem.
''' <summary>
''' NTFS FileSystem.
''' </summary>
NTFS = 32
''' <summary>
''' FAT16 FileSystem.
''' </summary>
FAT16 = 11
''' <summary>
''' FAT32 FileSystem.
''' </summary>
FAT32 = FAT16
End Enum
''' <summary>
''' Formats a drive.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
''' </summary>
''' <param name="DriveLetter">
''' Indicates the drive letter to format.
''' </param>
''' <param name="FileSystem">
''' Indicates the filesystem format to use for this volume.
''' The default is "NTFS".
''' </param>
''' <param name="QuickFormat">
''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
''' without scanning the disk for bad sectors.
''' Use this option only if the disk has been previously formatted,
''' and you know that the disk is not damaged.
''' The default is <c>true</c>.
''' </param>
''' <param name="ClusterSize">
''' Disk allocation unit size—cluster size.
''' All of the filesystems organizes the hard disk based on cluster size,
''' which represents the smallest amount of disk space that can be allocated to hold a file.
''' The smaller the cluster size you use, the more efficiently your disk stores information.
''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
''' For general use, the default settings are strongly recommended.
''' </param>
''' <param name="VolumeLabel">
''' Indicates the Label to use for the new volume.
''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
''' and up to 32 characters for NTFS filesystem volumes.
''' </param>
''' <param name="EnableCompression">Not implemented.</param>
''' <returns>
''' 0 = Success.
''' 1 = Unsupported file system.
''' 2 = Incompatible media in drive.
''' 3 = Access denied.
''' 4 = Call canceled.
''' 5 = Call cancellation request too late.
''' 6 = Volume write protected.
''' 7 = Volume lock failed.
''' 8 = Unable to quick format.
''' 9 = Input/Output (I/O) error.
''' 10 = Invalid volume label.
''' 11 = No media in drive.
''' 12 = Volume is too small.
''' 13 = Volume is too large.
''' 14 = Volume is not mounted.
''' 15 = Cluster size is too small.
''' 16 = Cluster size is too large.
''' 17 = Cluster size is beyond 32 bits.
''' 18 = Unknown error.
''' </returns>
Public Function FormatDrive(ByVal DriveLetter As Char,
Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
Optional ByVal QuickFormat As Boolean = True,
Optional ByVal ClusterSize As Integer = Nothing,
Optional ByVal VolumeLabel As String = Nothing,
Optional ByVal EnableCompression As Boolean = False) As Integer
' Volume-label error check.
If Not String.IsNullOrEmpty(VolumeLabel) Then
If VolumeLabel.Length > FileSystem Then
Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
FileSystem.ToString, CStr(FileSystem)))
End If
End If
Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
Convert.ToString(DriveLetter))
Using WMI As New ManagementObjectSearcher(Query)
Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
InvokeMethod("Format",
New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
End Using
Return 18 ' Unknown error.
End Function
@Echo OFF
Set "Output=%HomeDrive%\Registros\Cliente.reg"
Set "Key=HKCU\Software\SimonTatham\PuTTY\Sessions\CIA%%20-%%20Cliente"
Reg Export "%Key%" "%Output%"
Pause&Exit
Cita de: rapbyone en 15 Febrero 2014, 20:00 PMNo entiendo cual será el problema
Private Sub Test() Handles Button1.Click
AppActivate(Process.GetProcessesByName("notepad").First.Id)
Dim Result As Integer = SendInputs.SendKeys(Keys.Insert, BlockInput:=False)
' Dim Result2 As Integer = SendInputs.SendKey(Convert.ToChar(Keys.Enter))
' Dim Result2 As Integer = SendInputs.SendKey("x"c)
#If DEBUG Then
MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
#End If
End Sub
' ***********************************************************************
' Author : Elektro
' Modified : 02-17-2014
' ***********************************************************************
' <copyright file="SendInputs.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Imports "
Imports System.Runtime.InteropServices
Imports System.ComponentModel
#End Region
''' <summary>
'''
''' </summary>
Public Class SendInputs
#Region " P/Invoke "
Friend Class NativeMethods
#Region " Methods "
''' <summary>
''' Blocks keyboard and mouse input events from reaching applications.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
''' </summary>
''' <param name="fBlockIt">
''' The function's purpose.
''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
''' </param>
''' <returns>
''' If the function succeeds, the return value is nonzero.
''' If input is already blocked, the return value is zero.
''' </returns>
''' <remarks>
''' Note that only the thread that blocked input can successfully unblock input.
''' </remarks>
<DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
SetLastError:=True)>
Friend Shared Function BlockInput(
ByVal fBlockIt As Boolean
) As Integer
End Function
''' <summary>
''' Synthesizes keystrokes, mouse motions, and button clicks.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
''' </summary>
''' <param name="nInputs">
''' Indicates the number of structures in the pInputs array.
''' </param>
''' <param name="pInputs">
''' Indicates an Array of 'INPUT' structures.
''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
''' </param>
''' <param name="cbSize">
''' The size, in bytes, of an 'INPUT' structure.
''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully
''' inserted into the keyboard or mouse input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
<DllImport("user32.dll", SetLastError:=True)>
Friend Shared Function SendInput(
ByVal nInputs As Integer,
<MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
ByVal cbSize As Integer
) As Integer
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' VirtualKey codes.
''' </summary>
Friend Enum VirtualKeys As Short
''' <summary>
''' The Shift key.
''' VK_SHIFT
''' </summary>
SHIFT = &H10S
''' <summary>
''' The DEL key.
''' VK_DELETE
''' </summary>
DELETE = 46S
''' <summary>
''' The ENTER key.
''' VK_RETURN
''' </summary>
[RETURN] = 13S
End Enum
''' <summary>
''' The type of the input event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
''' </summary>
<Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
Friend Enum InputType As Integer
''' <summary>
''' The event is a mouse event.
''' Use the mi structure of the union.
''' </summary>
Mouse = 0
''' <summary>
''' The event is a keyboard event.
''' Use the ki structure of the union.
''' </summary>
Keyboard = 1
''' <summary>
''' The event is a hardware event.
''' Use the hi structure of the union.
''' </summary>
Hardware = 2
End Enum
''' <summary>
''' Specifies various aspects of a keystroke.
''' This member can be certain combinations of the following values.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
''' </summary>
<Description("Enumeration used for 'dwFlags' parameter of 'KEYBDINPUT ' structure")>
<Flags>
Friend Enum KeyboardInput_Flags As Integer
''' <summary>
''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
''' </summary>
ExtendedKey = &H1
''' <summary>
''' If specified, the key is being pressed.
''' </summary>
KeyDown = &H0
''' <summary>
''' If specified, the key is being released.
''' If not specified, the key is being pressed.
''' </summary>
KeyUp = &H2
''' <summary>
''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
''' </summary>
ScanCode = &H8
''' <summary>
''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
''' The 'wVk' parameter must be '0'.
''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
''' </summary>
Unicode = &H4
End Enum
#End Region
#Region " Structures "
''' <summary>
''' Used by 'SendInput' function
''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
<StructLayout(LayoutKind.Explicit)>
Friend Structure INPUT
' ******
' NOTE
' ******
' Field offset for 32 bit machine: 4
' Field offset for 64 bit machine: 8
''' <summary>
''' The type of the input event.
''' </summary>
<FieldOffset(0)>
Public type As InputType
''' <summary>
''' The information about a simulated mouse event.
''' </summary>
<FieldOffset(8)>
Public mi As MOUSEINPUT
''' <summary>
''' The information about a simulated keyboard event.
''' </summary>
<FieldOffset(8)>
Public ki As KEYBDINPUT
''' <summary>
''' The information about a simulated hardware event.
''' </summary>
<FieldOffset(8)>
Public hi As HARDWAREINPUT
End Structure
''' <summary>
''' Contains information about a simulated mouse event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'mi' parameter of 'INPUT' structure")>
Friend Structure MOUSEINPUT
''' <summary>
'''
''' </summary>
Public dx As Integer
''' <summary>
'''
''' </summary>
Public dy As Integer
''' <summary>
'''
''' </summary>
Public mouseData As Integer
''' <summary>
'''
''' </summary>
Public dwFlags As Integer
''' <summary>
'''
''' </summary>
Public time As Integer
''' <summary>
'''
''' </summary>
Public dwExtraInfo As IntPtr
End Structure
''' <summary>
''' Contains information about a simulated keyboard event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'ki' parameter of 'INPUT' structure")>
Friend Structure KEYBDINPUT
''' <summary>
''' A virtual-key code.
''' The code must be a value in the range '1' to '254'.
''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
''' </summary>
Public wVk As Short
''' <summary>
''' A hardware scan code for the key.
''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
''' </summary>
Public wScan As Short
''' <summary>
''' Specifies various aspects of a keystroke.
''' </summary>
Public dwFlags As KeyboardInput_Flags
''' <summary>
''' The time stamp for the event, in milliseconds.
''' If this parameter is '0', the system will provide its own time stamp.
''' </summary>
Public time As Integer
''' <summary>
''' An additional value associated with the keystroke.
''' Use the 'GetMessageExtraInfo' function to obtain this information.
''' </summary>
Public dwExtraInfo As IntPtr
End Structure
''' <summary>
''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'hi' parameter of 'INPUT' structure")>
Friend Structure HARDWAREINPUT
''' <summary>
''' The message generated by the input hardware.
''' </summary>
Public uMsg As Integer
''' <summary>
''' The low-order word of the lParam parameter for uMsg.
''' </summary>
Public wParamL As Short
''' <summary>
''' The high-order word of the lParam parameter for uMsg.
''' </summary>
Public wParamH As Short
End Structure
#End Region
End Class
#End Region
#Region " Public Methods "
''' <summary>
''' Sends a keystroke.
''' </summary>
''' <param name="key">
''' Indicates the keystroke to simulate.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully
''' inserted into the keyboard or mouse input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKey(ByVal key As Char,
Optional BlockInput As Boolean = False) As Integer
' Block Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(True)
' The inputs structures to send.
Dim Inputs As New List(Of NativeMethods.INPUT)
' The current input to add into the Inputs list.
Dim CurrentInput As New NativeMethods.INPUT
' Determines whether a character is an alphabetic letter.
Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)
' Determines whether a character is an uppercase alphabetic letter.
Dim IsUpperCase As Boolean =
(key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)
' Determines whether the CapsLock key is pressed down.
Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock
' Set the passed key to upper-case.
If IsAlphabetic AndAlso Not IsUpperCase Then
key = Convert.ToChar(key.ToString.ToUpper)
End If
' If character is UpperCase and CapsLock is pressed down,
' OrElse character is not UpperCase and CapsLock is not pressed down.
If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
OrElse (Not IsAlphabetic) Then
' Hold the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = 0
End With : Inputs.Add(CurrentInput)
' Release the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
' If character is UpperCase and CapsLock is not pressed down,
' OrElse character is not UpperCase and CapsLock is pressed down.
ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then
' Hold the Shift key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = NativeMethods.VirtualKeys.SHIFT
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
End With : Inputs.Add(CurrentInput)
' Hold the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
End With : Inputs.Add(CurrentInput)
' Release the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
' Release the Shift key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = NativeMethods.VirtualKeys.SHIFT
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
End If ' UpperCase And My.Computer.Keyboard.CapsLock is...
' Send the input key.
Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
Marshal.SizeOf(GetType(NativeMethods.INPUT)))
' Unblock Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(False)
End Function
''' <summary>
''' Sends a keystroke.
''' </summary>
''' <param name="key">
''' Indicates the keystroke to simulate.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully
''' inserted into the keyboard or mouse input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKey(ByVal key As Keys,
Optional BlockInput As Boolean = False) As Integer
Return SendKey(Convert.ToChar(key), BlockInput)
End Function
''' <summary>
''' Sends a string.
''' </summary>
''' <param name="String">
''' Indicates the string to send.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully
''' inserted into the keyboard or mouse input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKeys(ByVal [String] As String,
Optional BlockInput As Boolean = False) As Integer
Dim SuccessCount As Integer = 0
' Block Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(True)
For Each c As Char In [String]
SuccessCount += SendKey(c, BlockInput:=False)
Next c
' Unblock Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(False)
Return SuccessCount
End Function
#End Region
End Class
CitarCreo que no es muy justo tratar de morralla al trabajo que han hecho otros con el mismo trabajo (o más)
' GetDrivesOfType
' ( By Elektro )
'
' Usage Examples:
'
' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
'
' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
' MsgBox(Drive.Name)
' Next Drive
'
''' <summary>
''' Get all the connected drives of the given type.
''' </summary>
''' <param name="DriveType">Indicates the type of the drive.</param>
''' <returns>System.IO.DriveInfo[].</returns>
Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
Where Drive.DriveType = DriveType).ToArray
End Function
' ***********************************************************************
' Author : Elektro
' Modified : 02-17-2014
' ***********************************************************************
' <copyright file="DriveWatcher.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
' ''' <summary>
' ''' The DriveWatcher instance to monitor USB devices.
' ''' </summary>
'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
' ''' <summary>
' ''' Handles the DriveInserted event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE CONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
' ''' <summary>
' ''' Handles the DriveRemoved event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE DISCONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
#End Region
#Region " Imports "
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.ComponentModel
#End Region
''' <summary>
''' Device insertion/removal monitor.
''' </summary>
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
#Region " Objects "
''' <summary>
''' The current connected drives.
''' </summary>
Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
''' <summary>
''' Indicates the drive letter of the current device.
''' </summary>
Private DriveLetter As Char = Nothing
''' <summary>
''' Indicates the current Drive information.
''' </summary>
Private CurrentDrive As DriveWatcherInfo = Nothing
''' <summary>
''' The form to manage their Windows Messages.
''' </summary>
Private WithEvents form As Form = Nothing
#End Region
#Region " Events "
''' <summary>
''' Occurs when a drive is inserted.
''' </summary>
Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
''' <summary>
''' Occurs when a drive is removed.
''' </summary>
Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
#End Region
#Region " Enumerations "
''' <summary>
''' Notifies an application of a change to the hardware configuration of a device or the computer.
''' A window receives this message through its WindowProc function.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
''' </summary>
Private Enum DeviceEvents As Integer
''' <summary>
''' The current configuration has changed, due to a dock or undock.
''' </summary>
Change = &H219
''' <summary>
''' A device or piece of media has been inserted and becomes available.
''' </summary>
Arrival = &H8000
''' <summary>
''' Request permission to remove a device or piece of media.
''' This message is the last chance for applications and drivers to prepare for this removal.
''' However, any application can deny this request and cancel the operation.
''' </summary>
QueryRemove = &H8001
''' <summary>
''' A request to remove a device or piece of media has been canceled.
''' </summary>
QueryRemoveFailed = &H8002
''' <summary>
''' A device or piece of media is being removed and is no longer available for use.
''' </summary>
RemovePending = &H8003
''' <summary>
''' A device or piece of media has been removed.
''' </summary>
RemoveComplete = &H8004
''' <summary>
''' The type volume
''' </summary>
TypeVolume = &H2
End Enum
#End Region
#Region " Structures "
''' <summary>
''' Indicates information related of a Device.
''' ( Replic of System.IO.DriveInfo )
''' </summary>
Public Structure DriveWatcherInfo
''' <summary>
''' Indicates the name of a drive, such as 'C:\'.
''' </summary>
Public Name As String
''' <summary>
''' Indicates the amount of available free space on a drive, in bytes.
''' </summary>
Public AvailableFreeSpace As Long
''' <summary>
''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
''' </summary>
Public DriveFormat As String
''' <summary>
''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
''' </summary>
Public DriveType As DriveType
''' <summary>
''' Indicates whether a drive is ready.
''' </summary>
Public IsReady As Boolean
''' <summary>
''' Indicates the root directory of a drive.
''' </summary>
Public RootDirectory As String
''' <summary>
''' Indicates the total amount of free space available on a drive, in bytes.
''' </summary>
Public TotalFreeSpace As Long
''' <summary>
''' Indicates the total size of storage space on a drive, in bytes.
''' </summary>
Public TotalSize As Long
''' <summary>
''' Indicates the volume label of a drive.
''' </summary>
Public VolumeLabel As String
''' <summary>
''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
''' </summary>
''' <param name="e">The e.</param>
Public Sub New(ByVal e As DriveInfo)
Name = e.Name
Select Case e.IsReady
Case True ' Drive is formatted and ready.
IsReady = True
DriveFormat = e.DriveFormat
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = e.VolumeLabel
TotalSize = e.TotalSize
TotalFreeSpace = e.TotalFreeSpace
AvailableFreeSpace = e.AvailableFreeSpace
Case False ' Drive is not formatted so can't retrieve data.
IsReady = False
DriveFormat = Nothing
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = Nothing
TotalSize = 0
TotalFreeSpace = 0
AvailableFreeSpace = 0
End Select ' e.IsReady
End Sub
End Structure
''' <summary>
''' Contains information about a logical volume.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
''' </summary>
<StructLayout(LayoutKind.Sequential)>
Private Structure DEV_BROADCAST_VOLUME
''' <summary>
''' The size of this structure, in bytes.
''' </summary>
Public Size As UInteger
''' <summary>
''' Set to DBT_DEVTYP_VOLUME (2).
''' </summary>
Public Type As UInteger
''' <summary>
''' Reserved parameter; do not use this.
''' </summary>
Public Reserved As UInteger
''' <summary>
''' The logical unit mask identifying one or more logical units.
''' Each bit in the mask corresponds to one logical drive.
''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
''' </summary>
Public Mask As UInteger
''' <summary>
''' This parameter can be one of the following values:
''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
''' '0x0002': Indicated logical volume is a network volume.
''' </summary>
Public Flags As UShort
End Structure
#End Region
#Region " Constructor "
''' <summary>
''' Initializes a new instance of this class.
''' </summary>
''' <param name="form">The form to assign.</param>
Public Sub New(ByVal form As Form)
' Assign the Formulary.
Me.form = form
End Sub
#End Region
#Region " Event Handlers "
''' <summary>
''' Assign the handle of the target Form to this NativeWindow,
''' necessary to override target Form's WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated, form.Load, form.Shown
If Not MyBase.Handle.Equals(Me.form.Handle) Then
MyBase.AssignHandle(Me.form.Handle)
End If
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
MyBase.ReleaseHandle()
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
''' </summary>
''' <param name="Device">
''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
''' </param>
''' <returns>System.Char.</returns>
Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
Dim DriveLetters As Char() =
{
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
}
Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
For X As Integer = 0 To DeviceID.Length
If DeviceID(X) Then
Return DriveLetters(X)
End If
Next X
Return Nothing
End Function
#End Region
#Region " WndProc"
''' <summary>
''' Invokes the default window procedure associated with this window to process messages for this Window.
''' </summary>
''' <param name="m">
''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
''' </param>
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case DeviceEvents.Change ' The hardware has changed.
' Transform the LParam pointer into the data structure.
Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
Select Case m.WParam.ToInt32
Case DeviceEvents.Arrival ' The device is connected.
' Get the drive letter of the connected device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Get the drive information of the connected device.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' If it's an storage device then...
If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
' Inform that the device is connected by raising the 'DriveConnected' event.
RaiseEvent DriveInserted(Me, CurrentDrive)
' Add the connected device to the dictionary, to retrieve info.
If Not CurrentDrives.ContainsKey(DriveLetter) Then
CurrentDrives.Add(DriveLetter, CurrentDrive)
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
' Get the letter of the current device being removed.
DriveLetter = GetDriveLetter(CurrentWDrive)
' If the current device being removed is not in the dictionary then...
If Not CurrentDrives.ContainsKey(DriveLetter) Then
' Get the device information of the current device being removed.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' Add the current device to the dictionary,
' to retrieve info before lost it after fully-removal.
CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
Case DeviceEvents.RemoveComplete
' Get the letter of the removed device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
RaiseEvent DriveRemoved(Me, CurrentDrive)
' If the removed device is in the dictionary then...
If CurrentDrives.ContainsKey(DriveLetter) Then
' Remove the device from the dictionary.
CurrentDrives.Remove(DriveLetter)
End If ' CurrentDrives.ContainsKey(DriveLetter)
End Select ' m.WParam.ToInt32
End Select ' m.Msg
MyBase.WndProc(m) ' Return Message to base message handler.
End Sub
#End Region
#Region " Hidden methods "
' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
' NOTE: The methods can be re-enabled at any-time if needed.
''' <summary>
''' Assigns a handle to this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub AssignHandle()
End Sub
''' <summary>
''' Creates a window and its handle with the specified creation parameters.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateHandle()
End Sub
''' <summary>
''' Creates an object that contains all the relevant information required
''' to generate a proxy used to communicate with a remote object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateObjRef()
End Sub
''' <summary>
''' Invokes the default window procedure associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DefWndProc()
End Sub
''' <summary>
''' Destroys the window and its handle.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DestroyHandle()
End Sub
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub Equals()
End Sub
''' <summary>
''' Serves as the default hash function.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetHashCode()
End Sub
''' <summary>
''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetLifetimeService()
End Sub
''' <summary>
''' Obtains a lifetime service object to control the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub InitializeLifetimeService()
End Sub
''' <summary>
''' Releases the handle associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub ReleaseHandle()
End Sub
''' <summary>
''' Gets the handle for this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Property Handle()
#End Region
#Region " IDisposable "
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
Private IsDisposed As Boolean = False
''' <summary>
''' Prevent calls to methods after disposing.
''' </summary>
''' <exception cref="System.ObjectDisposedException"></exception>
Private Sub DisposedCheck()
If Me.IsDisposed Then
Throw New ObjectDisposedException(Me.GetType().FullName)
End If
End Sub
''' <summary>
''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
''' <summary>
''' Releases unmanaged and - optionally - managed resources.
''' </summary>
''' <param name="IsDisposing">
''' <c>true</c> to release both managed and unmanaged resources;
''' <c>false</c> to release only unmanaged resources.
''' </param>
Protected Sub Dispose(ByVal IsDisposing As Boolean)
If Not Me.IsDisposed Then
If IsDisposing Then
Me.form = Nothing
MyBase.ReleaseHandle()
MyBase.DestroyHandle()
End If
End If
Me.IsDisposed = True
End Sub
#End Region
End Class
' ***********************************************************************
' Author : Elektro
' Modified : 02-17-2014
' ***********************************************************************
' <copyright file="DriveWatcher.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
' ''' <summary>
' ''' The DriveWatcher instance to monitor USB devices.
' ''' </summary>
'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
' ''' <summary>
' ''' Handles the DriveInserted event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE CONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
' ''' <summary>
' ''' Handles the DriveRemoved event of the USBMonitor object.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
' Dim sb As New System.Text.StringBuilder
' sb.AppendLine("DRIVE DISCONNECTED!")
' sb.AppendLine()
' sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
' End If
'End Sub
#End Region
#Region " Imports "
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.ComponentModel
#End Region
''' <summary>
''' Device insertion/removal monitor.
''' </summary>
Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
#Region " Objects "
''' <summary>
''' The current connected drives.
''' </summary>
Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
''' <summary>
''' Indicates the drive letter of the current device.
''' </summary>
Private DriveLetter As Char = Nothing
''' <summary>
''' Indicates the current Drive information.
''' </summary>
Private CurrentDrive As DriveWatcherInfo = Nothing
''' <summary>
''' The form to manage their Windows Messages.
''' </summary>
Private WithEvents form As Form = Nothing
#End Region
#Region " Events "
''' <summary>
''' Occurs when a drive is inserted.
''' </summary>
Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
''' <summary>
''' Occurs when a drive is removed.
''' </summary>
Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
#End Region
#Region " Enumerations "
''' <summary>
''' Notifies an application of a change to the hardware configuration of a device or the computer.
''' A window receives this message through its WindowProc function.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
''' </summary>
Private Enum DeviceEvents As Integer
''' <summary>
''' The current configuration has changed, due to a dock or undock.
''' </summary>
Change = &H219
''' <summary>
''' A device or piece of media has been inserted and becomes available.
''' </summary>
Arrival = &H8000
''' <summary>
''' Request permission to remove a device or piece of media.
''' This message is the last chance for applications and drivers to prepare for this removal.
''' However, any application can deny this request and cancel the operation.
''' </summary>
QueryRemove = &H8001
''' <summary>
''' A request to remove a device or piece of media has been canceled.
''' </summary>
QueryRemoveFailed = &H8002
''' <summary>
''' A device or piece of media is being removed and is no longer available for use.
''' </summary>
RemovePending = &H8003
''' <summary>
''' A device or piece of media has been removed.
''' </summary>
RemoveComplete = &H8004
''' <summary>
''' The type volume
''' </summary>
TypeVolume = &H2
End Enum
#End Region
#Region " Structures "
''' <summary>
''' Indicates information related of a Device.
''' ( Replic of System.IO.DriveInfo )
''' </summary>
Public Structure DriveWatcherInfo
''' <summary>
''' Indicates the name of a drive, such as 'C:\'.
''' </summary>
Public Name As String
''' <summary>
''' Indicates the amount of available free space on a drive, in bytes.
''' </summary>
Public AvailableFreeSpace As Long
''' <summary>
''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
''' </summary>
Public DriveFormat As String
''' <summary>
''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
''' </summary>
Public DriveType As DriveType
''' <summary>
''' Indicates whether a drive is ready.
''' </summary>
Public IsReady As Boolean
''' <summary>
''' Indicates the root directory of a drive.
''' </summary>
Public RootDirectory As String
''' <summary>
''' Indicates the total amount of free space available on a drive, in bytes.
''' </summary>
Public TotalFreeSpace As Long
''' <summary>
''' Indicates the total size of storage space on a drive, in bytes.
''' </summary>
Public TotalSize As Long
''' <summary>
''' Indicates the volume label of a drive.
''' </summary>
Public VolumeLabel As String
''' <summary>
''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
''' </summary>
''' <param name="e">The e.</param>
Public Sub New(ByVal e As DriveInfo)
Name = e.Name
Select Case e.IsReady
Case True ' Drive is formatted and ready.
IsReady = True
DriveFormat = e.DriveFormat
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = e.VolumeLabel
TotalSize = e.TotalSize
TotalFreeSpace = e.TotalFreeSpace
AvailableFreeSpace = e.AvailableFreeSpace
Case False ' Drive is not formatted so can't retrieve data.
IsReady = False
DriveFormat = Nothing
DriveType = e.DriveType
RootDirectory = e.RootDirectory.FullName
VolumeLabel = Nothing
TotalSize = 0
TotalFreeSpace = 0
AvailableFreeSpace = 0
End Select ' e.IsReady
End Sub
End Structure
''' <summary>
''' Contains information about a logical volume.
''' For more info, see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
''' </summary>
<StructLayout(LayoutKind.Sequential)>
Private Structure DEV_BROADCAST_VOLUME
''' <summary>
''' The size of this structure, in bytes.
''' </summary>
Public Size As UInteger
''' <summary>
''' Set to DBT_DEVTYP_VOLUME (2).
''' </summary>
Public Type As UInteger
''' <summary>
''' Reserved parameter; do not use this.
''' </summary>
Public Reserved As UInteger
''' <summary>
''' The logical unit mask identifying one or more logical units.
''' Each bit in the mask corresponds to one logical drive.
''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
''' </summary>
Public Mask As UInteger
''' <summary>
''' This parameter can be one of the following values:
''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
''' '0x0002': Indicated logical volume is a network volume.
''' </summary>
Public Flags As UShort
End Structure
#End Region
#Region " Constructor "
''' <summary>
''' Initializes a new instance of this class.
''' </summary>
''' <param name="form">The form to assign.</param>
Public Sub New(ByVal form As Form)
' Assign the Formulary.
Me.form = form
End Sub
#End Region
#Region " Event Handlers "
''' <summary>
''' Assign the handle of the target Form to this NativeWindow,
''' necessary to override target Form's WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated, form.Load, form.Shown
If Not MyBase.Handle.Equals(Me.form.Handle) Then
MyBase.AssignHandle(Me.form.Handle)
End If
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
MyBase.ReleaseHandle()
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
''' </summary>
''' <param name="Device">
''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
''' </param>
''' <returns>System.Char.</returns>
Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
Dim DriveLetters As Char() =
{
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
}
Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
For X As Integer = 0 To DeviceID.Length
If DeviceID(X) Then
Return DriveLetters(X)
End If
Next X
Return Nothing
End Function
#End Region
#Region " WndProc"
''' <summary>
''' Invokes the default window procedure associated with this window to process messages for this Window.
''' </summary>
''' <param name="m">
''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
''' </param>
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case DeviceEvents.Change ' The hardware has changed.
' Transform the LParam pointer into the data structure.
Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
Select Case m.WParam.ToInt32
Case DeviceEvents.Arrival ' The device is connected.
' Get the drive letter of the connected device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Get the drive information of the connected device.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' If it's an storage device then...
If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
' Inform that the device is connected by raising the 'DriveConnected' event.
RaiseEvent DriveInserted(Me, CurrentDrive)
' Add the connected device to the dictionary, to retrieve info.
If Not CurrentDrives.ContainsKey(DriveLetter) Then
CurrentDrives.Add(DriveLetter, CurrentDrive)
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
' Get the letter of the current device being removed.
DriveLetter = GetDriveLetter(CurrentWDrive)
' If the current device being removed is not in the dictionary then...
If Not CurrentDrives.ContainsKey(DriveLetter) Then
' Get the device information of the current device being removed.
CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
' Add the current device to the dictionary,
' to retrieve info before lost it after fully-removal.
CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
End If ' Not CurrentDrives.ContainsKey(DriveLetter)
Case DeviceEvents.RemoveComplete
' Get the letter of the removed device.
DriveLetter = GetDriveLetter(CurrentWDrive)
' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
RaiseEvent DriveRemoved(Me, CurrentDrive)
' If the removed device is in the dictionary then...
If CurrentDrives.ContainsKey(DriveLetter) Then
' Remove the device from the dictionary.
CurrentDrives.Remove(DriveLetter)
End If ' CurrentDrives.ContainsKey(DriveLetter)
End Select ' m.WParam.ToInt32
End Select ' m.Msg
MyBase.WndProc(m) ' Return Message to base message handler.
End Sub
#End Region
#Region " Hidden methods "
' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
' NOTE: The methods can be re-enabled at any-time if needed.
''' <summary>
''' Assigns a handle to this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub AssignHandle()
End Sub
''' <summary>
''' Creates a window and its handle with the specified creation parameters.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateHandle()
End Sub
''' <summary>
''' Creates an object that contains all the relevant information required
''' to generate a proxy used to communicate with a remote object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateObjRef()
End Sub
''' <summary>
''' Invokes the default window procedure associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DefWndProc()
End Sub
''' <summary>
''' Destroys the window and its handle.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DestroyHandle()
End Sub
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub Equals()
End Sub
''' <summary>
''' Serves as the default hash function.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetHashCode()
End Sub
''' <summary>
''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub GetLifetimeService()
End Sub
''' <summary>
''' Obtains a lifetime service object to control the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub InitializeLifetimeService()
End Sub
''' <summary>
''' Releases the handle associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub ReleaseHandle()
End Sub
''' <summary>
''' Gets the handle for this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Property Handle()
#End Region
#Region " IDisposable "
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
Private IsDisposed As Boolean = False
''' <summary>
''' Prevent calls to methods after disposing.
''' </summary>
''' <exception cref="System.ObjectDisposedException"></exception>
Private Sub DisposedCheck()
If Me.IsDisposed Then
Throw New ObjectDisposedException(Me.GetType().FullName)
End If
End Sub
''' <summary>
''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
''' <summary>
''' Releases unmanaged and - optionally - managed resources.
''' </summary>
''' <param name="IsDisposing">
''' <c>true</c> to release both managed and unmanaged resources;
''' <c>false</c> to release only unmanaged resources.
''' </param>
Protected Sub Dispose(ByVal IsDisposing As Boolean)
If Not Me.IsDisposed Then
If IsDisposing Then
Me.form = Nothing
MyBase.ReleaseHandle()
MyBase.DestroyHandle()
End If
End If
Me.IsDisposed = True
End Sub
#End Region
End Class
Citar...FileCopy...
1er consejo: Citar...Format(IO.DriveInfo.GetDrives)...
2ndo consejo: CitarComboBox:Con todas las posibles letras de un USB o memoria extraible3er consejo:
CitarPara lo que quieres tú, la manera más sencilla es utiliza la shell de Windows.. es decir, si lo puedes hacer desde la cmd lo podrás hacer desde tu aplicación con todas las ventajas que conlleva
' GetDrivesOfType
' ( By Elektro )
'
' Usage Examples:
'
' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
'
' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
' MsgBox(Drive.Name)
' Next Drive
'
''' <summary>
''' Get all the connected drives of the given type.
''' </summary>
''' <param name="DriveType">Indicates the type of the drive.</param>
''' <returns>System.IO.DriveInfo[].</returns>
Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
Where Drive.DriveType = DriveType).ToArray
End Function
Dim Removables As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Removable)
ComboBox1.DataSource = Removables
' Format Drive
' ( By Elektro )
'
' Usage Examples:
' FormatDrive("Z")
' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
''' <summary>
''' Indicates the possible partition filesystem for Windows OS.
''' </summary>
Public Enum DriveFileSystem As Integer
' The numeric values indicates the max volume-label character-length for each filesystem.
''' <summary>
''' NTFS FileSystem.
''' </summary>
NTFS = 32
''' <summary>
''' FAT16 FileSystem.
''' </summary>
FAT16 = 11
''' <summary>
''' FAT32 FileSystem.
''' </summary>
FAT32 = FAT16
End Enum
''' <summary>
''' Formats a drive.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
''' </summary>
''' <param name="DriveLetter">
''' Indicates the drive letter to format.
''' </param>
''' <param name="FileSystem">
''' Indicates the filesystem format to use for this volume.
''' The default is "NTFS".
''' </param>
''' <param name="QuickFormat">
''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
''' without scanning the disk for bad sectors.
''' Use this option only if the disk has been previously formatted,
''' and you know that the disk is not damaged.
''' The default is <c>true</c>.
''' </param>
''' <param name="ClusterSize">
''' Disk allocation unit size—cluster size.
''' All of the filesystems organizes the hard disk based on cluster size,
''' which represents the smallest amount of disk space that can be allocated to hold a file.
''' The smaller the cluster size you use, the more efficiently your disk stores information.
''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
''' For general use, the default settings are strongly recommended.
''' </param>
''' <param name="VolumeLabel">
''' Indicates the Label to use for the new volume.
''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
''' and up to 32 characters for NTFS filesystem volumes.
''' </param>
''' <param name="EnableCompression">Not implemented.</param>
''' <returns>
''' 0 = Success.
''' 1 = Unsupported file system.
''' 2 = Incompatible media in drive.
''' 3 = Access denied.
''' 4 = Call canceled.
''' 5 = Call cancellation request too late.
''' 6 = Volume write protected.
''' 7 = Volume lock failed.
''' 8 = Unable to quick format.
''' 9 = Input/Output (I/O) error.
''' 10 = Invalid volume label.
''' 11 = No media in drive.
''' 12 = Volume is too small.
''' 13 = Volume is too large.
''' 14 = Volume is not mounted.
''' 15 = Cluster size is too small.
''' 16 = Cluster size is too large.
''' 17 = Cluster size is beyond 32 bits.
''' 18 = Unknown error.
''' </returns>
Public Function FormatDrive(ByVal DriveLetter As Char,
Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
Optional ByVal QuickFormat As Boolean = True,
Optional ByVal ClusterSize As Integer = Nothing,
Optional ByVal VolumeLabel As String = Nothing,
Optional ByVal EnableCompression As Boolean = False) As Integer
' Volume-label error check.
If Not String.IsNullOrEmpty(VolumeLabel) Then
If VolumeLabel.Length > FileSystem Then
Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
FileSystem.ToString, CStr(FileSystem)))
End If
End If
Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
Convert.ToString(DriveLetter))
Using WMI As New ManagementObjectSearcher(Query)
Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
InvokeMethod("Format",
New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
End Using
Return 18 ' Unknown error.
End Function
Cita de: Car0nte en 16 Febrero 2014, 17:52 PMPD: Elektro, estoy probando tu código y me da problemas con ShortcutManager.ShortcutInfo Será cosa mía... echaré un vistazo en msdn.