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

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 5 Visitantes están viendo este tema.
Páginas: 1 ... 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 [33] 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 527,158 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #320 en: 15 Octubre 2013, 10:12 am »

Las siguientes funciones pueden adaptarlas fácilmente para pasarle el handle de la ventana, yo preferí usar diréctamente el nombre del proceso en cuestión.





Mueve la ventana de un proceso

Código
  1. #Region " Move Process Window "
  2.  
  3.    ' [ Move Process Window ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Move the notepad window at 10,50 (X,Y)
  10.    ' Move_Process_Window("notepad.exe", 10, 50)
  11.    '
  12.    ' Move the notepad window at 10 (X) and preserving the original (Y) process window position
  13.    ' Move_Process_Window("notepad.exe", 10, Nothing)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  16.    Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As Rectangle) As Boolean
  17.    End Function
  18.  
  19.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, Width As Integer, Height As Integer, repaint As Boolean) As Boolean
  21.    End Function
  22.  
  23.    Private Sub Move_Process_Window(ByVal ProcessName As String, ByVal X As Integer, ByVal Y As Integer)
  24.  
  25.        ProcessName = If(ProcessName.ToLower.EndsWith(".exe"), _
  26.                         ProcessName.Substring(0, ProcessName.LastIndexOf(".")), _
  27.                         ProcessName)
  28.  
  29.        Dim rect As Rectangle = Nothing
  30.        Dim proc As Process = Nothing
  31.  
  32.        Try
  33.            ' Find the process
  34.            proc = Process.GetProcessesByName(ProcessName).First
  35.  
  36.            ' Store the process Main Window positions and sizes into the Rectangle.
  37.            GetWindowRect(proc.MainWindowHandle, rect)
  38.  
  39.            ' Move the Main Window
  40.            MoveWindow(proc.MainWindowHandle, _
  41.                       If(Not X = Nothing, X, rect.Left), _
  42.                       If(Not Y = Nothing, Y, rect.Top), _
  43.                       (rect.Width - rect.Left), _
  44.                       (rect.Height - rect.Top), _
  45.                       True)
  46.  
  47.        Catch ex As InvalidOperationException
  48.            'Throw New Exception("Process not found.")
  49.            MessageBox.Show("Process not found.", Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  50.  
  51.        Finally
  52.            rect = Nothing
  53.            If proc IsNot Nothing Then proc.Dispose()
  54.  
  55.        End Try
  56.  
  57.    End Sub
  58.  
  59. #End Region





Redimensiona la ventana de un proceso

Código
  1. #Region " Resize Process Window "
  2.  
  3.    ' [ Resize Process Window ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '        
  9.    ' Resize the notepad window at 500x250 (Width x Height)
  10.    ' Resize_Process_Window("notepad.exe", 500, 250)
  11.    '
  12.    ' Resize the notepad window at 500 (Width) and preserving the original (Height) process window size.
  13.    ' Resize_Process_Window("notepad.exe", 500, Nothing)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  16.    Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As Rectangle) As Boolean
  17.    End Function
  18.  
  19.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, Width As Integer, Height As Integer, repaint As Boolean) As Boolean
  21.    End Function
  22.  
  23.    Private Sub Resize_Process_Window(ByVal ProcessName As String, _
  24.                                      ByVal Width As Integer, _
  25.                                      ByVal Height As Integer)
  26.  
  27.        ProcessName = If(ProcessName.ToLower.EndsWith(".exe"), _
  28.                         ProcessName.Substring(0, ProcessName.LastIndexOf(".")), _
  29.                         ProcessName)
  30.  
  31.        Dim rect As Rectangle = Nothing
  32.        Dim proc As Process = Nothing
  33.  
  34.        Try
  35.            ' Find the process
  36.            proc = Process.GetProcessesByName(ProcessName).First
  37.  
  38.            ' Store the process Main Window positions and sizes into the Rectangle.
  39.            GetWindowRect(proc.MainWindowHandle, rect)
  40.  
  41.            ' Resize the Main Window
  42.            MoveWindow(proc.MainWindowHandle, _
  43.                       rect.Left, _
  44.                       rect.Top, _
  45.                       If(Not Width = Nothing, Width, (rect.Width - rect.Left)), _
  46.                       If(Not Height = Nothing, Height, (rect.Height - rect.Top)), _
  47.                       True)
  48.  
  49.        Catch ex As InvalidOperationException
  50.            'Throw New Exception("Process not found.")
  51.            MessageBox.Show("Process not found.", Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  52.  
  53.        Finally
  54.            rect = Nothing
  55.            If proc IsNot Nothing Then proc.Dispose()
  56.  
  57.        End Try
  58.  
  59.    End Sub
  60.  
  61. #End Region
  62.  




Desplaza la posición de la ventana de un proceso

Código
  1. #Region " Shift Process Window Position "
  2.  
  3.    ' [ Shift Process Window Position ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Shift the notepad window +10,-50 (X,Y)
  10.    ' Shift_Process_Window_Position("notepad.exe", +10, -50)
  11.    '
  12.    ' Shift the notepad window +10 (X) and preserving the original (Y) position
  13.    ' Shift_Process_Window_Position_Position("notepad.exe", +10, Nothing)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  16.    Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As Rectangle) As Boolean
  17.    End Function
  18.  
  19.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, Width As Integer, Height As Integer, repaint As Boolean) As Boolean
  21.    End Function
  22.  
  23.    Private Sub Shift_Process_Window_Position(ByVal ProcessName As String, ByVal X As Integer, ByVal Y As Integer)
  24.  
  25.        ProcessName = If(ProcessName.ToLower.EndsWith(".exe"), _
  26.                         ProcessName.Substring(0, ProcessName.LastIndexOf(".")), _
  27.                         ProcessName)
  28.  
  29.        Dim rect As Rectangle = Nothing
  30.        Dim proc As Process = Nothing
  31.  
  32.        Try
  33.            ' Find the process
  34.            proc = Process.GetProcessesByName(ProcessName).First
  35.  
  36.            ' Store the process Main Window positions and sizes into the Rectangle.
  37.            GetWindowRect(proc.MainWindowHandle, rect)
  38.  
  39.            ' Move the Main Window
  40.            MoveWindow(proc.MainWindowHandle, _
  41.                       If(Not X = Nothing, rect.Left + X, rect.Left), _
  42.                       If(Not Y = Nothing, rect.Top + Y, rect.Top), _
  43.                       (rect.Width - rect.Left), _
  44.                       (rect.Height - rect.Top), _
  45.                       True)
  46.  
  47.        Catch ex As InvalidOperationException
  48.            'Throw New Exception("Process not found.")
  49.            MessageBox.Show("Process not found.", Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  50.  
  51.        Finally
  52.            rect = Nothing
  53.            If proc IsNot Nothing Then proc.Dispose()
  54.  
  55.        End Try
  56.  
  57.    End Sub
  58.  
  59. #End Region





Desplaza el tamaño de la ventana de un proceso

Código
  1. #Region " Shift Process Window Size "
  2.  
  3.    ' [ Shift Process Window Size ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '        
  9.    ' Shift the size of notepad window to +10 Width and -5 Height
  10.    ' Shift_Process_Window_Size("notepad.exe", +10, -5)
  11.    '
  12.    ' Shift the size of notepad window to +10 Width and preserving the original Height process window size.
  13.    ' Shift_Process_Window_Size("notepad.exe", +10, Nothing)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  16.    Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As Rectangle) As Boolean
  17.    End Function
  18.  
  19.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, Width As Integer, Height As Integer, repaint As Boolean) As Boolean
  21.    End Function
  22.  
  23.    Private Sub Shift_Process_Window_Size(ByVal ProcessName As String, _
  24.                                      ByVal Width As Integer, _
  25.                                      ByVal Height As Integer)
  26.  
  27.        ProcessName = If(ProcessName.ToLower.EndsWith(".exe"), _
  28.                         ProcessName.Substring(0, ProcessName.LastIndexOf(".")), _
  29.                         ProcessName)
  30.  
  31.        Dim rect As Rectangle = Nothing
  32.        Dim proc As Process = Nothing
  33.  
  34.        Try
  35.            ' Find the process
  36.            proc = Process.GetProcessesByName(ProcessName).First
  37.  
  38.            ' Store the process Main Window positions and sizes into the Rectangle.
  39.            GetWindowRect(proc.MainWindowHandle, rect)
  40.  
  41.            ' Resize the Main Window
  42.            MoveWindow(proc.MainWindowHandle, _
  43.                       rect.Left, _
  44.                       rect.Top, _
  45.                       If(Not Width = Nothing, (rect.Width - rect.Left) + Width, (rect.Width - rect.Left)), _
  46.                       If(Not Height = Nothing, (rect.Height - rect.Top) + Height, (rect.Height - rect.Top)), _
  47.                       True)
  48.  
  49.        Catch ex As InvalidOperationException
  50.            'Throw New Exception("Process not found.")
  51.            MessageBox.Show("Process not found.", Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  52.  
  53.        Finally
  54.            rect = Nothing
  55.            If proc IsNot Nothing Then proc.Dispose()
  56.  
  57.        End Try
  58.  
  59.    End Sub
  60.  
  61. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #321 en: 17 Octubre 2013, 13:37 pm »

Volver todos los elementos de un Array a Lower-Case:

Código
  1. #Region " Array ToLower-Case "
  2.  
  3.    ' [ Array ToLower-Case ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim Elements As IEnumerable = Array_ToLowerCase({"abC", "DEf", "GhI", Nothing, ""})
  10.  
  11.    Private Function Array_ToLowerCase(ByVal [Array] As IEnumerable) As IEnumerable
  12.  
  13.        Return From str In [Array] _
  14.               Select If(String.IsNullOrEmpty(str), _
  15.                         String.Empty, str.ToLower())
  16.  
  17.    End Function
  18.  
  19. #End Region





Volver todos los elementos de un Array a Upper-Case:

Código
  1. #Region " Array_ToUpperCase "
  2.  
  3.    ' [ Array_ToUpperCase ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim Elements As IEnumerable = Array_ToUpperCase({"abC", "DEf", "GhI", Nothing, ""})
  10.  
  11.    Private Function Array_ToUpperCase(ByVal [Array] As IEnumerable) As IEnumerable
  12.  
  13.        Return From str In [Array] _
  14.               Select If(String.IsNullOrEmpty(str), _
  15.                         String.Empty, str.ToUpper())
  16.  
  17.    End Function
  18.  
  19. #End Region





101 Ejemplos de como usar LINQ: http://msdn.microsoft.com/en-us/vstudio/bb688088.aspx





Ejemplos de uso de la librería "TypedUnits" -> http://www.codeproject.com/Articles/611731/Working-with-Units-and-Amounts

Sirve para manejar cálculos y convertir casi todo tipo de unidades a otras unidades (Ej: Newtons, kilometros, kilogramos).


Código
  1.         Dim Conversion As TypedUnits.Amount = _
  2.             TypedUnits.UnitManager.ConvertTo(New TypedUnits.Amount( _
  3.                                              2, _
  4.                                              StandardUnits.TimeUnits.Minute), _
  5.                                              StandardUnits.TimeUnits.Second)
  6.  
  7.         MsgBox(Conversion.Value & " Seconds") ' Result: 120 Seconds
  8.  
  9.  
  10.         Dim unit As TypedUnits.Amount = _
  11.             New TypedUnits.Amount(1, StandardUnits.LengthUnits.KiloMeter)
  12.  
  13.         MsgBox(unit.Unit.Factor) ' Result: 1000


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #322 en: 19 Octubre 2013, 13:03 pm »

Mutear la aplicación:

Código
  1. #Region " Mute Application "
  2.  
  3.    ' [ Mute Application ]
  4.    '
  5.    ' Examples :
  6.    ' MuteApplication()
  7.  
  8.    <System.Runtime.InteropServices.DllImport("winmm.dll")> _
  9.    Private Shared Function waveOutSetVolume(hwo As IntPtr, dwVolume As UInteger) As Integer
  10.    End Function
  11.  
  12.    Public Shared Sub MuteApplication()
  13.        Dim NewVolume As Integer = 0
  14.        Dim NewVolumeAllChannels As UInteger = ((CUInt(NewVolume) And &HFFFF) Or (CUInt(NewVolume) << 16))
  15.        waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels)
  16.    End Sub
  17.  
  18. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #323 en: 20 Octubre 2013, 20:03 pm »

· Seleccionar items en un Listbox sin que el Listbox salte a la posición del nuevo item seleccionado.

Código
  1. #Region " [ListBox] Select item without jump "
  2.  
  3.    ' [ListBox] Select item without jump
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Select_Item_Without_Jump(ListBox1, 50, ListBoxItemSelected.Select)
  10.    '
  11.    ' For x As Integer = 0 To ListBox1.Items.Count - 1
  12.    '    Select_Item_Without_Jump(ListBox1, x, ListBoxItemSelected.Select)
  13.    ' Next
  14.  
  15.    Public Enum ListBoxItemSelected
  16.        [Select] = 1
  17.        [Unselect] = 0
  18.    End Enum
  19.  
  20.    Public Shared Sub Select_Item_Without_Jump(lb As ListBox, index As Integer, selected As ListBoxItemSelected)
  21.        Dim i As Integer = lb.TopIndex ' Store the selected item index
  22.        lb.BeginUpdate() ' Disable drawing on control
  23.        lb.SetSelected(index, selected) ' Select the item
  24.        lb.TopIndex = i ' Jump to the previous selected item
  25.        lb.EndUpdate() ' Eenable drawing
  26.    End Sub
  27.  
  28. #End Region





· Desactivar/Activar el Dibujado (Drawing) en un control

Código
  1. #Region " Enable-Disable Drawing on Control"
  2.  
  3.    ' Enable-Disable Drawing on Control
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' To disable drawing:
  10.    ' Control_Drawing(ListBox1, DrawingEnabled.Disable)
  11.    '  
  12.    ' To enable drawing:
  13.    ' Control_Drawing(ListBox1, DrawingEnabled.Enable)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll", _
  16.    EntryPoint:="LockWindowUpdate", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  17.    Public Shared Function LockWindow(Handle As IntPtr) As IntPtr
  18.    End Function
  19.  
  20.    Private Enum DrawingEnabled
  21.        Enable
  22.        Disable
  23.    End Enum
  24.  
  25.    Private Sub Control_Drawing(ByVal ctrl As Control, ByVal DrawingEnabled As DrawingEnabled)
  26.  
  27.        Select Case DrawingEnabled
  28.  
  29.            Case DrawingEnabled.Enable
  30.                LockWindow(ctrl.Handle)
  31.                LockWindow(IntPtr.Zero)
  32.  
  33.  
  34.            Case DrawingEnabled.Disable
  35.                LockWindow(ctrl.Handle)
  36.  
  37.        End Select
  38.  
  39.    End Sub
  40.  
  41. #End Region
« Última modificación: 22 Octubre 2013, 16:19 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #324 en: 21 Octubre 2013, 14:07 pm »

Una Class que nos facilitará mucho la tarea de descargar archivos de forma asincronica, para descargar archivos de forma simultanea.

Código
  1. #Region " DownloadFileAsyncExtended "
  2.  
  3. #Region " Usage Examples "
  4.  
  5. ' Public Class Form1
  6. '
  7. ' ' // Instance a new Downlaoder Class
  8. ' Private WithEvents Downloader As New DownloadFileAsyncExtended
  9. '
  10. ' ' // create a listview to update.
  11. ' Private lv As New ListView With {.View = View.Details, .Dock = DockStyle.Fill}
  12. '
  13. ' ' // create a listview item to update.
  14. ' Private lvi As New ListViewItem
  15. '
  16. ' ' // Set an url file to downloads.
  17. ' Dim url As String = "http://msft.digitalrivercontent.net/win/X17-58857.iso"
  18.  
  19.  
  20. ' Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  21. '
  22. '     ' Add columns to listview.
  23. '     lv.Columns.AddRange({New ColumnHeader With {.Text = "Filename"}, _
  24. '                          New ColumnHeader With {.Text = "Size"}, _
  25. '                          New ColumnHeader With {.Text = "Status"}, _
  26. '                          New ColumnHeader With {.Text = "Completed"}, _
  27. '                          New ColumnHeader With {.Text = "Progress"}, _
  28. '                          New ColumnHeader With {.Text = "Speed"}, _
  29. '                          New ColumnHeader With {.Text = "Time Elapsed"}, _
  30. '                          New ColumnHeader With {.Text = "Time Left"} _
  31. '                        })
  32. '
  33. '     ' Add subitems to listview item.
  34. '     lvi.SubItems.AddRange({"Filename", "Size", "Status", "Completed", "Progress", "Speed", "Time Elapsed", "Time Left"})
  35. '
  36. '     ' Add a Object tag to the listview item,
  37. '     ' so later we can reffer to this download to pause/resume or cancel it.
  38. '     lvi.Tag = Downloader
  39. '
  40. '     ' Add the Listview control into the UI.
  41. '     Me.Controls.Add(lv)
  42. '     ' Add the Listview item into the Listview.
  43. '     lv.Items.Add(lvi)
  44. '
  45. '     ' Set Application simultaneous internet downloads limit.
  46. '     Net.ServicePointManager.DefaultConnectionLimit = 5
  47. '
  48. '     '// IMPORTANT !!
  49. '     '// If you don't add this line, then all events are raised on a separate thread,
  50. '     '// and you will get cross-thread errors when accessing the Listview,
  51. '     '// or other controls directly in the raised events.
  52. '     Downloader.SynchronizingObject = Me
  53. '
  54. '     '// Update frequency.
  55. '     '// A value higher than 500 ms will prevent the DownloadProgressChanged event,
  56. '     '// from firing continuously and hogging CPU when updating the controls.
  57. '     '// If you download small files that could be downloaded within a second,
  58. '     '// then set it to "NoDelay" or the progress might not be visible.
  59. '     Downloader.ProgressUpdateFrequency = DownloadFileAsyncExtended.UpdateFrequency.MilliSeconds_500
  60. '
  61. '     '// The method to actually download a file. The "userToken" parameter can,
  62. '     '// for example be a control you wish to update in the DownloadProgressChanged,
  63. '     '// and DownloadCompleted events. It is a ListViewItem in this example.
  64. '     Downloader.DowloadFileAsync(url, "C:\Downloaded file.iso", lvi)
  65. '
  66. ' End Sub
  67.  
  68.  
  69. ' '// This event allows you to show the download progress to the user.
  70. '
  71. ' ' e.BytesReceived = Bytes received so far.
  72. ' ' e.DownloadSpeedBytesPerSec = Download speed in bytes per second.
  73. ' ' e.DownloadTimeSeconds = Download time in seconds so far.
  74. ' ' e.ProgressPercentage = Percentage of the file downloaded.
  75. ' ' e.RemainingTimeSeconds = Remaining download time in seconds.
  76. ' ' e.TotalBytesToReceive = Total size of the file that is being downloaded.
  77. ' ' e.userToken = Usually the control(s) you wish to update.
  78. ' Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As FileDownloadProgressChangedEventArgs) _
  79. ' Handles Downloader.DownloadProgressChanged
  80. '
  81. '     ' Get the ListViewItem we passed as "userToken" parameter, so we can update it.
  82. '     Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  83. '
  84. '     ' Update the ListView item subitems.
  85. '     lvi.SubItems(0).Text = url
  86. '     lvi.SubItems(1).Text = String.Format("{0:#,#} KB", (e.TotalBytesToReceive / 1024))
  87. '     lvi.SubItems(2).Text = "Downloading"
  88. '     lvi.SubItems(3).Text = String.Format("{0:#,#} KB", (e.BytesReceived / 1024))
  89. '     lvi.SubItems(4).Text = e.ProgressPercentage & "%"
  90. '     lvi.SubItems(5).Text = (e.DownloadSpeedBytesPerSec \ 1024).ToString & " kB/s"
  91. '     lvi.SubItems(6).Text = String.Format("{0}:{1}:{2}", _
  92. '                            (e.DownloadTimeSeconds \ 3600).ToString("00"), _
  93. '                            ((e.DownloadTimeSeconds Mod 3600) \ 60).ToString("00"), _
  94. '                            (e.DownloadTimeSeconds Mod 60).ToString("00"))
  95. '     lvi.SubItems(7).Text = String.Format("{0}:{1}:{2}", _
  96. '                            (e.RemainingTimeSeconds \ 3600).ToString("00"), _
  97. '                            ((e.RemainingTimeSeconds Mod 3600) \ 60).ToString("00"), _
  98. '                            (e.RemainingTimeSeconds Mod 60).ToString("00"))
  99. '
  100. ' End Sub
  101.  
  102.  
  103. ' '// This event lets you know when the download is complete.
  104. ' '// The download finished successfully, the user cancelled the download or there was an error.
  105. ' Private Sub DownloadCompleted(ByVal sender As Object, ByVal e As FileDownloadCompletedEventArgs) _
  106. ' Handles Downloader.DownloadCompleted
  107. '
  108. '     ' Get the ListViewItem we passed as userToken parameter, so we can update it.
  109. '     Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  110. '
  111. '     If e.ErrorMessage IsNot Nothing Then ' Was there an error.
  112. '
  113. '         lvi.SubItems(2).Text = "Error: " & e.ErrorMessage.Message.ToString
  114. '
  115. '         ' Set an Error ImageKey.
  116. '         ' lvi.ImageKey = "Error"
  117. '
  118. '     ElseIf e.Cancelled Then ' The user cancelled the download.
  119. '
  120. '         lvi.SubItems(2).Text = "Paused"
  121. '
  122. '         ' Set a Paused ImageKey.
  123. '         ' lvi.ImageKey = "Paused"
  124. '
  125. '     Else ' Download was successful.
  126. '
  127. '         lvi.SubItems(2).Text = "Finished"
  128. '
  129. '         ' Set a Finished ImageKey.
  130. '         ' lvi.ImageKey = "Finished"
  131. '
  132. '     End If
  133. '
  134. '     ' Set Tag to Nothing in order to remove the wClient class instance,
  135. '     ' so this way we know we can't resume the download.
  136. '     lvi.Tag = Nothing
  137. '
  138. ' End Sub
  139.  
  140.  
  141. ' '// To Resume a file:
  142. ' ' Download_Helper.Resume_Download(lvi.Tag)
  143.  
  144. ' '// To pause or cancel a file:
  145. ' ' Download_Helper.PauseCancel_Download(lvi.Tag)
  146.  
  147.  
  148. ' End Class
  149.  
  150. #End Region
  151.  
  152. Imports System.IO
  153. Imports System.Net
  154. Imports System.Threading
  155.  
  156. '// This is the main download class.
  157. Public Class DownloadFileAsyncExtended
  158.  
  159. #Region "Methods"
  160.  
  161.    Private _URL As String = String.Empty
  162.    Private _LocalFilePath As String = String.Empty
  163.    Private _userToken As Object = Nothing
  164.    Private _ContentLenght As Long = 0
  165.    Private _TotalBytesReceived As Long = 0
  166.  
  167.    '// Start the asynchronous download.
  168.    Public Sub DowloadFileAsync(ByVal URL As String, ByVal LocalFilePath As String, ByVal userToken As Object)
  169.  
  170.        Dim Request As HttpWebRequest
  171.        Dim fileURI As New Uri(URL) '// Will throw exception if empty or random string.
  172.  
  173.        '// Make sure it's a valid http:// or https:// url.
  174.        If fileURI.Scheme <> Uri.UriSchemeHttp And fileURI.Scheme <> Uri.UriSchemeHttps Then
  175.            Throw New Exception("Invalid URL. Must be http:// or https://")
  176.        End If
  177.  
  178.        '// Save this to private variables in case we need to resume.
  179.        _URL = URL
  180.        _LocalFilePath = LocalFilePath
  181.        _userToken = userToken
  182.  
  183.        '// Create the request.
  184.        Request = CType(HttpWebRequest.Create(New Uri(URL)), HttpWebRequest)
  185.        Request.Credentials = Credentials
  186.        Request.AllowAutoRedirect = True
  187.        Request.ReadWriteTimeout = 30000
  188.        Request.Proxy = Proxy
  189.        Request.KeepAlive = False
  190.        Request.Headers = _Headers '// NOTE: Will throw exception if wrong headers supplied.
  191.  
  192.        '// If we're resuming, then add the AddRange header.
  193.        If _ResumeAsync Then
  194.            Dim FileInfo As New FileInfo(LocalFilePath)
  195.            If FileInfo.Exists Then
  196.                Request.AddRange(FileInfo.Length)
  197.            End If
  198.        End If
  199.  
  200.        '// Signal we're busy downloading
  201.        _isbusy = True
  202.  
  203.        '// Make sure this is set to False or the download will stop immediately.
  204.        _CancelAsync = False
  205.  
  206.        '// This is the data we're sending to the GetResponse Callback.
  207.        Dim State As New HttpWebRequestState(LocalFilePath, Request, _ResumeAsync, userToken)
  208.  
  209.        '// Begin to get a response from the server.
  210.        Dim result As IAsyncResult = Request.BeginGetResponse(AddressOf GetResponse_Callback, State)
  211.  
  212.        '// Add custom 30 second timeout for connecting.
  213.        '// The Timeout property is ignored when using the asynchronous BeginGetResponse.
  214.        ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf TimeoutCallback), State, 30000, True)
  215.  
  216.    End Sub
  217.  
  218.    '// Here we receive the response from the server. We do not check for the "Accept-Ranges"
  219.    '// response header, in order to find out if the server supports resuming, because it MAY
  220.    '// send the "Accept-Ranges" response header, but is not required to do so. This is
  221.    '// unreliable, so we'll just continue and catch the exception that will occur if not
  222.    '// supported and send it the DownloadCompleted event. We also don't check if the
  223.    '// Content-Length is '-1', because some servers return '-1', eventhough the file/webpage
  224.    '// you're trying to download is valid. e.ProgressPercentage returns '-1' in that case.
  225.    Private Sub GetResponse_Callback(ByVal result As IAsyncResult)
  226.  
  227.        Dim State As HttpWebRequestState = CType(result.AsyncState, HttpWebRequestState)
  228.        Dim DestinationStream As FileStream = Nothing
  229.        Dim Response As HttpWebResponse = Nothing
  230.        Dim Duration As New Stopwatch
  231.        Dim Buffer(8191) As Byte
  232.        Dim BytesRead As Long = 0
  233.        Dim ElapsedSeconds As Long = 0
  234.        Dim DownloadSpeed As Long = 0
  235.        Dim DownloadProgress As Long = 0
  236.        Dim BytesReceivedThisSession As Long = 0
  237.  
  238.        ''// Get response
  239.        Response = CType(State.Request.EndGetResponse(result), HttpWebResponse)
  240.  
  241.        '// Asign Response headers to ReadOnly ResponseHeaders property.
  242.        _ResponseHeaders = Response.Headers
  243.  
  244.        '// If the server does not reply with an 'OK (200)' message when starting
  245.        '// the download or a 'PartialContent (206)' message when resuming.
  246.        If Response.StatusCode <> HttpStatusCode.OK And Response.StatusCode <> HttpStatusCode.PartialContent Then
  247.            '// Send error message to anyone who is listening.
  248.            OnDownloadCompleted(New FileDownloadCompletedEventArgs(New Exception(Response.StatusCode), False, State.userToken))
  249.            Return
  250.        End If
  251.  
  252.        '// Create/open the file to write to.
  253.        If State.ResumeDownload Then
  254.            '// If resumed, then create or open the file.
  255.            DestinationStream = New FileStream(State.LocalFilePath, FileMode.OpenOrCreate, FileAccess.Write)
  256.        Else
  257.            '// If not resumed, then create the file, which will delete the existing file if it already exists.
  258.            DestinationStream = New FileStream(State.LocalFilePath, FileMode.Create, FileAccess.Write)
  259.            '// Get the ContentLength only when we're starting the download. Not when resuming.
  260.            _ContentLenght = Response.ContentLength
  261.        End If
  262.  
  263.        '// Moves stream position to beginning of the file when starting the download.
  264.        '// Moves stream position to end of the file when resuming the download.
  265.        DestinationStream.Seek(0, SeekOrigin.End)
  266.  
  267.        '// Start timer to get download duration / download speed, etc.
  268.        Duration.Start()
  269.  
  270.        '// Get the Response Stream.
  271.        Using responseStream As Stream = Response.GetResponseStream()
  272.            Do
  273.                '// Read some bytes.
  274.                BytesRead = responseStream.Read(Buffer, 0, Buffer.Length)
  275.  
  276.                If BytesRead > 0 Then
  277.                    '// Write incoming data to the file.
  278.                    DestinationStream.Write(Buffer, 0, BytesRead)
  279.                    '// Count the total number of bytes downloaded.
  280.                    _TotalBytesReceived += BytesRead
  281.                    '// Count the number of bytes downloaded this session (Resume).
  282.                    BytesReceivedThisSession += BytesRead
  283.                    '// Get number of elapsed seconds (need round number to prevent 'division by zero' error).
  284.                    ElapsedSeconds = CLng(Duration.Elapsed.TotalSeconds)
  285.  
  286.                    '// Update frequency
  287.                    If (Duration.ElapsedMilliseconds - DownloadProgress) >= ProgressUpdateFrequency Then
  288.                        DownloadProgress = Duration.ElapsedMilliseconds
  289.                        '// Calculate download speed in bytes per second.
  290.                        If ElapsedSeconds > 0 Then
  291.                            DownloadSpeed = (BytesReceivedThisSession \ ElapsedSeconds)
  292.                        End If
  293.                        '// Send download progress to anyone who is listening.
  294.                        OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, ElapsedSeconds, DownloadSpeed, State.userToken))
  295.                    End If
  296.  
  297.                    '// Exit loop when paused.
  298.                    If _CancelAsync Then Exit Do
  299.  
  300.                End If
  301.            Loop Until BytesRead = 0
  302.  
  303.        End Using
  304.  
  305.        Try
  306.            '// Send download progress once more. If the UpdateFrequency has been set to
  307.            '// HalfSecond or Seconds, then the last percentage returned might be 98% or 99%.
  308.            '// This makes sure it's 100%.
  309.            OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, Duration.Elapsed.TotalSeconds, DownloadSpeed, State.userToken))
  310.  
  311.            If _CancelAsync Then
  312.                '// Send completed message (Paused) to anyone who is listening.
  313.                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, True, State.userToken))
  314.            Else
  315.                '// Send completed message (Finished) to anyone who is listening.
  316.                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, False, State.userToken))
  317.            End If
  318.  
  319.        Catch ex As Exception
  320.            '// Send completed message (Error) to anyone who is listening.
  321.            OnDownloadCompleted(New FileDownloadCompletedEventArgs(ex, False, State.userToken))
  322.  
  323.        Finally
  324.            '// Close the file.
  325.            If DestinationStream IsNot Nothing Then
  326.                DestinationStream.Flush()
  327.                DestinationStream.Close()
  328.                DestinationStream = Nothing
  329.            End If
  330.            '// Stop and reset the duration timer.
  331.            Duration.Reset()
  332.            Duration = Nothing
  333.            '// Signal we're not downloading anymore.
  334.            _isbusy = False
  335.  
  336.        End Try
  337.  
  338.    End Sub
  339.  
  340.    '// Here we will abort the download if it takes more than 30 seconds to connect, because
  341.    '// the Timeout property is ignored when using the asynchronous BeginGetResponse.
  342.    Private Sub TimeoutCallback(ByVal State As Object, ByVal TimedOut As Boolean)
  343.  
  344.        If TimedOut Then
  345.            Dim RequestState As HttpWebRequestState = CType(State, HttpWebRequestState)
  346.            If RequestState IsNot Nothing Then
  347.                RequestState.Request.Abort()
  348.            End If
  349.        End If
  350.  
  351.    End Sub
  352.  
  353.    '// Cancel the asynchronous download.
  354.    Private _CancelAsync As Boolean = False
  355.    Public Sub CancelAsync()
  356.        _CancelAsync = True
  357.    End Sub
  358.  
  359.    '// Resume the asynchronous download.
  360.    Private _ResumeAsync As Boolean = False
  361.    Public Sub ResumeAsync()
  362.  
  363.        '// Throw exception if download is already in progress.
  364.        If _isbusy Then
  365.            Throw New Exception("Download is still busy. Use IsBusy property to check if download is already busy.")
  366.        End If
  367.  
  368.        '// Throw exception if URL or LocalFilePath is empty, which means
  369.        '// the download wasn't even started yet with DowloadFileAsync.
  370.        If String.IsNullOrEmpty(_URL) AndAlso String.IsNullOrEmpty(_LocalFilePath) Then
  371.            Throw New Exception("Cannot resume a download which hasn't been started yet. Call DowloadFileAsync first.")
  372.        Else
  373.            '// Set _ResumeDownload to True, so we know we need to add
  374.            '// the Range header in order to resume the download.
  375.            _ResumeAsync = True
  376.            '// Restart (Resume) the download.
  377.            DowloadFileAsync(_URL, _LocalFilePath, _userToken)
  378.        End If
  379.  
  380.    End Sub
  381.  
  382. #End Region
  383.  
  384. #Region "Properties"
  385.  
  386.    Public Enum UpdateFrequency
  387.        _NoDelay = 0
  388.        MilliSeconds_100 = 100
  389.        MilliSeconds_200 = 200
  390.        MilliSeconds_300 = 300
  391.        MilliSeconds_400 = 400
  392.        MilliSeconds_500 = 500
  393.        MilliSeconds_600 = 600
  394.        MilliSeconds_700 = 700
  395.        MilliSeconds_800 = 800
  396.        MilliSeconds_900 = 900
  397.        Seconds_1 = 1000
  398.        Seconds_2 = 2000
  399.        Seconds_3 = 3000
  400.        Seconds_4 = 4000
  401.        Seconds_5 = 5000
  402.        Seconds_6 = 6000
  403.        Seconds_7 = 7000
  404.        Seconds_8 = 8000
  405.        Seconds_9 = 9000
  406.        Seconds_10 = 10000
  407.    End Enum
  408.  
  409.    '// Progress Update Frequency.
  410.    Public Property ProgressUpdateFrequency() As UpdateFrequency
  411.  
  412.    '// Proxy.
  413.    Public Property Proxy() As IWebProxy
  414.  
  415.    '// Credentials.
  416.    Public Property Credentials() As ICredentials
  417.  
  418.    '// Headers.
  419.    Public Property Headers() As New WebHeaderCollection
  420.  
  421.    '// Is download busy.
  422.    Private _isbusy As Boolean = False
  423.    Public ReadOnly Property IsBusy() As Boolean
  424.        Get
  425.            Return _isbusy
  426.        End Get
  427.    End Property
  428.  
  429.    '// ResponseHeaders.
  430.    Private _ResponseHeaders As WebHeaderCollection = Nothing
  431.    Public ReadOnly Property ResponseHeaders() As WebHeaderCollection
  432.        Get
  433.            Return _ResponseHeaders
  434.        End Get
  435.    End Property
  436.  
  437.    '// SynchronizingObject property to marshal events back to the UI thread.
  438.    Private _synchronizingObject As System.ComponentModel.ISynchronizeInvoke
  439.    Public Property SynchronizingObject() As System.ComponentModel.ISynchronizeInvoke
  440.        Get
  441.            Return Me._synchronizingObject
  442.        End Get
  443.        Set(ByVal value As System.ComponentModel.ISynchronizeInvoke)
  444.            Me._synchronizingObject = value
  445.        End Set
  446.    End Property
  447.  
  448. #End Region
  449.  
  450. #Region "Events"
  451.  
  452.    Public Event DownloadProgressChanged As EventHandler(Of FileDownloadProgressChangedEventArgs)
  453.    Private Delegate Sub DownloadProgressChangedEventInvoker(ByVal e As FileDownloadProgressChangedEventArgs)
  454.    Protected Overridable Sub OnDownloadProgressChanged(ByVal e As FileDownloadProgressChangedEventArgs)
  455.        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
  456.            'Marshal the call to the thread that owns the synchronizing object.
  457.            Me.SynchronizingObject.Invoke(New DownloadProgressChangedEventInvoker(AddressOf OnDownloadProgressChanged), _
  458.                                          New Object() {e})
  459.        Else
  460.            RaiseEvent DownloadProgressChanged(Me, e)
  461.        End If
  462.    End Sub
  463.  
  464.    Public Event DownloadCompleted As EventHandler(Of FileDownloadCompletedEventArgs)
  465.    Private Delegate Sub DownloadCompletedEventInvoker(ByVal e As FileDownloadCompletedEventArgs)
  466.    Protected Overridable Sub OnDownloadCompleted(ByVal e As FileDownloadCompletedEventArgs)
  467.        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
  468.            'Marshal the call to the thread that owns the synchronizing object.
  469.            Me.SynchronizingObject.Invoke(New DownloadCompletedEventInvoker(AddressOf OnDownloadCompleted), _
  470.                                          New Object() {e})
  471.        Else
  472.            RaiseEvent DownloadCompleted(Me, e)
  473.        End If
  474.    End Sub
  475.  
  476. #End Region
  477.  
  478. End Class
  479.  
  480. Public Class Download_Helper
  481.  
  482.    ''' <summary>
  483.    ''' Resumes a file download.
  484.    ''' </summary>
  485.    Public Shared Sub Resume_Download(ByVal File As Object)
  486.  
  487.        Dim Downloader As DownloadFileAsyncExtended
  488.  
  489.        Try
  490.            Downloader = DirectCast(File, DownloadFileAsyncExtended)
  491.            Downloader.CancelAsync()
  492.  
  493.        Catch ex As Exception
  494.            MessageBox.Show(ex.Message, Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  495.  
  496.        End Try
  497.  
  498.  
  499.    End Sub
  500.  
  501.    ''' <summary>
  502.    ''' Pauses or cancel a file download.
  503.    ''' </summary>
  504.    Public Shared Sub PauseCancel_Download(ByVal File As Object)
  505.  
  506.        Dim Downloader As DownloadFileAsyncExtended
  507.  
  508.        Try
  509.  
  510.            Downloader = DirectCast(File, DownloadFileAsyncExtended)
  511.  
  512.            If Not Downloader.IsBusy Then
  513.                Downloader.ResumeAsync()
  514.            End If
  515.  
  516.        Catch ex As Exception
  517.            MessageBox.Show(ex.Message, Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  518.  
  519.        End Try
  520.  
  521.    End Sub
  522.  
  523. End Class
  524.  
  525. '// This class is passed as a parameter to the GetResponse Callback,
  526. '// so we can work with the data in the Response Callback.
  527. Public Class HttpWebRequestState
  528.  
  529.    Private _LocalFilePath As String
  530.    Private _Request As HttpWebRequest
  531.    Private _ResumeDownload As Boolean
  532.    Private _userToken As Object
  533.  
  534.    Public Sub New(ByVal LocalFilePath As String, ByVal Request As HttpWebRequest, ByVal ResumeDownload As Boolean, ByVal userToken As Object)
  535.        _LocalFilePath = LocalFilePath
  536.        _Request = Request
  537.        _ResumeDownload = ResumeDownload
  538.        _userToken = userToken
  539.    End Sub
  540.  
  541.    Public ReadOnly Property LocalFilePath() As String
  542.        Get
  543.            Return _LocalFilePath
  544.        End Get
  545.    End Property
  546.  
  547.    Public ReadOnly Property Request() As HttpWebRequest
  548.        Get
  549.            Return _Request
  550.        End Get
  551.    End Property
  552.  
  553.    Public ReadOnly Property ResumeDownload() As Boolean
  554.        Get
  555.            Return _ResumeDownload
  556.        End Get
  557.    End Property
  558.  
  559.    Public ReadOnly Property userToken() As Object
  560.        Get
  561.            Return _userToken
  562.        End Get
  563.    End Property
  564.  
  565. End Class
  566.  
  567.  
  568. '// This is the data returned to the user for each download in the
  569. '// Progress Changed event, so you can update controls with the progress.
  570. Public Class FileDownloadProgressChangedEventArgs
  571.    Inherits EventArgs
  572.  
  573.    Private _BytesReceived As Long
  574.    Private _TotalBytesToReceive As Long
  575.    Private _DownloadTime As Long
  576.    Private _DownloadSpeed As Long
  577.    Private _userToken As Object
  578.  
  579.    Public Sub New(ByVal BytesReceived As Long, ByVal TotalBytesToReceive As Long, ByVal DownloadTime As Long, ByVal DownloadSpeed As Long, ByVal userToken As Object)
  580.        _BytesReceived = BytesReceived
  581.        _TotalBytesToReceive = TotalBytesToReceive
  582.        _DownloadTime = DownloadTime
  583.        _DownloadSpeed = DownloadSpeed
  584.        _userToken = userToken
  585.    End Sub
  586.  
  587.    Public ReadOnly Property BytesReceived() As Long
  588.        Get
  589.            Return _BytesReceived
  590.        End Get
  591.    End Property
  592.  
  593.    Public ReadOnly Property TotalBytesToReceive() As Long
  594.        Get
  595.            Return _TotalBytesToReceive
  596.        End Get
  597.    End Property
  598.  
  599.    Public ReadOnly Property ProgressPercentage() As Long
  600.        Get
  601.            If _TotalBytesToReceive > 0 Then
  602.                Return Math.Ceiling((_BytesReceived / _TotalBytesToReceive) * 100)
  603.            Else
  604.                Return -1
  605.            End If
  606.        End Get
  607.    End Property
  608.  
  609.    Public ReadOnly Property DownloadTimeSeconds() As Long
  610.        Get
  611.            Return _DownloadTime
  612.        End Get
  613.    End Property
  614.  
  615.    Public ReadOnly Property RemainingTimeSeconds() As Long
  616.        Get
  617.            If DownloadSpeedBytesPerSec > 0 Then
  618.                Return Math.Ceiling((_TotalBytesToReceive - _BytesReceived) / DownloadSpeedBytesPerSec)
  619.            Else
  620.                Return 0
  621.            End If
  622.        End Get
  623.    End Property
  624.  
  625.    Public ReadOnly Property DownloadSpeedBytesPerSec() As Long
  626.        Get
  627.            Return _DownloadSpeed
  628.        End Get
  629.    End Property
  630.  
  631.    Public ReadOnly Property userToken() As Object
  632.        Get
  633.            Return _userToken
  634.        End Get
  635.    End Property
  636.  
  637. End Class
  638.  
  639.  
  640. '// This is the data returned to the user for each download in the
  641. '// Download Completed event, so you can update controls with the result.
  642. Public Class FileDownloadCompletedEventArgs
  643.    Inherits EventArgs
  644.  
  645.    Private _ErrorMessage As Exception
  646.    Private _Cancelled As Boolean
  647.    Private _userToken As Object
  648.  
  649.    Public Sub New(ByVal ErrorMessage As Exception, ByVal Cancelled As Boolean, ByVal userToken As Object)
  650.        _ErrorMessage = ErrorMessage
  651.        _Cancelled = Cancelled
  652.        _userToken = userToken
  653.    End Sub
  654.  
  655.    Public ReadOnly Property ErrorMessage() As Exception
  656.        Get
  657.            Return _ErrorMessage
  658.        End Get
  659.    End Property
  660.  
  661.    Public ReadOnly Property Cancelled() As Boolean
  662.        Get
  663.            Return _Cancelled
  664.        End Get
  665.    End Property
  666.  
  667.    Public ReadOnly Property userToken() As Object
  668.        Get
  669.            Return _userToken
  670.        End Get
  671.    End Property
  672.  
  673. End Class
  674.  
  675. #End Region


Y aquí una Class para entender su funcionamiento.
(Copiar y pegar la class y compilar)




Código
  1. Public Class Form1
  2.  
  3.    ' // Instance a new Downlaoder Class
  4.    Private WithEvents Downloader As New DownloadFileAsyncExtended
  5.  
  6.    ' // create a listview to update.
  7.    Private lv As New ListView With {.View = View.Details, .Dock = DockStyle.Fill}
  8.  
  9.    ' // create a listview item to update.
  10.    Private lvi As New ListViewItem
  11.  
  12.    '// Set an url file to downloads.
  13.    Dim url As String = "http://msft.digitalrivercontent.net/win/X17-58857.iso"
  14.  
  15.    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  16.  
  17.        ' Add columns to listview.
  18.        lv.Columns.AddRange({New ColumnHeader With {.Text = "Filename"}, _
  19.                             New ColumnHeader With {.Text = "Size"}, _
  20.                             New ColumnHeader With {.Text = "Status"}, _
  21.                             New ColumnHeader With {.Text = "Completed"}, _
  22.                             New ColumnHeader With {.Text = "Progress"}, _
  23.                             New ColumnHeader With {.Text = "Speed"}, _
  24.                             New ColumnHeader With {.Text = "Time Elapsed"}, _
  25.                             New ColumnHeader With {.Text = "Time Left"} _
  26.                           })
  27.  
  28.        ' Add subitems to listview item.
  29.        lvi.SubItems.AddRange({"Filename", "Size", "Status", "Completed", "Progress", "Speed", "Time Elapsed", "Time Left"})
  30.  
  31.        ' Add a Object tag to the listview item,
  32.        ' so later we can reffer to this download to pause/resume or cancel it.
  33.        lvi.Tag = Downloader
  34.  
  35.        ' Add the Listview control into the UI.
  36.        Me.Controls.Add(lv)
  37.        ' Add the Listview item into the Listview.
  38.        lv.Items.Add(lvi)
  39.  
  40.        ' Set Application simultaneous internet downloads limit.
  41.        Net.ServicePointManager.DefaultConnectionLimit = 5
  42.  
  43.        '// IMPORTANT !!
  44.        '// If you don't add this line, then all events are raised on a separate thread,
  45.        '// and you will get cross-thread errors when accessing the Listview,
  46.        '// or other controls directly in the raised events.
  47.        Downloader.SynchronizingObject = Me
  48.  
  49.        '// Update frequency.
  50.        '// A value higher than 500 ms will prevent the DownloadProgressChanged event,
  51.        '// from firing continuously and hogging CPU when updating the controls.
  52.        '// If you download small files that could be downloaded within a second,
  53.        '// then set it to "NoDelay" or the progress might not be visible.
  54.        Downloader.ProgressUpdateFrequency = DownloadFileAsyncExtended.UpdateFrequency.MilliSeconds_500
  55.  
  56.        '// The method to actually download a file. The "userToken" parameter can,
  57.        '// for example be a control you wish to update in the DownloadProgressChanged,
  58.        '// and DownloadCompleted events. It is a ListViewItem in this example.
  59.        Downloader.DowloadFileAsync(url, "C:\Downloaded file.iso", lvi)
  60.  
  61.    End Sub
  62.  
  63.  
  64.    '// This event allows you to show the download progress to the user.
  65.    '
  66.    ' e.BytesReceived = Bytes received so far.
  67.    ' e.DownloadSpeedBytesPerSec = Download speed in bytes per second.
  68.    ' e.DownloadTimeSeconds = Download time in seconds so far.
  69.    ' e.ProgressPercentage = Percentage of the file downloaded.
  70.    ' e.RemainingTimeSeconds = Remaining download time in seconds.
  71.    ' e.TotalBytesToReceive = Total size of the file that is being downloaded.
  72.    ' e.userToken = Usually the control(s) you wish to update.
  73.    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As FileDownloadProgressChangedEventArgs) _
  74.    Handles Downloader.DownloadProgressChanged
  75.  
  76.        ' Get the ListViewItem we passed as "userToken" parameter, so we can update it.
  77.        Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  78.  
  79.        ' Update the ListView item subitems.
  80.        lvi.SubItems(0).Text = url
  81.        lvi.SubItems(1).Text = String.Format("{0:#,#} KB", (e.TotalBytesToReceive / 1024))
  82.        lvi.SubItems(2).Text = "Downloading"
  83.        lvi.SubItems(3).Text = String.Format("{0:#,#} KB", (e.BytesReceived / 1024))
  84.        lvi.SubItems(4).Text = e.ProgressPercentage & "%"
  85.        lvi.SubItems(5).Text = (e.DownloadSpeedBytesPerSec \ 1024).ToString & " kB/s"
  86.        lvi.SubItems(6).Text = String.Format("{0}:{1}:{2}", _
  87.                               (e.DownloadTimeSeconds \ 3600).ToString("00"), _
  88.                               ((e.DownloadTimeSeconds Mod 3600) \ 60).ToString("00"), _
  89.                               (e.DownloadTimeSeconds Mod 60).ToString("00"))
  90.        lvi.SubItems(7).Text = String.Format("{0}:{1}:{2}", _
  91.                               (e.RemainingTimeSeconds \ 3600).ToString("00"), _
  92.                               ((e.RemainingTimeSeconds Mod 3600) \ 60).ToString("00"), _
  93.                               (e.RemainingTimeSeconds Mod 60).ToString("00"))
  94.  
  95.    End Sub
  96.  
  97.  
  98.    '// This event lets you know when the download is complete.
  99.    '// The download finished successfully, the user cancelled the download or there was an error.
  100.    Private Sub DownloadCompleted(ByVal sender As Object, ByVal e As FileDownloadCompletedEventArgs) _
  101.    Handles Downloader.DownloadCompleted
  102.  
  103.        ' Get the ListViewItem we passed as userToken parameter, so we can update it.
  104.        Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  105.  
  106.        If e.ErrorMessage IsNot Nothing Then ' Was there an error.
  107.  
  108.            lvi.SubItems(2).Text = "Error: " & e.ErrorMessage.Message.ToString
  109.  
  110.            ' Set an Error ImageKey.
  111.            ' lvi.ImageKey = "Error"
  112.  
  113.        ElseIf e.Cancelled Then ' The user cancelled the download.
  114.  
  115.            lvi.SubItems(2).Text = "Paused"
  116.  
  117.            ' Set a Paused ImageKey.
  118.            ' lvi.ImageKey = "Paused"
  119.  
  120.        Else ' Download was successful.
  121.  
  122.            lvi.SubItems(2).Text = "Finished"
  123.  
  124.            ' Set a Finished ImageKey.
  125.            ' lvi.ImageKey = "Finished"
  126.  
  127.        End If
  128.  
  129.        ' Set Tag to Nothing in order to remove the wClient class instance,
  130.        ' so this way we know we can't resume the download.
  131.        lvi.Tag = Nothing
  132.  
  133.    End Sub
  134.  
  135.    ' Private Sub Button_Resume_Click(sender As Object, e As EventArgs) Handles Button_Resume.Click
  136.    '// To Resume a file:
  137.    ' Download_Helper.Resume_Download(lvi.Tag)
  138.    'End Sub
  139.  
  140.    'Private Sub Button_Pause_Click(sender As Object, e As EventArgs) Handles Button_Pause.Click
  141.    '// To pause or cancel a file:
  142.    ' Download_Helper.PauseCancel_Download(lvi.Tag)
  143.    'End Sub
  144.  
  145. End Class
« Última modificación: 21 Octubre 2013, 14:13 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #325 en: 21 Octubre 2013, 19:11 pm »

· Dibujar una barra de progreso en un Item de un ListView:







PD: Es preferible adaptar el siguiente código para hacer un user-control heredado de un Listview (solo hay que modificar 4 tonterías sencillas de este código) y añadirle anti-flickering al user-control, pero bueno, pueden dibujar el Listview desde otra Class como se muestra en este ejemplo, el código no es mio, solo lo he adaptado.

Código
  1. #Region " [ListView] Draw ProgressBar "
  2.  
  3.    ' [ [ListView] Draw ProgressBar ]
  4.  
  5.    Private Listview_Column As Integer = 4 ' The column index to draw the ProgressBar
  6.  
  7.    Private Percent As Double = 0 ' The progress percentage
  8.    Private Percent_DecimalFactor As Short = 1 ' Example: 0.1
  9.    Private Percent_Text As String = "% Done" ' Example: 0.1% Done
  10.    Private Percent_Forecolor As Brush = Brushes.Black
  11.    Private Percent_Font As Font = Me.Font
  12.  
  13.    Private ProgressBar_BackColor As Brush = Brushes.White
  14.    Private ProgressBar_BorderColor As Pen = Pens.LightGray
  15.    Private ProgressBar_FillColor1 As Color = Color.YellowGreen
  16.    Private ProgressBar_FillColor2 As Color = Color.White
  17.  
  18.    ' ListView [Layout]
  19.    Private Sub ListView1_Layout(sender As Object, e As LayoutEventArgs) _
  20.    Handles ListView1.Layout
  21.  
  22.        ' Set Listview OwnerDraw to True, so we can draw the progressbar.
  23.        ListView1.OwnerDraw = True
  24.  
  25.    End Sub
  26.  
  27.    ' ListView [DrawColumnHeader]
  28.    Private Sub ListView_DrawColumnHeader(ByVal sender As Object, ByVal e As DrawListViewColumnHeaderEventArgs) _
  29.    Handles ListView1.DrawColumnHeader
  30.  
  31.        e.DrawDefault = True ' Draw default ColumnHeader.
  32.  
  33.    End Sub
  34.  
  35.    ' ListView [DrawItem]
  36.    Private Sub ListView_DrawItem(ByVal sender As Object, ByVal e As DrawListViewItemEventArgs) _
  37.    Handles ListView1.DrawItem
  38.  
  39.        e.DrawDefault = False ' Draw default main item.
  40.  
  41.    End Sub
  42.  
  43.    ' ListView [DrawSubItem]
  44.    Private Sub ListView_DrawSubItem(ByVal sender As Object, ByVal e As DrawListViewSubItemEventArgs) _
  45.    Handles ListView1.DrawSubItem
  46.  
  47.        If (e.ItemState And ListViewItemStates.Selected) <> 0 Then
  48.            ' Item is highlighted.
  49.            e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds)
  50.        End If
  51.  
  52.        ' Draw the progressbar.
  53.        If e.ColumnIndex = Listview_Column Then
  54.  
  55.            ' Center the text in the progressbar.
  56.            Dim sf As New StringFormat
  57.            sf.Alignment = StringAlignment.Center
  58.  
  59.            ' Background color of the progressbar is white.
  60.            e.Graphics.FillRectangle(ProgressBar_BackColor, e.Bounds)
  61.  
  62.            ' Percentage of the progressbar to fill.
  63.            Dim FillPercent As Integer = CInt(((Percent) / 100) * (e.Bounds.Width - 2))
  64.  
  65.            ' This creates a nice color gradient to fill.
  66.            Dim brGradient As Brush = _
  67.                New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), _
  68.                                                                 ProgressBar_FillColor1, ProgressBar_FillColor2, 270, True)
  69.            ' Draw the actual progressbar.
  70.            e.Graphics.FillRectangle(brGradient, _
  71.                                     e.Bounds.X + 1, e.Bounds.Y + 2, _
  72.                                     FillPercent, e.Bounds.Height - 3)
  73.  
  74.            ' Draw the percentage number and percent sign.
  75.            ' NOTE: make sure that e.SubItem.Text only contains a number or an error will occur.
  76.            e.Graphics.DrawString(Percent.ToString("n" & Percent_DecimalFactor) & Percent_Text, _
  77.                                  Percent_Font, Percent_Forecolor, _
  78.                                  CSng(e.Bounds.X + (e.Bounds.Width / 2)), e.Bounds.Y + 3, _
  79.                                  sf)
  80.  
  81.            ' Draw a light gray rectangle/border around the progressbar.
  82.            e.Graphics.DrawRectangle(ProgressBar_BorderColor, _
  83.                                     e.Bounds.X, e.Bounds.Y + 1, _
  84.                                     e.Bounds.Width - 1, e.Bounds.Height - 2)
  85.        Else
  86.            e.DrawDefault = True
  87.  
  88.        End If
  89.  
  90.    End Sub
  91.  
  92. #End Region
  93.  



· Un ejemplo que he hecho para mostrar como usar una expresión Lambda al Invocar propiedades de controles:

Código
  1. #Region " Invoke Lambda "
  2.  
  3.    ' Create a thread.
  4.    Private t As Threading.Thread = New Threading.Thread(AddressOf UI_Thread)
  5.  
  6.    ' Create two Textbox.
  7.    Dim tb1 As New TextBox With {.Text = "Hello World!"}
  8.    Dim tb2 As New TextBox With {.Location = New Point(tb1.Location.X, (tb1.Location.Y + tb1.Height))}
  9.  
  10.    Private Sub Form1_Load(sender As Object, e As EventArgs) _
  11.    Handles MyBase.Load
  12.  
  13.        Me.Controls.AddRange({tb1, tb2}) ' Add the Textbox to the UI.
  14.        t.Start() ' Start the thread.
  15.  
  16.    End Sub
  17.  
  18.    Private Sub UI_Thread()
  19.  
  20.        If tb2.InvokeRequired Then ' Check if invocation is required for the TextBox on the main thread.
  21.            tb2.Invoke(Sub() tb2.Text = tb1.Text) ' Then Invoke a Lambda method.
  22.        Else
  23.            tb2.Text = tb1.Text
  24.        End If
  25.  
  26.    End Sub
  27.  
  28. #End Region



· Un ejemplo que muestra como crear y usar un delegado para actualizar un control desde otro thread:

Código
  1. #Region " Delegate Example "
  2.  
  3.   ' Create the delegate to be able to update the TextBox.
  4.    Private Delegate Sub TextBoxUpdateUI(ByVal txt As String)
  5.  
  6.    ' Create a thread.
  7.    Private t As Threading.Thread = New Threading.Thread(AddressOf UI_Thread)
  8.  
  9.    ' Create two Textbox.
  10.    Dim tb1 As New TextBox With {.Text = "Hello World!"}
  11.    Dim tb2 As New TextBox With {.Location = New Point(tb1.Location.X, (tb1.Location.Y + tb1.Height))}
  12.  
  13.    Private Sub Form1_Load(sender As Object, e As EventArgs) _
  14.    Handles MyBase.Load
  15.  
  16.        Me.Controls.AddRange({tb1, tb2}) ' Add the Textbox to the UI.
  17.        t.Start() ' Start the thread.
  18.  
  19.    End Sub
  20.  
  21.    Private Sub UI_Thread()
  22.  
  23.        If tb2.InvokeRequired Then ' Check if invocation is required for the TextBox on the main thread.
  24.            Dim tb_delegate As New TextBoxUpdateUI(AddressOf UI_Thread) ' Set the TextBox delegate.
  25.            tb2.Invoke(tb_delegate, Text) ' Invoke the delegate and the control property to update.
  26.        Else
  27.            tb2.Text = tb1.Text
  28.        End If
  29.  
  30.    End Sub
  31.  
  32. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #326 en: 21 Octubre 2013, 19:29 pm »

Le he hecho una revisión de código a un ListView extendio que ya compartí hace tiempo, le he añadido la ProgressBar que he comentado más arriba, no lo he testeado mucho pero parece que todo funciona como debe funcionar,
que lo disfruteis!

Código
  1. '  /*                  *\
  2. ' |#* ListView Elektro *#|
  3. '  \*                  */
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. '   Properties:
  8. '   ...........
  9. ' · Disable_Flickering
  10. ' · Double_Buffer
  11. ' · GridLineColor
  12. ' · ItemHighlightColor
  13. ' · ItemNotFocusedHighlighColor
  14. ' · DrawCustomGridLines
  15. ' · UseDefaultGridLines
  16. ' · Enable_ProgressBar
  17. ' · Progressbar_Column
  18. ' · Percent
  19. ' · Percent_Decimal
  20. ' · Percent_Font
  21. ' · Percent_Text
  22. ' · Percent_Forecolor
  23. ' · Percent_Text_Allignment
  24. ' · ProgressBar_BackColor
  25. ' · ProgressBar_BorderColor
  26. ' · ProgressBar_FillColor1
  27. ' · ProgressBar_FillColor2
  28. '
  29. '   Events:
  30. '   .......
  31. ' · ItemAdded
  32. ' · ItemRemoved
  33. '
  34. '   Methods:
  35. '   .......
  36. ' · AddItem
  37. ' · RemoveItem
  38.  
  39. Public Class ListView_Elektro : Inherits ListView
  40.  
  41.    Public Event ItemAdded()
  42.    Public Event ItemRemoved()
  43.  
  44.    Private _Disable_Flickering As Boolean = True
  45.    Private _gridLines As Boolean = False
  46.    Private _useDefaultGridLines As Boolean = False
  47.    Private _gridLineColor As Color = Color.Black
  48.    Private _itemHighlightColor As Color = Color.FromKnownColor(KnownColor.Highlight)
  49.    Private _itemNotFocusedHighlighColor As Color = Color.FromKnownColor(KnownColor.MenuBar)
  50.  
  51.    Private _enable_progressbar As Boolean = False
  52.    Private _progressbar_column As Integer = Nothing
  53.  
  54.    Private _percent As Double = 0
  55.    Private _percent_decimal As Short = 2
  56.    Private _percent_text As String = "%"
  57.    Private _percent_text_allignment As StringAlignment = StringAlignment.Center
  58.    Private _percent_stringformat As StringFormat = New StringFormat With {.Alignment = _percent_text_allignment}
  59.    Private _percent_font As Font = Me.Font
  60.    Private _percent_forecolor As SolidBrush = New SolidBrush(Color.Black)
  61.  
  62.    Private _progressBar_backcolor As SolidBrush = New SolidBrush(Color.Red)
  63.    Private _progressBar_bordercolor As Pen = New Pen(Color.LightGray)
  64.    Private _progressBar_fillcolor1 As Color = Color.YellowGreen
  65.    Private _progressBar_fillcolor2 As Color = Color.White
  66.  
  67.    Public Sub New()
  68.  
  69.        Me.Name = "ListView_Elektro"
  70.        Me.DoubleBuffered = True
  71.        Me.UseDefaultGridLines = True
  72.  
  73.        ' Set Listview OwnerDraw to True, so we can draw the progressbar inside.
  74.        If Me.Enable_ProgressBar Then Me.OwnerDraw = True
  75.  
  76.        ' Me.GridLines = True
  77.        ' Me.MultiSelect = True
  78.        ' Me.FullRowSelect = True
  79.        ' Me.View = View.Details
  80.  
  81.    End Sub
  82.  
  83. #Region " Properties "
  84.  
  85.    ''' <summary>
  86.    ''' Enable/Disable any flickering effect on the ListView.
  87.    ''' </summary>
  88.    Protected Overrides ReadOnly Property CreateParams() As CreateParams
  89.        Get
  90.            If _Disable_Flickering Then
  91.                Dim cp As CreateParams = MyBase.CreateParams
  92.                cp.ExStyle = cp.ExStyle Or &H2000000
  93.                Return cp
  94.            Else
  95.                Return MyBase.CreateParams
  96.            End If
  97.        End Get
  98.    End Property
  99.  
  100.    ''' <summary>
  101.    ''' Set the Double Buffer.
  102.    ''' </summary>
  103.    Public Property Double_Buffer() As Boolean
  104.        Get
  105.            Return Me.DoubleBuffered
  106.        End Get
  107.        Set(ByVal Value As Boolean)
  108.            Me.DoubleBuffered = Value
  109.        End Set
  110.    End Property
  111.  
  112.    ''' <summary>
  113.    ''' Enable/Disable the flickering effects on this ListView.
  114.    '''
  115.    ''' This property turns off any Flicker effect on the ListView
  116.    ''' ...but also reduces the performance (speed) of the ListView about 30% slower.
  117.    ''' This don't affect to the performance of the application itself, only to the performance of this control.
  118.    ''' </summary>
  119.    Public Property Disable_Flickering() As Boolean
  120.        Get
  121.            Return _Disable_Flickering
  122.        End Get
  123.        Set(ByVal Value As Boolean)
  124.            Me._Disable_Flickering = Value
  125.        End Set
  126.    End Property
  127.  
  128.    ''' <summary>
  129.    ''' Changes the gridline color.
  130.    ''' </summary>
  131.    Public Property GridLineColor() As Color
  132.        Get
  133.            Return _gridLineColor
  134.        End Get
  135.        Set(ByVal value As Color)
  136.            If value <> _gridLineColor Then
  137.                _gridLineColor = value
  138.                If _gridLines Then
  139.                    Me.Invalidate()
  140.                End If
  141.            End If
  142.        End Set
  143.    End Property
  144.  
  145.    ''' <summary>
  146.    ''' Changes the color when item is highlighted.
  147.    ''' </summary>
  148.    Public Property ItemHighlightColor() As Color
  149.        Get
  150.            Return _itemHighlightColor
  151.        End Get
  152.        Set(ByVal value As Color)
  153.            If value <> _itemHighlightColor Then
  154.                _itemHighlightColor = value
  155.                Me.Invalidate()
  156.            End If
  157.        End Set
  158.    End Property
  159.  
  160.    ''' <summary>
  161.    ''' Changes the color when the item is not focused.
  162.    ''' </summary>
  163.    Public Property ItemNotFocusedHighlighColor() As Color
  164.        Get
  165.            Return _itemNotFocusedHighlighColor
  166.        End Get
  167.        Set(ByVal value As Color)
  168.            If value <> _itemNotFocusedHighlighColor Then
  169.                _itemNotFocusedHighlighColor = value
  170.                Me.Invalidate()
  171.            End If
  172.        End Set
  173.    End Property
  174.  
  175.    Private ReadOnly Property DrawCustomGridLines() As Boolean
  176.        Get
  177.            Return (_gridLines And Not _useDefaultGridLines)
  178.        End Get
  179.    End Property
  180.  
  181.    Public Shadows Property GridLines() As Boolean
  182.        Get
  183.            Return _gridLines
  184.        End Get
  185.        Set(ByVal value As Boolean)
  186.            _gridLines = value
  187.        End Set
  188.    End Property
  189.  
  190.    ''' <summary>
  191.    ''' use the default gridlines.
  192.    ''' </summary>
  193.    Public Property UseDefaultGridLines() As Boolean
  194.        Get
  195.            Return _useDefaultGridLines
  196.        End Get
  197.        Set(ByVal value As Boolean)
  198.            If _useDefaultGridLines <> value Then
  199.                _useDefaultGridLines = value
  200.            End If
  201.            MyBase.GridLines = value
  202.            MyBase.OwnerDraw = Not value
  203.        End Set
  204.    End Property
  205. #End Region
  206.  
  207. #Region " Procedures "
  208.  
  209.    ''' <summary>
  210.    ''' Monitors when an Item is added to the ListView.
  211.    ''' </summary>
  212.    Public Function AddItem(ByVal Text As String) As ListViewItem
  213.        RaiseEvent ItemAdded()
  214.        Return MyBase.Items.Add(Text)
  215.    End Function
  216.  
  217.    ''' <summary>
  218.    ''' Monitors when an Item is removed from the ListView.
  219.    ''' </summary>
  220.    Public Sub RemoveItem(ByVal Item As ListViewItem)
  221.        RaiseEvent ItemRemoved()
  222.        MyBase.Items.Remove(Item)
  223.    End Sub
  224.  
  225.    Protected Overrides Sub OnDrawColumnHeader(ByVal e As DrawListViewColumnHeaderEventArgs)
  226.        e.DrawDefault = True
  227.        MyBase.OnDrawColumnHeader(e)
  228.    End Sub
  229.  
  230.    Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
  231.        For Each selectedIndex As Integer In MyBase.SelectedIndices
  232.            MyBase.RedrawItems(selectedIndex, selectedIndex, False)
  233.        Next
  234.        MyBase.OnLostFocus(e)
  235.    End Sub
  236.  
  237.    Protected Overrides Sub OnDrawSubItem(ByVal e As DrawListViewSubItemEventArgs)
  238.  
  239.        Dim drawAsDefault As Boolean = False
  240.        Dim highlightBounds As Rectangle = Nothing
  241.        Dim highlightBrush As SolidBrush = Nothing
  242.  
  243.        'FIRST DETERMINE THE COLOR
  244.        If e.Item.Selected Then
  245.            If MyBase.Focused Then
  246.                highlightBrush = New SolidBrush(_itemHighlightColor)
  247.            ElseIf HideSelection Then
  248.                drawAsDefault = True
  249.            Else
  250.                highlightBrush = New SolidBrush(_itemNotFocusedHighlighColor)
  251.            End If
  252.        Else
  253.            drawAsDefault = True
  254.        End If
  255.  
  256.        If drawAsDefault Then
  257.            e.DrawBackground()
  258.        Else
  259.            'NEXT DETERMINE THE BOUNDS IN WHICH TO DRAW THE BACKGROUND
  260.            If FullRowSelect Then
  261.                highlightBounds = e.Bounds
  262.            Else
  263.                highlightBounds = e.Item.GetBounds(ItemBoundsPortion.Label)
  264.            End If
  265.  
  266.            'ONLY DRAW HIGHLIGHT IN 1 OF 2 CASES
  267.            'CASE 1 - FULL ROW SELECT (AND DRAWING ANY ITEM)
  268.            'CASE 2 - NOT FULL ROW SELECT (AND DRAWING 1ST ITEM)
  269.            If FullRowSelect Then
  270.                e.Graphics.FillRectangle(highlightBrush, highlightBounds)
  271.            ElseIf e.ColumnIndex = 0 Then
  272.                e.Graphics.FillRectangle(highlightBrush, highlightBounds)
  273.            Else
  274.                e.DrawBackground()
  275.            End If
  276.        End If
  277.  
  278.        e.DrawText()
  279.  
  280.        If _gridLines Then
  281.            e.Graphics.DrawRectangle(New Pen(_gridLineColor), e.Bounds)
  282.        End If
  283.  
  284.  
  285.        If FullRowSelect Then
  286.            e.DrawFocusRectangle(e.Item.GetBounds(ItemBoundsPortion.Entire))
  287.        Else
  288.            e.DrawFocusRectangle(e.Item.GetBounds(ItemBoundsPortion.Label))
  289.        End If
  290.  
  291.        MyBase.OnDrawSubItem(e)
  292.  
  293.    End Sub
  294.  
  295. #End Region
  296.  
  297. #Region " ProgressBar Properties "
  298.  
  299.    ''' <summary>
  300.    ''' Enables the drawing of a ProgressBar
  301.    ''' This property should be "True" to use any of the ProgressBar properties.
  302.    ''' </summary>
  303.    Public Property Enable_ProgressBar As Boolean
  304.        Get
  305.            Return _enable_progressbar
  306.        End Get
  307.        Set(ByVal value As Boolean)
  308.            Me.OwnerDraw = value
  309.            _enable_progressbar = value
  310.        End Set
  311.    End Property
  312.  
  313.    ''' <summary>
  314.    ''' The column index to draw the ProgressBar
  315.    ''' </summary>
  316.    Public Property Progressbar_Column As Integer
  317.        Get
  318.            Return _progressbar_column
  319.        End Get
  320.        Set(ByVal value As Integer)
  321.            _progressbar_column = value
  322.        End Set
  323.    End Property
  324.  
  325.    ''' <summary>
  326.    ''' The ProgressBar progress percentage
  327.    ''' </summary>
  328.    Public Property Percent As Double
  329.        Get
  330.            Return _percent
  331.        End Get
  332.        Set(ByVal value As Double)
  333.            _percent = value
  334.        End Set
  335.    End Property
  336.  
  337.    ''' <summary>
  338.    ''' The decimal factor which should be displayed for the ProgressBar progress percentage
  339.    ''' </summary>
  340.    Public Property Percent_Decimal As Short
  341.        Get
  342.            Return _percent_decimal
  343.        End Get
  344.        Set(ByVal value As Short)
  345.            _percent_decimal = value
  346.        End Set
  347.    End Property
  348.  
  349.    ''' <summary>
  350.    ''' The Font to be used as the ProgressBar Percent text
  351.    ''' </summary>
  352.    Public Property Percent_Font As Font
  353.        Get
  354.            Return _percent_font
  355.        End Get
  356.        Set(ByVal value As Font)
  357.            _percent_font = value
  358.        End Set
  359.    End Property
  360.  
  361.    ''' <summary>
  362.    ''' The additional text to add to the ProgressBar Percent value
  363.    ''' </summary>
  364.    Public Property Percent_Text As String
  365.        Get
  366.            Return _percent_text
  367.        End Get
  368.        Set(ByVal value As String)
  369.            _percent_text = value
  370.        End Set
  371.    End Property
  372.  
  373.    ''' <summary>
  374.    ''' The ForeColor of the ProgressBar Percent Text
  375.    ''' </summary>
  376.    Public Property Percent_Forecolor As Color
  377.        Get
  378.            Return _percent_forecolor.Color
  379.        End Get
  380.        Set(ByVal value As Color)
  381.            _percent_forecolor = New SolidBrush(value)
  382.        End Set
  383.    End Property
  384.  
  385.    ''' <summary>
  386.    ''' The text allignment to use for the ProgressBar
  387.    ''' </summary>
  388.    Public Property Percent_Text_Allignment As StringAlignment
  389.        Get
  390.            Return _percent_stringformat.Alignment
  391.        End Get
  392.        Set(ByVal value As StringAlignment)
  393.            _percent_stringformat.Alignment = value
  394.        End Set
  395.    End Property
  396.  
  397.    ''' <summary>
  398.    ''' The ProgressBar BackColor
  399.    ''' </summary>
  400.    Public Property ProgressBar_BackColor As Color
  401.        Get
  402.            Return _progressBar_backcolor.Color
  403.        End Get
  404.        Set(ByVal value As Color)
  405.            _progressBar_backcolor = New SolidBrush(value)
  406.        End Set
  407.    End Property
  408.  
  409.    ''' <summary>
  410.    ''' The ProgressBar BorderColor
  411.    ''' </summary>
  412.    Public Property ProgressBar_BorderColor As Color
  413.        Get
  414.            Return _progressBar_bordercolor.Color
  415.        End Get
  416.        Set(ByVal value As Color)
  417.            _progressBar_bordercolor = New Pen(value)
  418.        End Set
  419.    End Property
  420.  
  421.    ''' <summary>
  422.    ''' The First ProgressBar Gradient color
  423.    ''' </summary>
  424.    Public Property ProgressBar_FillColor1 As Color
  425.        Get
  426.            Return _progressBar_fillcolor1
  427.        End Get
  428.        Set(ByVal value As Color)
  429.            _progressBar_fillcolor1 = value
  430.        End Set
  431.    End Property
  432.  
  433.    ''' <summary>
  434.    ''' The Last ProgressBar Gradient color
  435.    ''' </summary>
  436.    Public Property ProgressBar_FillColor2 As Color
  437.        Get
  438.            Return _progressBar_fillcolor2
  439.        End Get
  440.        Set(ByVal value As Color)
  441.            _progressBar_fillcolor2 = value
  442.        End Set
  443.    End Property
  444.  
  445. #End Region
  446.  
  447. #Region " ProgressBar EventHandlers "
  448.  
  449.    ' ListView [DrawColumnHeader]
  450.    Public Sub Me_DrawColumnHeader(ByVal sender As Object, ByVal e As DrawListViewColumnHeaderEventArgs) Handles Me.DrawColumnHeader
  451.  
  452.        e.DrawDefault = True ' Draw default ColumnHeader.
  453.  
  454.    End Sub
  455.  
  456.    ' ListView [DrawItem]
  457.    Public Sub Me_DrawItem(ByVal sender As Object, ByVal e As DrawListViewItemEventArgs) 'Handles Me.DrawItem
  458.  
  459.        e.DrawDefault = False ' Draw default main item.
  460.  
  461.    End Sub
  462.  
  463.    ' ListView [DrawSubItem]
  464.    Public Sub Me_DrawSubItem(ByVal sender As Object, ByVal e As DrawListViewSubItemEventArgs) Handles Me.DrawSubItem
  465.  
  466.        If (e.ItemState And ListViewItemStates.Selected) <> 0 Then
  467.            ' Item is highlighted.
  468.            e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds)
  469.        End If
  470.  
  471.        ' Draw the progressbar.
  472.        If e.ColumnIndex = Me.Progressbar_Column Then
  473.  
  474.            If (Not Me.Enable_ProgressBar OrElse Me.Progressbar_Column = Nothing) Then Exit Sub
  475.  
  476.            ' Background color of the progressbar is white.
  477.            e.Graphics.FillRectangle(Me._progressBar_backcolor, e.Bounds)
  478.  
  479.            ' This creates a nice color gradient to fill.
  480.            Dim brGradient As Brush = _
  481.                New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), _
  482.                                                                 Me.ProgressBar_FillColor1, Me.ProgressBar_FillColor2, 270, True)
  483.            ' Draw the actual progressbar.
  484.            e.Graphics.FillRectangle(brGradient, _
  485.                                     e.Bounds.X + 1, e.Bounds.Y + 2, _
  486.                                     CInt(((Me.Percent) / 100) * (e.Bounds.Width - 2)), e.Bounds.Height - 3)
  487.  
  488.            ' Draw the percentage number and percent sign.
  489.            e.Graphics.DrawString(Me.Percent.ToString("n" & Me.Percent_Decimal) & Me.Percent_Text, _
  490.                                  Me.Percent_Font, Me._percent_forecolor, _
  491.                                  CSng(e.Bounds.X + (e.Bounds.Width / 2)), e.Bounds.Y + 3, _
  492.                                  _percent_stringformat)
  493.  
  494.            ' Draw a light gray rectangle/border around the progressbar.
  495.            e.Graphics.DrawRectangle(Me._progressBar_bordercolor, _
  496.                                     e.Bounds.X, e.Bounds.Y + 1, _
  497.                                     e.Bounds.Width - 1, e.Bounds.Height - 2)
  498.        Else
  499.            e.DrawDefault = True
  500.  
  501.        End If
  502.  
  503.    End Sub
  504.  
  505. #End Region
  506.  
  507. End Class
« Última modificación: 21 Octubre 2013, 21:04 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #327 en: 22 Octubre 2013, 16:13 pm »

Unas sencillas funciones para convertir pluma/brocha a color, y viceversa.

Código
  1. #Region " Color To Pen "
  2.  
  3.    ' [ Color To Pen ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_Pen(Color.Red).Color.Name) ' Result: Red
  9.  
  10.    Private Function Color_To_Pen(ByVal color As Color) As Pen
  11.  
  12.        Dim _pen As Pen = Nothing
  13.  
  14.        Try
  15.            _pen = New Pen(color)
  16.            Return _pen
  17.  
  18.        Catch ex As Exception
  19.            Throw New Exception(ex.Message)
  20.            Return Nothing
  21.  
  22.        Finally
  23.            If _pen IsNot Nothing Then _pen.Dispose()
  24.  
  25.        End Try
  26.  
  27.    End Function
  28.  
  29. #End Region

Código
  1. #Region " Color To SolidBrush "
  2.  
  3.    ' [ Color To SolidBrush ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_SolidBrush(Color.Red).Color.Name) ' Result: Red
  9.  
  10.    Private Function Color_To_SolidBrush(ByVal color As Color) As SolidBrush
  11.  
  12.        Dim _brush As SolidBrush = Nothing
  13.  
  14.        Try
  15.            _brush = New SolidBrush(color)
  16.            Return _brush
  17.  
  18.        Catch ex As Exception
  19.            Throw New Exception(ex.Message)
  20.            Return Nothing
  21.  
  22.        Finally
  23.            If _brush IsNot Nothing Then _brush.Dispose()
  24.  
  25.        End Try
  26.  
  27.    End Function
  28.  
  29. #End Region

Código
  1. #Region " Pen To Color "
  2.  
  3.    ' [ Pen To Color ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Pen_To_Color(New Pen(Color.Red)).Name) ' Result: Red
  9.  
  10.    Private Function Pen_To_Color(ByVal pen As Pen) As Color
  11.        Return pen.Color
  12.    End Function
  13.  
  14. #End Region

Código
  1. #Region " SolidBrush To Color "
  2.  
  3.    ' [ SolidBrush To Color ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(SolidBrush_To_Color(New SolidBrush(Color.Red)).Name) ' Result: Red
  9.  
  10.    Private Function SolidBrush_To_Color(ByVal brush As SolidBrush) As Color
  11.        Return brush.Color
  12.    End Function
  13.  
  14. #End Region





Y otra sencilla función para parsear un valor de una enumeración:

Código
  1.    #Region " Enum Parser "
  2.  
  3.       ' [ Enum Parser ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       '
  9.       ' MsgBox(Enum_Parser(Of Keys)(65).ToString) ' Result: A
  10.       ' MsgBox(Enum_Parser(Of Keys)("A").ToString) ' Result: A
  11.       ' TextBox1.BackColor = Color.FromKnownColor(Enum_Parser(Of KnownColor)("Red"))
  12.  
  13.    Private Function Enum_Parser(Of T)(Value As Object) As T
  14.  
  15.        Try
  16.            Return [Enum].Parse(GetType(T), Value, True)
  17.  
  18.        Catch ex As ArgumentException
  19.            Throw New Exception("Enum value not found")
  20.  
  21.        Catch ex As Exception
  22.            Throw New Exception(String.Format("{0}: {1}}", _
  23.                                ex.Message, ex.StackTrace))
  24.  
  25.        End Try
  26.  
  27.    End Function
  28.  
  29.    #End Region
« Última modificación: 22 Octubre 2013, 16:18 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #328 en: 22 Octubre 2013, 19:23 pm »

Otra función simple, que devuelve las medidas de la fuente de texto:

Código
  1. #Region " Get Text Measure "
  2.  
  3.    ' [ Get Text Measure ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Get_Text_Measure("Hello World!", New Font(New FontFamily("Lucida Console"), 12)).Width)  ' Result: 127
  10.    ' MsgBox(Get_Text_Measure("Hello World!", New Font(New FontFamily("Lucida Console"), 12)).Height) ' Result: 16
  11.  
  12.    Private Function Get_Text_Measure(ByVal text As String, ByVal font As Font) As SizeF
  13.        Return TextRenderer.MeasureText(text, font)
  14.    End Function
  15.  
  16. #End Region





Esta función obtiene el texto de una ventana, pasándole como parámetro el handle de dicha ventana:

Código
  1. #Region " Get Window Text "
  2.  
  3.    ' [ Get Window Text ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim str as String = Get_Window_Text(hwnd)
  9.  
  10.    <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  11.    Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
  12.    End Function
  13.  
  14.    <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  15.    Private Shared Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
  16.    End Function
  17.  
  18.    Public Function Get_Window_Text(ByVal hWnd As IntPtr) As String
  19.  
  20.        If hWnd = IntPtr.Zero Then : Return Nothing
  21.  
  22.        Else
  23.  
  24.            Dim length As Integer = GetWindowTextLength(hWnd)
  25.  
  26.            If length = 0 Then
  27.                Return Nothing
  28.            End If
  29.  
  30.            Dim sb As New System.Text.StringBuilder("", length)
  31.  
  32.            GetWindowText(hWnd, sb, sb.Capacity + 1)
  33.            Return sb.ToString()
  34.  
  35.        End If
  36.  
  37.    End Function
  38.  
  39. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #329 en: 24 Octubre 2013, 13:57 pm »

Con este código podemos heredar un TextBox y averiguar la opción que ha elegido el usuario en el CMT por defecto de Windows.

El código original no es mio, pero lo he adaptado apra que funcione corréctamente la opción "Cut", y le he añadido la constande de "Delete".

Modo de empleo:

Código
  1.    Private Sub TextBox1_OnTextCommand(sender As Object, e As MyTextBox.ContextCommandEventArgs) _
  2.    Handles MyTextBox1.OnCut, MyTextBox1.OnPaste, MyTextBox1.OnCopy, MyTextBox1.OnDelete
  3.  
  4.        MessageBox.Show("Activated " & e.Command.ToString())
  5.  
  6.    End Sub

Código
  1. Class MyTextBox : Inherits TextBox
  2.  
  3.    Private Last_Command As ContextCommands = Nothing
  4.  
  5.    Private WithEvents CopyOrCut_Timer As New Timer _
  6.            With {.Interval = 5, .Enabled = False}
  7.  
  8.    Public Enum ContextCommands
  9.        WM_CUT = &H300
  10.        WM_COPY = &H301
  11.        WM_PASTE = &H302
  12.        WM_DELETE = &H303
  13.    End Enum
  14.  
  15.    Public Class ContextCommandEventArgs
  16.        Inherits EventArgs
  17.        Public Property Command As ContextCommands
  18.    End Class
  19.  
  20.    Event OnCut(sender As Object, e As ContextCommandEventArgs)
  21.    Event OnCopy(sender As Object, e As ContextCommandEventArgs)
  22.    Event OnPaste(sender As Object, e As ContextCommandEventArgs)
  23.    Event OnDelete(sender As Object, e As ContextCommandEventArgs)
  24.  
  25.    Protected Overrides Sub WndProc(ByRef m As Message)
  26.  
  27.        MyBase.WndProc(m)
  28.  
  29.        Select Case m.Msg
  30.  
  31.            Case ContextCommands.WM_COPY
  32.                Last_Command = ContextCommands.WM_COPY
  33.                CopyOrCut_Timer.Enabled = True
  34.  
  35.            Case ContextCommands.WM_CUT
  36.                Last_Command = ContextCommands.WM_CUT
  37.  
  38.            Case ContextCommands.WM_PASTE
  39.                RaiseEvent OnPaste(Me, New ContextCommandEventArgs() _
  40.                                       With {.Command = ContextCommands.WM_PASTE})
  41.  
  42.            Case ContextCommands.WM_DELETE
  43.                RaiseEvent OnDelete(Me, New ContextCommandEventArgs() _
  44.                                        With {.Command = ContextCommands.WM_DELETE})
  45.  
  46.        End Select
  47.  
  48.    End Sub
  49.  
  50.    Private Sub Cut_Timer_Tick(sender As Object, e As EventArgs) _
  51.    Handles CopyOrCut_Timer.Tick
  52.  
  53.        sender.enabled = False
  54.  
  55.        Select Case Last_Command
  56.  
  57.            Case ContextCommands.WM_COPY
  58.                RaiseEvent OnCopy(Me, New ContextCommandEventArgs() _
  59.                                      With {.Command = ContextCommands.WM_COPY})
  60.  
  61.            Case ContextCommands.WM_CUT
  62.                RaiseEvent OnCut(Me, New ContextCommandEventArgs() _
  63.                                     With {.Command = ContextCommands.WM_CUT})
  64.  
  65.        End Select
  66.  
  67.        Last_Command = Nothing
  68.  
  69.    End Sub
  70.  
  71. End Class
En línea



Páginas: 1 ... 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 [33] 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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