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 1 Visitante están viendo este tema.
Páginas: 1 ... 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 49 50 51 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,176 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #350 en: 5 Diciembre 2013, 19:47 pm »

Actualizada la colección de snippets con un total de 544 Snippets...
...Casi nada!!

http://elektrostudios.tk/Snippets.zip

En la primera página de este hilo tienen un índice de todos los snippets que contiene el pack.

PD: Algunos de los antiguos snippets (no todos) han sido mejorados y/o simplificados.

Saludos!


« Última modificación: 5 Diciembre 2013, 19:49 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #351 en: 8 Diciembre 2013, 00:26 am »

Un ayudante para la interface MCI, reproduce archivos wav,mp3,midi y obtiene información esencial del archivo.

La class es algo básica, solo le añadí lo esencial porque me dió bastantes problemas la verdad.

Código
  1. ' [ MCI Player ]
  2. '
  3. ' // By Elektro H@cker
  4.  
  5. #Region " Usage Examples "
  6.  
  7. ' Dim AudioFile As New MCIPlayer("C:\Audio.wav")
  8. ' AudioFile.Play(AudioPlayMode.BackgroundLoop)
  9.  
  10. ' Dim sb As New System.Text.StringBuilder
  11. ' sb.AppendLine("Filename: " & AudioFile.Filename)
  12. ' sb.AppendLine("State...: " & AudioFile.State.ToString)
  13. ' sb.AppendLine("Mode....: " & AudioFile.PlaybackMode.ToString)
  14. ' sb.AppendLine("Channels: " & CStr(AudioFile.Channels))
  15. ' sb.AppendLine("Duration: " & TimeSpan.FromMilliseconds(AudioFile.Duration).ToString("hh\:mm\:ss"))
  16.  
  17. ' MessageBox.Show(sb.ToString, "MCI Player", MessageBoxButtons.OK, MessageBoxIcon.Information)
  18.  
  19. ' AudioFile.Stop()
  20.  
  21. #End Region
  22.  
  23. #Region " MCI Player "
  24.  
  25. ''' <summary>
  26. ''' Play Wave, MP3 or MIDI files
  27. ''' </summary>
  28. Public Class MCIPlayer
  29.    Inherits NativeWindow
  30.    Implements IDisposable
  31.  
  32. #Region " API "
  33.  
  34.    ''' <summary>
  35.    ''' Sends a command string to an MCI device.
  36.    ''' The device that the command is sent to is specified in the command string.
  37.    ''' </summary>
  38.    ''' <param name="command">
  39.    ''' Pointer to a null-terminated string that specifies an MCI command string.
  40.    ''' For a list, see Multimedia Command Strings.
  41.    ''' </param>
  42.    ''' <param name="buffer">
  43.    ''' Buffer that receives return information.
  44.    ''' If no return information is needed, this parameter can be NULL.
  45.    ''' </param>
  46.    ''' <param name="bufferSize">
  47.    ''' Size, in characters, of the return buffer specified.
  48.    ''' </param>
  49.    ''' <param name="hwndCallback">
  50.    ''' Handle to a callback window if the "notify" flag was specified in the command string.
  51.    ''' </param>
  52.    <System.Runtime.InteropServices.
  53.    DllImport("winmm.dll", SetLastError:=True)>
  54.    Private Shared Function mciSendString(
  55.            ByVal command As String,
  56.            ByVal buffer As System.Text.StringBuilder,
  57.            ByVal bufferSize As Integer,
  58.            ByVal hwndCallback As IntPtr
  59.    ) As Integer
  60.    End Function
  61.  
  62. #End Region
  63.  
  64. #Region " Variables "
  65.  
  66.    ''' <summary>
  67.    ''' The form to manage Windows Messages.
  68.    ''' </summary>
  69.    Private WithEvents formulary As Form = Nothing
  70.  
  71.    ''' <summary>
  72.    ''' Indicates the audio play command of mciSendString.
  73.    ''' </summary>
  74.    Private PlayCommand As String = String.Empty
  75.  
  76.    ''' <summary>
  77.    ''' Buffer that receives return information.
  78.    ''' </summary>
  79.    Private ReturnInfo As New System.Text.StringBuilder() With {.Capacity = 255}
  80.  
  81.    ''' <summary>
  82.    ''' The current filename of the file that is to be played.
  83.    ''' </summary>
  84.    Private _filename As String = String.Empty
  85.  
  86.    ''' <summary>
  87.    ''' Indicates the current playback mode.
  88.    ''' </summary>
  89.    Private _PlaybackMode As AudioPlayMode
  90.  
  91.    ''' <summary>
  92.    ''' Flag to cancel the BackgroundLoop PlaybackMode.
  93.    ''' </summary>
  94.    Private CancelLoop As Boolean = False
  95.  
  96. #End Region
  97.  
  98. #Region " Properties "
  99.  
  100.    ''' <summary>
  101.    ''' The current filename of the file that is to be played.
  102.    ''' </summary>
  103.    Public Property Filename() As String
  104.  
  105.        Get
  106.            Return _filename
  107.        End Get
  108.  
  109.        Set(ByVal value As String)
  110.  
  111.            If Not IO.File.Exists(value) Then
  112.                Throw New IO.FileNotFoundException
  113.                Exit Property
  114.            End If
  115.  
  116.            _filename = value
  117.  
  118.        End Set
  119.  
  120.    End Property
  121.  
  122.    ''' <summary>
  123.    ''' Gets che current Playback State.
  124.    ''' </summary>
  125.    Public ReadOnly Property State As PlaybackState
  126.        Get
  127.            mciSendString("status file mode", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
  128.            Return [Enum].Parse(GetType(PlaybackState), ReturnInfo.ToString, True)
  129.        End Get
  130.    End Property
  131.  
  132.    ''' <summary>
  133.    ''' Gets or sets the playback mode of the current file.
  134.    ''' </summary>
  135.    Public Property PlaybackMode As AudioPlayMode
  136.        Get
  137.            Return _PlaybackMode
  138.        End Get
  139.        Set(value As AudioPlayMode)
  140.            _PlaybackMode = value
  141.        End Set
  142.    End Property
  143.  
  144.    ''' <summary>
  145.    ''' Gets the channels of the file.
  146.    ''' </summary>
  147.    ReadOnly Property Channels() As Integer
  148.        Get
  149.            mciSendString("status file channels", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
  150.            Return If(IsNumeric(ReturnInfo.ToString),
  151.                      CInt(ReturnInfo.ToString),
  152.                      -1)
  153.        End Get
  154.    End Property
  155.  
  156.    ''' <summary>
  157.    ''' Gets the file duration in Milleseconds.
  158.    ''' </summary>
  159.    ReadOnly Property Duration() As Integer
  160.        Get
  161.            mciSendString("set file time format milliseconds", Nothing, 0, IntPtr.Zero)
  162.            mciSendString("status file length", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
  163.            Return If(String.IsNullOrEmpty(ReturnInfo.ToString), 0, CInt(ReturnInfo.ToString))
  164.        End Get
  165.    End Property
  166.  
  167. #End Region
  168.  
  169. #Region " Enumerations "
  170.  
  171.    ''' <summary>
  172.    ''' Audio File playback state.
  173.    ''' </summary>
  174.    Public Enum PlaybackState As Short
  175.  
  176.        ''' <summary>
  177.        ''' File is playing.
  178.        ''' </summary>
  179.        Playing = 0
  180.  
  181.        ''' <summary>
  182.        ''' File is paused.
  183.        ''' </summary>
  184.        Paused = 1
  185.  
  186.        ''' <summary>
  187.        ''' File is stopped.
  188.        ''' </summary>
  189.        Stopped = 2
  190.  
  191.    End Enum
  192.  
  193.    ''' <summary>
  194.    ''' Windows Message Identifiers.
  195.    ''' </summary>
  196.    Public Enum KnownMessages As Integer
  197.  
  198.        ''' <summary>
  199.        ''' Notifies an application that an MCI device has completed an operation.
  200.        ''' MCI devices send this message only when the MCI_NOTIFY flag is used.
  201.        ''' </summary>
  202.        MM_MCINOTIFY = 953
  203.  
  204.    End Enum
  205.  
  206. #End Region
  207.  
  208. #Region " Constructor "
  209.  
  210.    ''' <summary>
  211.    ''' Play Wave, MP3 or MIDI files.
  212.    ''' </summary>
  213.    ''' <param name="AudioFile">Indicates the filename of the media to play.</param>
  214.    Public Sub New(ByVal AudioFile As String)
  215.  
  216.        ' Set the Audio file.
  217.        Me.Filename = AudioFile
  218.  
  219.        ' Set the Formulary.
  220.        Me.formulary = Form.ActiveForm
  221.  
  222.        ' Assign the form handle.
  223.        SetFormHandle()
  224.  
  225.    End Sub
  226.  
  227.    ''' <summary>
  228.    ''' Play Wave, MP3 or MIDI files.
  229.    ''' </summary>
  230.    ''' <param name="Formulary">Indicates the Form to assign the Handle.</param>
  231.    ''' <param name="AudioFile">Indicates the filename of the media to play.</param>
  232.    ''' <remarks></remarks>
  233.    Public Sub New(ByVal Formulary As Form, ByVal AudioFile As String)
  234.  
  235.        ' Set the Audio file.
  236.        Me.Filename = AudioFile
  237.  
  238.        ' Set the Formulary.
  239.        Me.formulary = Formulary
  240.  
  241.        ' Assign the form handle.
  242.        SetFormHandle()
  243.  
  244.    End Sub
  245.  
  246. #End Region
  247.  
  248. #Region " Public Methods "
  249.  
  250.    ''' <summary>
  251.    ''' Plays the file that is specified as the filename.
  252.    ''' </summary>
  253.    ''' <remarks></remarks>
  254.    Public Sub Play(ByVal PlayMode As AudioPlayMode)
  255.  
  256.        DisposedCheck()
  257.  
  258.        Select Case PlayMode
  259.  
  260.            Case AudioPlayMode.Background
  261.                PlayCommand = "play file from 0"
  262.                Me.PlaybackMode = AudioPlayMode.Background
  263.  
  264.            Case AudioPlayMode.BackgroundLoop
  265.                PlayCommand = "play file from 0 notify"
  266.                Me.PlaybackMode = AudioPlayMode.BackgroundLoop
  267.  
  268.            Case AudioPlayMode.WaitToComplete
  269.                PlayCommand = "play file from 0 wait"
  270.                Me.PlaybackMode = AudioPlayMode.WaitToComplete
  271.  
  272.        End Select
  273.  
  274.        ' Open command
  275.        Select Case Me.Filename.Split(".").LastOrDefault
  276.  
  277.            Case "mp3"
  278.                mciSendString(String.Format("open ""{0}"" type mpegvideo alias file", Me.Filename),
  279.                              Nothing,
  280.                              0,
  281.                              IntPtr.Zero)
  282.  
  283.            Case "wav"
  284.                mciSendString(String.Format("open ""{0}"" type waveaudio alias file", Me.Filename),
  285.                              Nothing,
  286.                              0,
  287.                              IntPtr.Zero)
  288.  
  289.            Case "mid", "midi"
  290.                mciSendString("stop midi", Nothing, 0, 0)
  291.                mciSendString("close midi", Nothing, 0, 0)
  292.                mciSendString(String.Format("open sequencer! ""{0}"" alias file", Me.Filename),
  293.                              Nothing,
  294.                              0, IntPtr.Zero)
  295.  
  296.            Case Else
  297.                Throw New Exception("File type not supported.")
  298.                [Close]()
  299.  
  300.        End Select
  301.  
  302.        ' Play command
  303.        mciSendString(PlayCommand, Nothing, 0, If(PlaybackMode = AudioPlayMode.BackgroundLoop,
  304.                                                  Me.Handle,
  305.                                                  IntPtr.Zero))
  306.  
  307.    End Sub
  308.  
  309.    ''' <summary>
  310.    ''' Pause the current playback.
  311.    ''' </summary>
  312.    ''' <remarks></remarks>
  313.    Public Sub Pause()
  314.        DisposedCheck()
  315.        CancelLoop = True
  316.        mciSendString("pause file", Nothing, 0, IntPtr.Zero)
  317.    End Sub
  318.  
  319.    ''' <summary>
  320.    ''' Resume the current playback if it is currently paused.
  321.    ''' </summary>
  322.    Public Sub [Resume]()
  323.        DisposedCheck()
  324.        If Me.State = PlaybackState.Paused Then
  325.            CancelLoop = False
  326.            mciSendString("resume file", Nothing, 0, IntPtr.Zero)
  327.        End If
  328.    End Sub
  329.  
  330.    ''' <summary>
  331.    ''' Stop the current playback.
  332.    ''' </summary>
  333.    Public Sub [Stop]()
  334.        DisposedCheck()
  335.        CancelLoop = True
  336.        mciSendString("stop file", Nothing, 0, IntPtr.Zero)
  337.    End Sub
  338.  
  339.    ''' <summary>
  340.    ''' Close the current file.
  341.    ''' </summary>
  342.    Public Overloads Sub [Close]()
  343.        DisposedCheck()
  344.        CancelLoop = True
  345.        mciSendString("close file", Nothing, 0, IntPtr.Zero)
  346.    End Sub
  347.  
  348. #End Region
  349.  
  350. #Region " Event Handlers "
  351.  
  352.    ''' <summary>
  353.    ''' Assign the handle of the target form to this NativeWindow,
  354.    ''' necessary to override WndProc.
  355.    ''' </summary>
  356.    Private Sub SetFormHandle() _
  357.    Handles formulary.HandleCreated, formulary.Load, formulary.Shown
  358.  
  359.        Try
  360.            If Not Me.Handle.Equals(Me.formulary.Handle) Then
  361.                Me.AssignHandle(Me.formulary.Handle)
  362.            End If
  363.        Catch ' ex As InvalidOperationException
  364.        End Try
  365.  
  366.    End Sub
  367.  
  368.    ''' <summary>
  369.    ''' Releases the Handle.
  370.    ''' </summary>
  371.    Private Sub OnHandleDestroyed() _
  372.    Handles formulary.HandleDestroyed
  373.  
  374.        Me.ReleaseHandle()
  375.  
  376.    End Sub
  377.  
  378. #End Region
  379.  
  380. #Region " Windows Messages "
  381.  
  382.    ''' <summary>
  383.    ''' Processes Windows messages for this Window.
  384.    ''' </summary>
  385.    ''' <param name="m">
  386.    ''' Contains the Windows Message parameters.
  387.    ''' </param>
  388.    Protected Overrides Sub WndProc(ByRef m As Message)
  389.  
  390.        MyBase.WndProc(m)
  391.  
  392.        If m.Msg = KnownMessages.MM_MCINOTIFY Then
  393.  
  394.            If Not CancelLoop Then
  395.                Play(AudioPlayMode.BackgroundLoop)
  396.            Else
  397.                CancelLoop = False
  398.            End If
  399.  
  400.        End If
  401.  
  402.    End Sub
  403.  
  404. #End Region
  405.  
  406. #Region " IDisposable "
  407.  
  408.    ''' <summary>
  409.    ''' To detect redundant calls when disposing.
  410.    ''' </summary>
  411.    Private IsDisposed As Boolean = False
  412.  
  413.    ''' <summary>
  414.    ''' Prevents calls to methods after disposing.
  415.    ''' </summary>
  416.    Private Sub DisposedCheck()
  417.        If Me.IsDisposed Then
  418.            Throw New ObjectDisposedException(Me.GetType().FullName)
  419.        End If
  420.    End Sub
  421.  
  422.    ''' <summary>
  423.    ''' Disposes the objects generated by this instance.
  424.    ''' </summary>
  425.    Public Sub Dispose() Implements IDisposable.Dispose
  426.        Dispose(True)
  427.        GC.SuppressFinalize(Me)
  428.    End Sub
  429.  
  430.    ' IDisposable
  431.    Protected Overridable Sub Dispose(IsDisposing As Boolean)
  432.  
  433.        If Not Me.IsDisposed Then
  434.  
  435.            If IsDisposing Then
  436.                [Close]()
  437.                Me.formulary = Nothing
  438.                Me.ReleaseHandle()
  439.                Me.DestroyHandle()
  440.            End If
  441.  
  442.        End If
  443.  
  444.        Me.IsDisposed = True
  445.  
  446.    End Sub
  447.  
  448. #End Region
  449.  
  450. End Class
  451.  
  452. #End Region





Un pequeño ejemplo que hice para recordar el uso de una Task:

Código
  1. #Region " TASK Example "
  2.  
  3. Public Class Form1
  4.  
  5.    ' NORMAL TASK USAGE:
  6.    ' ------------------
  7.    Private Task1 As Threading.Tasks.Task
  8.    Private Task1CTS As New Threading.CancellationTokenSource
  9.    Private Task1CT As Threading.CancellationToken = Task1CTS.Token
  10.  
  11.    Private Sub MyTask1(ByVal CancellationToken As Threading.CancellationToken)
  12.  
  13.        For x As Integer = 0 To 9999
  14.  
  15.            If Not CancellationToken.IsCancellationRequested Then
  16.                Debug.Print("Task1: " & x)
  17.            Else
  18.                MsgBox(String.Format("Task1 Canceled at ""{0}""", x))
  19.                Exit Sub
  20.            End If
  21.  
  22.        Next x
  23.  
  24.    End Sub
  25.  
  26.    ' ANONYMOUS TASK METHOD:
  27.    ' ---------------------
  28.    Private Task2 As Threading.Tasks.Task
  29.    Private Task2CTS As New Threading.CancellationTokenSource
  30.    Private Task2CT As Threading.CancellationToken = Task2CTS.Token
  31.  
  32.    Private Delegate Function Task2Delegate(ByVal CancellationToken As Threading.CancellationToken)
  33.  
  34.    Private MyTask2 As Task2Delegate =
  35.      Function(CancellationToken As Threading.CancellationToken) As Boolean
  36.  
  37.          For x As Integer = 0 To 9999
  38.  
  39.              If Not CancellationToken.IsCancellationRequested Then
  40.                  Debug.Print("Task2: " & x)
  41.              Else
  42.                  MsgBox(String.Format("Task2 Canceled at ""{0}""", x))
  43.                  Return False
  44.              End If
  45.  
  46.          Next x
  47.  
  48.          Return True
  49.  
  50.      End Function
  51.  
  52.    Private Sub TaskTest() Handles MyBase.Shown
  53.  
  54.        ' Run an asynchronous Task.
  55.        Task1 = Threading.Tasks.Task.Factory.StartNew(Sub() MyTask1(Task1CT), Task1CT)
  56.  
  57.        ' Wait 2 seconds (Just to demonstrate this example)
  58.        Threading.Thread.Sleep(2 * 1000)
  59.  
  60.        ' Cancel the Task.
  61.        Task1CTS.Cancel()
  62.  
  63.        ' Wait for the Task to finish the being cancelled.
  64.        Task1.Wait()
  65.  
  66.        ' Show the task status
  67.        MsgBox(Task1.Status.ToString) ' Result: RanToCompletion
  68.  
  69.        ' ReStart the Task1.
  70.        Task1 = Threading.Tasks.Task.Factory.StartNew(Sub() MyTask1(Task1CT), Task1CT)
  71.  
  72.        ' Start the Task2
  73.        Task2 = Threading.Tasks.Task.Factory.StartNew(Of Boolean)(Function() MyTask2(Task2CT), Task2CT)
  74.  
  75.        ' Wait for both Taks to finish their execution.
  76.        Threading.Tasks.Task.WaitAll()
  77.  
  78.    End Sub
  79.  
  80. End Class
  81.  
  82. #End Region


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #352 en: 10 Diciembre 2013, 07:22 am »

Un buen ejemplo de como parsear un documento HTML utilizando la librería HTMLAgilityPack.

Código
  1. Public Class Form1
  2.  
  3.    Private ReadOnly html As String =
  4.        <a><![CDATA[
  5. <!DOCTYPE html>
  6. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  7. <body>
  8.  
  9. <div class="infolinks"><input type="hidden" name="IL_IN_TAG" value="1"/></div><div id="main">
  10.  
  11. <div class="music">
  12.  
  13. <h2 class="boxtitle">New releases \ <small>
  14. <a href="/newalbums" title="New releases mp3 downloads" rel="bookmark">see all</a></small>
  15. </h2>
  16.  
  17. <div class="item">
  18.  
  19.     <div class="thumb">
  20. <a href="http://www.mp3crank.com/curt-smith/deceptively-heavy-121861" rel="bookmark" lang="en" title="Curt Smith - Deceptively Heavy album downloads"><img width="100" height="100" alt="Mp3 downloads Curt Smith - Deceptively Heavy" title="Free mp3 downloads Curt Smith - Deceptively Heavy" src="http://www.mp3crank.com/cover-album/Curt-Smith-Deceptively-Heavy-400x400.jpg"/></a>
  21.     </div>
  22.  
  23. <div class="release">
  24. <h3>Curt Smith</h3>
  25. <h4>
  26. <a href="http://www.mp3crank.com/curt-smith/deceptively-heavy-121861" title="Mp3 downloads Curt Smith - Deceptively Heavy">Deceptively Heavy</a>
  27. </h4>
  28. <script src="/ads/button.js"></script>
  29. </div>
  30.  
  31. <div class="release-year">
  32. <p>Year</p>
  33. <span>2013</span>
  34. </div>
  35.  
  36. <div class="genre">
  37. <p>Genre</p>
  38. <a href="http://www.mp3crank.com/genre/indie" rel="tag">Indie</a><a href="http://www.mp3crank.com/genre/pop" rel="tag">Pop</a>
  39. </div>
  40.  
  41. </div>
  42.  
  43. <div class="item">
  44.  
  45.     <div class="thumb">
  46. <a href="http://www.mp3crank.com/wolf-eyes/lower-demos-121866" rel="bookmark" lang="en" title="Wolf Eyes - Lower Demos album downloads"><img width="100" height="100" alt="Mp3 downloads Wolf Eyes - Lower Demos" title="Free mp3 downloads Wolf Eyes - Lower Demos" src="http://www.mp3crank.com/cover-album/Wolf-Eyes-–-Lower-Demos.jpg" /></a>
  47.     </div>
  48.  
  49. <div class="release">
  50. <h3>Wolf Eyes</h3>
  51. <h4>
  52. <a href="http://www.mp3crank.com/wolf-eyes/lower-demos-121866" title="Mp3 downloads Wolf Eyes - Lower Demos">Lower Demos</a>
  53. </h4>
  54. <script src="/ads/button.js"></script>
  55. </div>
  56.  
  57. <div class="release-year">
  58. <p>Year</p>
  59. <span>2013</span>
  60. </div>
  61.  
  62. <div class="genre">
  63. <p>Genre</p>
  64. <a href="http://www.mp3crank.com/genre/rock" rel="tag">Rock</a>
  65. </div>
  66.  
  67. </div>
  68.  
  69. </div>
  70.  
  71. </div>
  72.  
  73. </body>
  74. </html>
  75. ]]></a>.Value
  76.  
  77.    Private sb As New System.Text.StringBuilder
  78.  
  79.    Private htmldoc As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument
  80.    Private htmlnodes As HtmlAgilityPack.HtmlNodeCollection = Nothing
  81.  
  82.    Private Title As String = String.Empty
  83.    Private Cover As String = String.Empty
  84.    Private Year As String = String.Empty
  85.    Private Genres As String() = {String.Empty}
  86.    Private URL As String = String.Empty
  87.  
  88.    Private Sub Test() Handles MyBase.Shown
  89.  
  90.        ' Load the html document.
  91.        htmldoc.LoadHtml(html)
  92.  
  93.        ' Select the (10 items) nodes.
  94.        ' All "SelectSingleNode" below will use this DIV element as a starting point.
  95.        htmlnodes = htmldoc.DocumentNode.SelectNodes("//div[@class='item']")
  96.  
  97.        ' Loop trough the nodes.
  98.        For Each node As HtmlAgilityPack.HtmlNode In htmlnodes
  99.  
  100.            Title = node.SelectSingleNode(".//div[@class='release']/h4/a[@title]").GetAttributeValue("title", "Unknown Title")
  101.            Cover = node.SelectSingleNode(".//div[@class='thumb']/a/img[@src]").GetAttributeValue("src", String.Empty)
  102.            Year = node.SelectSingleNode(".//div[@class='release-year']/span").InnerText
  103.            Genres = (From n In node.SelectNodes(".//div[@class='genre']/a") Select n.InnerText).ToArray()
  104.            URL = node.SelectSingleNode(".//div[@class='release']/h4/a[@href]").GetAttributeValue("href", "Unknown URL")
  105.  
  106.            ' Display the information:
  107.            sb.Clear()
  108.            sb.AppendLine(String.Format("Title : {0}", Title))
  109.            sb.AppendLine(String.Format("Cover : {0}", Cover))
  110.            sb.AppendLine(String.Format("Year  : {0}", Year))
  111.            sb.AppendLine(String.Format("Genres: {0}", String.Join(", ", Genres)))
  112.            sb.AppendLine(String.Format("URL   : {0}", URL))
  113.            MsgBox(sb.ToString)
  114.  
  115.        Next node
  116.  
  117.    End Sub
  118.  
  119. End Class
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #353 en: 10 Diciembre 2013, 17:55 pm »

Una nueva versión de mi INI manager, empecé desde cero para simplificar todo el código y le añadí un parámetro al método "Get_Value" para devolver un valor por defecto (se debe especificar) si el valor no se encuentra.

Código
  1. ' [ INI File Manager ]
  2. '
  3. ' // By Elektro H@cker
  4.  
  5. #Region " Usage Examples "
  6.  
  7. '' Set the initialization file path.
  8. 'INIFileManager.FilePath = IO.Path.Combine(Application.StartupPath, "Config.ini")
  9.  
  10. '' Create the initialization file.
  11. 'INIFileManager.File.Create()
  12.  
  13. '' Check that the initialization file exist.
  14. 'MsgBox(INIFileManager.File.Exist)
  15.  
  16. '' Writes a new entire initialization file with the specified text content.
  17. 'INIFileManager.File.Write(New List(Of String) From {"[Section Name 1]"})
  18.  
  19. '' Set an existing value or append it at the enf of the initialization file.
  20. 'INIFileManager.Key.Set("KeyName1", "Value1")
  21.  
  22. '' Set an existing value on a specific section or append them at the enf of the initialization file.
  23. 'INIFileManager.Key.Set("KeyName2", "Value2", "[Section Name 2]")
  24.  
  25. '' Gets the value of the specified Key name,
  26. 'MsgBox(INIFileManager.Key.Get("KeyName1"))
  27.  
  28. '' Gets the value of the specified Key name on the specified Section.
  29. 'MsgBox(INIFileManager.Key.Get("KeyName2", , "[Section Name 2]"))
  30.  
  31. '' Gets the value of the specified Key name and returns a default value if the key name is not found.
  32. 'MsgBox(INIFileManager.Key.Get("KeyName0", "I'm a default value"))
  33.  
  34. '' Gets the value of the specified Key name, and assign it to a control property.
  35. 'CheckBox1.Checked = CType(INIFileManager.Key.Get("KeyName1"), Boolean)
  36.  
  37. '' Checks whether a Key exists.
  38. 'MsgBox(INIFileManager.Key.Exist("KeyName1"))
  39.  
  40. '' Checks whether a Key exists on a specific section.
  41. 'MsgBox(INIFileManager.Key.Exist("KeyName2", "[First Section]"))
  42.  
  43. '' Remove a key name.
  44. 'INIFileManager.Key.Remove("KeyName1")
  45.  
  46. '' Remove a key name on the specified Section.
  47. 'INIFileManager.Key.Remove("KeyName2", "[Section Name 2]")
  48.  
  49. '' Add a new section.
  50. 'INIFileManager.Section.Add("[Section Name 3]")
  51.  
  52. '' Get the contents of a specific section.
  53. 'MsgBox(String.Join(Environment.NewLine, INIFileManager.Section.Get("[Section Name 1]")))
  54.  
  55. '' Remove an existing section.
  56. 'INIFileManager.Section.Remove("[Section Name 2]")
  57.  
  58. '' Checks that the initialization file contains at least one section.
  59. 'MsgBox(INIFileManager.Section.Has())
  60.  
  61. '' Sort the initialization file (And remove empty lines).
  62. 'INIFileManager.File.Sort(True)
  63.  
  64. '' Gets the initialization file section names.
  65. 'MsgBox(String.Join(", ", INIFileManager.Section.GetNames()))
  66.  
  67. '' Gets the initialization file content.
  68. 'MsgBox(String.Join(Environment.NewLine, INIFileManager.File.Get()))
  69.  
  70. '' Delete the initialization file from disk.
  71. 'INIFileManager.File.Delete()
  72.  
  73. #End Region
  74.  
  75. #Region " INI File Manager "
  76.  
  77. Public Class INIFileManager
  78.  
  79. #Region " Members "
  80.  
  81. #Region " Properties "
  82.  
  83.    ''' <summary>
  84.    ''' Indicates the initialization file path.
  85.    ''' </summary>
  86.    Public Shared Property FilePath As String =
  87.        IO.Path.Combine(Application.StartupPath, Process.GetCurrentProcess().ProcessName & ".ini")
  88.  
  89. #End Region
  90.  
  91. #Region " Variables "
  92.  
  93.    ''' <summary>
  94.    ''' Stores the initialization file content.
  95.    ''' </summary>
  96.    Private Shared Content As New List(Of String)
  97.  
  98.    ''' <summary>
  99.    ''' Stores the INI section names.
  100.    ''' </summary>
  101.    Private Shared SectionNames As String() = {String.Empty}
  102.  
  103.    ''' <summary>
  104.    ''' Indicates the start element index of a section name.
  105.    ''' </summary>
  106.    Private Shared SectionStartIndex As Integer = -1
  107.  
  108.    ''' <summary>
  109.    ''' Indicates the end element index of a section name.
  110.    ''' </summary>
  111.    Private Shared SectionEndIndex As Integer = -1
  112.  
  113.    ''' <summary>
  114.    ''' Stores a single sorted section block with their keys and values.
  115.    ''' </summary>
  116.    Private Shared SortedSection As New List(Of String)
  117.  
  118.    ''' <summary>
  119.    ''' Stores all the sorted section blocks with their keys and values.
  120.    ''' </summary>
  121.    Private Shared SortedSections As New List(Of String)
  122.  
  123.    ''' <summary>
  124.    ''' Indicates the INI element index that contains the Key and value.
  125.    ''' </summary>
  126.    Private Shared KeyIndex As Integer = -1
  127.  
  128.    ''' <summary>
  129.    ''' Indicates the culture to compare the strings.
  130.    ''' </summary>
  131.    Private Shared ReadOnly CompareMode As StringComparison = StringComparison.InvariantCultureIgnoreCase
  132.  
  133. #End Region
  134.  
  135. #Region " Exceptions "
  136.  
  137.    ''' <summary>
  138.    ''' Exception is thrown when a section name parameter has invalid format.
  139.    ''' </summary>
  140.    Private Class SectionNameInvalidFormatException
  141.        Inherits Exception
  142.  
  143.        Public Sub New()
  144.            MyBase.New("Section name parameter has invalid format." &
  145.                       Environment.NewLine &
  146.                       "The rigth syntax is: [SectionName]")
  147.        End Sub
  148.  
  149.        Public Sub New(message As String)
  150.            MyBase.New(message)
  151.        End Sub
  152.  
  153.        Public Sub New(message As String, inner As Exception)
  154.            MyBase.New(message, inner)
  155.        End Sub
  156.  
  157.    End Class
  158.  
  159. #End Region
  160.  
  161. #End Region
  162.  
  163. #Region " Methods "
  164.  
  165.    <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  166.    Private Shadows Sub ReferenceEquals()
  167.    End Sub
  168.  
  169.    <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  170.    Private Shadows Sub Equals()
  171.    End Sub
  172.  
  173.    Public Class [File]
  174.  
  175.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  176.        Private Shadows Sub ReferenceEquals()
  177.        End Sub
  178.  
  179.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  180.        Private Shadows Sub Equals()
  181.        End Sub
  182.  
  183.        ''' <summary>
  184.        ''' Checks whether the initialization file exist.
  185.        ''' </summary>
  186.        ''' <returns>True if initialization file exist, otherwise False.</returns>
  187.        Public Shared Function Exist() As Boolean
  188.            Return IO.File.Exists(FilePath)
  189.        End Function
  190.  
  191.        ''' <summary>
  192.        ''' Creates the initialization file.
  193.        ''' If the file already exist it would be replaced.
  194.        ''' </summary>
  195.        ''' <param name="Encoding">The Text encoding to write the initialization file.</param>
  196.        ''' <returns>True if the operation success, otherwise False.</returns>
  197.        Public Shared Function Create(Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  198.  
  199.            Try
  200.                IO.File.WriteAllText(FilePath,
  201.                                     String.Empty,
  202.                                     If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
  203.            Catch ex As Exception
  204.                Throw
  205.                Return False
  206.  
  207.            End Try
  208.  
  209.            Return True
  210.  
  211.        End Function
  212.  
  213.        ''' <summary>
  214.        ''' Deletes the initialization file.
  215.        ''' </summary>
  216.        ''' <returns>True if the operation success, otherwise False.</returns>
  217.        Public Shared Function Delete() As Boolean
  218.  
  219.            If Not [File].Exist Then Return False
  220.  
  221.            Try
  222.                IO.File.Delete(FilePath)
  223.            Catch ex As Exception
  224.                Throw
  225.                Return False
  226.  
  227.            End Try
  228.  
  229.            Content = Nothing
  230.  
  231.            Return True
  232.  
  233.        End Function
  234.  
  235.        ''' <summary>
  236.        ''' Returns the initialization file content.
  237.        ''' </summary>
  238.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  239.        Public Shared Function [Get](Optional ByVal Encoding As System.Text.Encoding = Nothing) As List(Of String)
  240.  
  241.            Content = IO.File.ReadAllLines(FilePath,
  242.                                           If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding)).ToList()
  243.  
  244.            Return Content
  245.  
  246.        End Function
  247.  
  248.        ''' <summary>
  249.        ''' Sort the initialization file content by the Key names.
  250.        ''' If the initialization file contains sections then the sections are sorted by their names also.
  251.        ''' </summary>
  252.        ''' <param name="RemoveEmptyLines">Remove empty lines.</param>
  253.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  254.        ''' <returns>True if the operation success, otherwise False.</returns>
  255.        Public Shared Function Sort(Optional ByVal RemoveEmptyLines As Boolean = False,
  256.                                    Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  257.  
  258.            If Not [File].Exist() Then Return False
  259.  
  260.            [File].[Get](Encoding)
  261.  
  262.            Select Case Section.Has(Encoding)
  263.  
  264.                Case True ' initialization file contains at least one Section.
  265.  
  266.                    SortedSection.Clear()
  267.                    SortedSections.Clear()
  268.  
  269.                    Section.GetNames(Encoding) ' Get the (sorted) section names
  270.  
  271.                    For Each name As String In SectionNames
  272.  
  273.                        SortedSection = Section.[Get](name, Encoding) ' Get the single section lines.
  274.  
  275.                        If RemoveEmptyLines Then ' Remove empty lines.
  276.                            SortedSection = SortedSection.Where(Function(line) _
  277.                                                                Not String.IsNullOrEmpty(line) AndAlso
  278.                                                                Not String.IsNullOrWhiteSpace(line)).ToList
  279.                        End If
  280.  
  281.                        SortedSection.Sort() ' Sort the single section keys.
  282.  
  283.                        SortedSections.Add(name) ' Add the section name to the sorted sections list.
  284.                        SortedSections.AddRange(SortedSection) ' Add the single section to the sorted sections list.
  285.  
  286.                    Next name
  287.  
  288.                    Content = SortedSections
  289.  
  290.                Case False ' initialization file doesn't contains any Section.
  291.                    Content.Sort()
  292.  
  293.                    If RemoveEmptyLines Then
  294.                        Content = Content.Where(Function(line) _
  295.                                                        Not String.IsNullOrEmpty(line) AndAlso
  296.                                                        Not String.IsNullOrWhiteSpace(line)).ToList
  297.                    End If
  298.  
  299.            End Select ' Section.Has()
  300.  
  301.            ' Save changes.
  302.            Return [File].Write(Content, Encoding)
  303.  
  304.        End Function
  305.  
  306.        ''' <summary>
  307.        ''' Writes a new initialization file with the specified text content..
  308.        ''' </summary>
  309.        ''' <param name="Content">Indicates the text content to write in the initialization file.</param>
  310.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  311.        ''' <returns>True if the operation success, otherwise False.</returns>
  312.        Public Shared Function Write(ByVal Content As List(Of String),
  313.                                     Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  314.  
  315.            Try
  316.                IO.File.WriteAllLines(FilePath,
  317.                                      Content,
  318.                                      If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
  319.            Catch ex As Exception
  320.                Throw
  321.                Return False
  322.  
  323.            End Try
  324.  
  325.            Return True
  326.  
  327.        End Function
  328.  
  329.    End Class
  330.  
  331.    Public Class [Key]
  332.  
  333.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  334.        Private Shadows Sub ReferenceEquals()
  335.        End Sub
  336.  
  337.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  338.        Private Shadows Sub Equals()
  339.        End Sub
  340.  
  341.        ''' <summary>
  342.        ''' Return a value indicating whether a key name exist or not.
  343.        ''' </summary>
  344.        ''' <param name="KeyName">Indicates the key name that contains the value to modify.</param>
  345.        ''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
  346.        ''' <param name="Encoding">The Text encoding to write the initialization file.</param>
  347.        ''' <returns>True if the key name exist, otherwise False.</returns>
  348.        Public Shared Function Exist(ByVal KeyName As String,
  349.                                     Optional ByVal SectionName As String = Nothing,
  350.                                     Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  351.  
  352.            If Not [File].Exist() Then Return False
  353.  
  354.            [File].[Get](Encoding)
  355.  
  356.            [Key].GetIndex(KeyName, SectionName)
  357.  
  358.            Select Case SectionName Is Nothing
  359.  
  360.                Case True
  361.                    Return Convert.ToBoolean(Not KeyIndex)
  362.  
  363.                Case Else
  364.                    Return Convert.ToBoolean(Not (KeyIndex + SectionStartIndex))
  365.  
  366.            End Select
  367.  
  368.        End Function
  369.  
  370.        ''' <summary>
  371.        ''' Set the value of an existing key name.
  372.        '''
  373.        ''' If the initialization file doesn't exists, or else the Key doesn't exist,
  374.        ''' or else the Section parameter is not specified and the key name doesn't exist;
  375.        ''' then the 'key=value' is appended to the end of the initialization file.
  376.        '''
  377.        ''' if the specified Section name exist but the Key name doesn't exist,
  378.        ''' then the 'key=value' is appended to the end of the Section.
  379.        '''
  380.        ''' </summary>
  381.        ''' <param name="KeyName">Indicates the key name that contains the value to modify.</param>
  382.        ''' <param name="Value">Indicates the new value.</param>
  383.        ''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
  384.        ''' <param name="Encoding">The Text encoding to write the initialization file.</param>
  385.        ''' <returns>True if the operation success, otherwise False.</returns>
  386.        Public Shared Function [Set](ByVal KeyName As String,
  387.                                     ByVal Value As String,
  388.                                     Optional ByVal SectionName As String = Nothing,
  389.                                     Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  390.  
  391.            If Not [File].Exist() Then [File].Create()
  392.  
  393.            [File].[Get](Encoding)
  394.  
  395.            [Key].GetIndex(KeyName, SectionName)
  396.  
  397.            ' If KeyName is not found and indicated Section is found, then...
  398.            If KeyIndex = -1 AndAlso SectionEndIndex <> -1 Then
  399.  
  400.                ' If section EndIndex is the last line of file, then...
  401.                If SectionEndIndex = Content.Count Then
  402.  
  403.                    Content(Content.Count - 1) = Content(Content.Count - 1) &
  404.                                                         Environment.NewLine &
  405.                                                         String.Format("{0}={1}", KeyName, Value)
  406.  
  407.                Else ' If not section EndIndex is the last line of file, then...
  408.  
  409.                    Content(SectionEndIndex) = String.Format("{0}={1}", KeyName, Value) &
  410.                                                    Environment.NewLine &
  411.                                                    Content(SectionEndIndex)
  412.                End If
  413.  
  414.                ' If KeyName is found then...
  415.            ElseIf KeyIndex <> -1 Then
  416.                Content(KeyIndex) = String.Format("{0}={1}", KeyName, Value)
  417.  
  418.                ' If KeyName is not found and Section parameter is passed. then...
  419.            ElseIf KeyIndex = -1 AndAlso SectionName IsNot Nothing Then
  420.                Content.Add(SectionName)
  421.                Content.Add(String.Format("{0}={1}", KeyName, Value))
  422.  
  423.                ' If KeyName is not found, then...
  424.            ElseIf KeyIndex = -1 Then
  425.                Content.Add(String.Format("{0}={1}", KeyName, Value))
  426.  
  427.            End If
  428.  
  429.            ' Save changes.
  430.            Return [File].Write(Content, Encoding)
  431.  
  432.        End Function
  433.  
  434.        ''' <summary>
  435.        ''' Get the value of an existing key name.
  436.        ''' If the initialization file or else the Key doesn't exist then a 'Nothing' object is returned.
  437.        ''' </summary>
  438.        ''' <param name="KeyName">Indicates the key name to retrieve their value.</param>
  439.        ''' <param name="DefaultValue">Indicates a default value to return if the key name is not found.</param>
  440.        ''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
  441.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  442.        Public Shared Function [Get](ByVal KeyName As String,
  443.                                     Optional ByVal DefaultValue As Object = Nothing,
  444.                                     Optional ByVal SectionName As String = Nothing,
  445.                                     Optional ByVal Encoding As System.Text.Encoding = Nothing) As Object
  446.  
  447.            If Not [File].Exist() Then Return DefaultValue
  448.  
  449.            [File].[Get](Encoding)
  450.  
  451.            [Key].GetIndex(KeyName, SectionName)
  452.  
  453.            Select Case KeyIndex
  454.  
  455.                Case Is <> -1 ' KeyName found.
  456.                    Return Content(KeyIndex).Substring(Content(KeyIndex).IndexOf("=") + 1)
  457.  
  458.                Case Else ' KeyName not found.
  459.                    Return DefaultValue
  460.  
  461.            End Select
  462.  
  463.        End Function
  464.  
  465.        ''' <summary>
  466.        ''' Returns the initialization file line index of the key name.
  467.        ''' </summary>
  468.        ''' <param name="KeyName">Indicates the Key name to retrieve their value.</param>
  469.        ''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
  470.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  471.        Private Shared Sub GetIndex(ByVal KeyName As String,
  472.                                    Optional ByVal SectionName As String = Nothing,
  473.                                    Optional ByVal Encoding As System.Text.Encoding = Nothing)
  474.  
  475.            If Content Is Nothing Then [File].Get(Encoding)
  476.  
  477.            ' Reset the INI index elements to negative values.
  478.            KeyIndex = -1
  479.            SectionStartIndex = -1
  480.            SectionEndIndex = -1
  481.  
  482.            If SectionName IsNot Nothing AndAlso Not SectionName Like "[[]?*[]]" Then
  483.                Throw New SectionNameInvalidFormatException
  484.                Exit Sub
  485.            End If
  486.  
  487.            ' Locate the KeyName and set their element index.
  488.            ' If the KeyName is not found then the value is set to "-1" to return an specified default value.
  489.            Select Case String.IsNullOrEmpty(SectionName)
  490.  
  491.                Case True ' Any SectionName parameter is specified.
  492.  
  493.                    KeyIndex = Content.FindIndex(Function(line) line.StartsWith(String.Format("{0}=", KeyName),
  494.                                                                              StringComparison.InvariantCultureIgnoreCase))
  495.  
  496.                Case False ' SectionName parameter is specified.
  497.  
  498.                    Select Case Section.Has(Encoding)
  499.  
  500.                        Case True ' INI contains at least one Section.
  501.  
  502.                            SectionStartIndex = Content.FindIndex(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode))
  503.                            If SectionStartIndex = -1 Then ' Section doesn't exist.
  504.                                Exit Sub
  505.                            End If
  506.  
  507.                            SectionEndIndex = Content.FindIndex(SectionStartIndex + 1, Function(line) line.Trim Like "[[]?*[]]")
  508.                            If SectionEndIndex = -1 Then
  509.                                ' This fixes the value if the section is at the end of file.
  510.                                SectionEndIndex = Content.Count
  511.                            End If
  512.  
  513.                            KeyIndex = Content.FindIndex(SectionStartIndex, SectionEndIndex - SectionStartIndex,
  514.                                                                  Function(line) line.StartsWith(String.Format("{0}=", KeyName),
  515.                                                                                      StringComparison.InvariantCultureIgnoreCase))
  516.  
  517.                        Case False ' INI doesn't contains Sections.
  518.                            GetIndex(KeyName, , Encoding)
  519.  
  520.                    End Select ' Section.Has()
  521.  
  522.            End Select ' String.IsNullOrEmpty(SectionName)
  523.  
  524.        End Sub
  525.  
  526.        ''' <summary>
  527.        ''' Remove an existing key name.
  528.        ''' </summary>
  529.        ''' <param name="KeyName">Indicates the key name to retrieve their value.</param>
  530.        ''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
  531.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  532.        ''' <returns>True if the operation success, otherwise False.</returns>
  533.        Public Shared Function Remove(ByVal KeyName As String,
  534.                                      Optional ByVal SectionName As String = Nothing,
  535.                                      Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  536.  
  537.            If Not [File].Exist() Then Return False
  538.  
  539.            [File].[Get](Encoding)
  540.  
  541.            [Key].GetIndex(KeyName, SectionName)
  542.  
  543.            Select Case KeyIndex
  544.  
  545.                Case Is <> -1 ' Key found.
  546.  
  547.                    ' Remove the element containing the key name.
  548.                    Content.RemoveAt(KeyIndex)
  549.  
  550.                    ' Save changes.
  551.                    Return [File].Write(Content, Encoding)
  552.  
  553.                Case Else ' KeyName not found.
  554.                    Return False
  555.  
  556.            End Select
  557.  
  558.        End Function
  559.  
  560.    End Class
  561.  
  562.    Public Class Section
  563.  
  564.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  565.        Private Shadows Sub ReferenceEquals()
  566.        End Sub
  567.  
  568.        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
  569.        Private Shadows Sub Equals()
  570.        End Sub
  571.  
  572.        ''' <summary>
  573.        ''' Adds a new section at bottom of the initialization file.
  574.        ''' </summary>
  575.        ''' <param name="SectionName">Indicates the Section name to add.</param>
  576.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  577.        ''' <returns>True if the operation success, otherwise False.</returns>
  578.        Public Shared Function Add(Optional ByVal SectionName As String = Nothing,
  579.                                   Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  580.  
  581.            If Not [File].Exist() Then [File].Create()
  582.  
  583.            If Not SectionName Like "[[]?*[]]" Then
  584.                Throw New SectionNameInvalidFormatException
  585.                Exit Function
  586.            End If
  587.  
  588.            [File].[Get](Encoding)
  589.  
  590.            Select Case Section.GetNames(Encoding).Where(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode)).Any
  591.  
  592.                Case False ' Any of the existing Section names is equal to given section name.
  593.  
  594.                    ' Add the new section name.
  595.                    Content.Add(SectionName)
  596.  
  597.                    ' Save changes.
  598.                    Return [File].Write(Content, Encoding)
  599.  
  600.                Case Else ' An existing Section name is equal to given section name.
  601.                    Return False
  602.  
  603.            End Select
  604.  
  605.        End Function
  606.  
  607.        ''' <summary>
  608.        ''' Returns all the keys and values of an existing Section Name.
  609.        ''' </summary>
  610.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  611.        ''' <param name="SectionName">Indicates the section name where to retrieve their keynames and values.</param>
  612.        Public Shared Function [Get](ByVal SectionName As String,
  613.                                     Optional ByVal Encoding As System.Text.Encoding = Nothing) As List(Of String)
  614.  
  615.            If Content Is Nothing Then [File].Get(Encoding)
  616.  
  617.            SectionStartIndex = Content.FindIndex(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode))
  618.  
  619.            SectionEndIndex = Content.FindIndex(SectionStartIndex + 1, Function(line) line.Trim Like "[[]?*[]]")
  620.  
  621.            If SectionEndIndex = -1 Then
  622.                SectionEndIndex = Content.Count ' This fixes the value if the section is at the end of file.
  623.            End If
  624.  
  625.            Return Content.GetRange(SectionStartIndex, SectionEndIndex - SectionStartIndex).Skip(1).ToList
  626.  
  627.        End Function
  628.  
  629.        ''' <summary>
  630.        ''' Returns all the section names of the initialization file.
  631.        ''' </summary>
  632.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  633.        Public Shared Function GetNames(Optional ByVal Encoding As System.Text.Encoding = Nothing) As String()
  634.  
  635.            If Content Is Nothing Then [File].Get(Encoding)
  636.  
  637.            ' Get the Section names.
  638.            SectionNames = (From line In Content Where line.Trim Like "[[]?*[]]").ToArray
  639.  
  640.            ' Sort the Section names.
  641.            If SectionNames.Count <> 0 Then Array.Sort(SectionNames)
  642.  
  643.            ' Return the Section names.
  644.            Return SectionNames
  645.  
  646.        End Function
  647.  
  648.        ''' <summary>
  649.        ''' Gets a value indicating whether the initialization file contains at least one Section.
  650.        ''' </summary>
  651.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  652.        ''' <returns>True if the INI contains at least one section, otherwise False.</returns>
  653.        Public Shared Function Has(Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  654.  
  655.            If Content Is Nothing Then [File].Get(Encoding)
  656.  
  657.            Return (From line In Content Where line.Trim Like "[[]?*[]]").Any()
  658.  
  659.        End Function
  660.  
  661.        ''' <summary>
  662.        ''' Removes an existing section with all of it's keys and values.
  663.        ''' </summary>
  664.        ''' <param name="SectionName">Indicates the Section name to remove with all of it's key/values.</param>
  665.        ''' <param name="Encoding">The Text encoding to read the initialization file.</param>
  666.        ''' <returns>True if the operation success, otherwise False.</returns>
  667.        Public Shared Function Remove(Optional ByVal SectionName As String = Nothing,
  668.                                      Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
  669.  
  670.            If Not [File].Exist() Then Return False
  671.  
  672.            If Not SectionName Like "[[]?*[]]" Then
  673.                Throw New SectionNameInvalidFormatException
  674.                Exit Function
  675.            End If
  676.  
  677.            [File].[Get](Encoding)
  678.  
  679.            Select Case [Section].GetNames(Encoding).Where(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode)).Any
  680.  
  681.                Case True ' An existing Section name is equal to given section name.
  682.  
  683.                    ' Get the section StartIndex and EndIndex.
  684.                    [Get](SectionName)
  685.  
  686.                    ' Remove the section range index.
  687.                    Content.RemoveRange(SectionStartIndex, SectionEndIndex - SectionStartIndex)
  688.  
  689.                    ' Save changes.
  690.                    Return [File].Write(Content, Encoding)
  691.  
  692.                Case Else ' Any of the existing Section names is equal to given section name.
  693.                    Return False
  694.  
  695.            End Select
  696.  
  697.        End Function
  698.  
  699.    End Class
  700.  
  701. #End Region
  702.  
  703. End Class
  704.  
  705. #End Region
« Última modificación: 15 Diciembre 2014, 21:35 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



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

Una función de uso genérico para delimitar un string, es decir, para tomar una porción dell texto (solo una).

Código
  1. #Region " Delimit String "
  2.  
  3.    ' [ Delimit String ]
  4.    '
  5.    ' // By Elektro H@ker
  6.    '
  7.    ' Result: my new house today
  8.    ' MsgBox(Delimit_String("Welcome to my new house today", "to"))
  9.  
  10.    ' Result: my new house
  11.    ' MsgBox(Delimit_String("Welcome to my new house today", "to", "today"))
  12.  
  13.    ' Result: my new house
  14.    ' MsgBox(Delimit_String("Welcome to my new house today", "TO", "tODaY", RegexOptions.IgnoreCase))
  15.  
  16.    ' Result: my new house
  17.    ' MsgBox(Delimit_String("Welcome to my new house today", "to", "to", RegexOptions.IgnoreCase Or RegexOptions.RightToLeft))
  18.  
  19.    ' Result: Nothing (No IgnoreCase specified.)
  20.    ' MsgBox(Delimit_String("Welcome to my new house today", "TO", "HoUSe"))
  21.  
  22.    ' Result: Nothing (Second delimiter is not found.)
  23.    ' MsgBox(Delimit_String("Welcome to my new house today", "to", "tokyo", ))
  24.  
  25.    ''' <summary>
  26.    ''' Delimit a String using Start/End delimiters.
  27.    ''' </summary>
  28.    ''' <param name="str">Indicates the String to delimit.</param>
  29.    ''' <param name="Delimiter_A">A delimiter used to indicate the end of the string.</param>
  30.    ''' <param name="Delimiter_B">An optional delimiter used to indicate the end of the string produced by the first delimiter.</param>
  31.    ''' <param name="Options">Indicates options such as IgnoreCase or to start splitting from RightToLeft.</param>
  32.    Private Function Delimit_String(ByVal str As String,
  33.                                    ByVal Delimiter_A As String,
  34.                                    Optional ByVal Delimiter_B As String = "",
  35.                                    Optional ByVal Options As RegexOptions = RegexOptions.None) As String
  36.  
  37.        Dim rgx1 As New Regex(Delimiter_A, Options)
  38.        Dim rgx2 As New Regex(Delimiter_B, Options)
  39.  
  40.        Dim m1 = rgx1.Match(str)
  41.        Select Case Options.ToString.Contains(RegexOptions.RightToLeft.ToString)
  42.            Case False ' Left To Right
  43.                str = str.Substring(m1.Index + m1.Length)
  44.            Case True ' Right To Left
  45.                str = str.Substring(0, m1.Index)
  46.        End Select
  47.  
  48.        Dim m2 = rgx2.Match(str)
  49.        If Not String.IsNullOrWhiteSpace(Delimiter_B) Then
  50.            Select Case Options.ToString.Contains(RegexOptions.RightToLeft.ToString)
  51.                Case False ' Left To Right
  52.                    str = str.Substring(0, m2.Index)
  53.                Case True ' Right To Left
  54.                    str = str.Substring(m2.Index + m2.Length)
  55.            End Select
  56.        End If
  57.  
  58.        Return str
  59.  
  60.    End Function
  61.  
  62. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #355 en: 12 Diciembre 2013, 06:54 am »

Control Iterator

Recolecta uno o varios controles y realiza una operación específica en ellos.

Le añadí decenas de overloads y métodos, el código es bien largo: http://pastebin.com/ypuQdKf0

Ejemplos de uso:
Código
  1. ControlIterator.Disable(CheckBox1)
  2.  
  3. ControlIterator.Enable({CheckBox1, CheckBox2})
  4.  
  5. ControlIterator.Check(Of CheckBox)(Me)
  6.  
  7. ControlIterator.Uncheck(Of CheckBox)(Me.GroupBox1)
  8.  
  9. ControlIterator.Hide(Of CheckBox)("1")
  10.  
  11. ControlIterator.PerformAction(Of CheckBox)(Sub(ctrl As CheckBox) ctrl.Visible = True)
  12.  
  13. ControlIterator.AsyncPerformAction(RichTextBox1,
  14.                                    Sub(rb As RichTextBox)
  15.                                        For n As Integer = 0 To 9
  16.                                            rb.AppendText(CStr(n))
  17.                                        Next
  18.                                    End Sub)
« Última modificación: 12 Diciembre 2013, 08:08 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #356 en: 13 Diciembre 2013, 15:06 pm »

Unos snippets para el control GeckoFX https://bitbucket.org/geckofx/ la cual necesita (una versión específica de) XulRunner http://ftp.mozilla.org/pub/mozilla.org/xulrunner/releases/

- Navega a una url y espera a que la página se haya cargado complétamente.

Código
  1.    ' [GeckoFX] - Navigate And Wait
  2.    '
  3.    ' // By Elektro H@cker
  4.    '
  5.    ' Usage Examples:
  6.    ' NavigateAndWait(GeckoWebBrowser1, "www.google.com") : MsgBox("Page fully loaded!")
  7.  
  8.    Private WebPageLoaded As Boolean = False
  9.  
  10.    ''' <summary>
  11.    ''' Navigates to an url and waits the page to be loaded.
  12.    ''' </summary>
  13.    ''' <param name="url">Indicates the url to navigate.</param>
  14.    Public Sub NavigateAndWait(Byval Browser as Gecko.GeckoWebBrowser,
  15.                               Byval url As String,
  16.                               Optional loadFlags As Gecko.GeckoLoadFlags = Gecko.GeckoLoadFlags.None,
  17.                               Optional referrer As String = Nothing,
  18.                               Optional postData As Gecko.GeckoMIMEInputStream = Nothing)
  19.  
  20.        Me.WebPageLoaded = False
  21.  
  22.        AddHandler Browser.DocumentCompleted, AddressOf GeckoWebBrowserDocumentCompleted
  23.        Browser.Navigate(url, loadFlags, referrer, postData)
  24.  
  25.        Do Until Me.WebPageLoaded
  26.            Application.DoEvents()
  27.        Loop
  28.  
  29.        RemoveHandler Browser.DocumentCompleted, AddressOf GeckoWebBrowserDocumentCompleted
  30.  
  31.    End Sub
  32.  
  33.    ' GeckoWebBrowser [DocumentCompleted]
  34.    Private Sub GeckoWebBrowserDocumentCompleted(ByVal sender As Object, e As EventArgs)
  35.  
  36.        Me.WebPageLoaded = True
  37.  
  38.    End Sub


- Elimina todas las cookies que haya generado el navegador

Código
  1.    ' [GeckoFX] - Remove All Cookies
  2.  
  3.    Private Sub RemoveAllCookies()
  4.        Dim CookieMan As nsICookieManager2
  5.        CookieMan = Xpcom.GetService(Of nsICookieManager2)("@mozilla.org/cookiemanager;1")
  6.        CookieMan = Xpcom.QueryInterface(Of nsICookieManager2)(CookieMan)
  7.        CookieMan.RemoveAll()
  8.    End Sub

- Establece algunas preferencias interesantes del navegador

Código
  1.    Private Sub SetNavigatorPreferences()
  2.  
  3.        ' Pipelining reduces network load and can reduce page loading times over high-latency connections,
  4.        ' but not all servers support it.
  5.        ' Some servers may even behave incorrectly if they receive pipelined requests.
  6.        ' If a proxy server is not configured, this preference controls whether to attempt to use pipelining.
  7.        ' Value = Attempt to use pipelining in HTTP 1.1 connections or not.
  8.        Gecko.GeckoPreferences.Default("network.http.pipelining") = True
  9.  
  10.        ' Many problems with pipelining are related to broken proxy servers sitting between the user and the destination web site.
  11.        ' Since this is not a problem with SSL, it is possible to turn on pipelining for SSL websites only.
  12.        ' This preference controls whether to use pipelining for secure websites, regardless of network.http.pipelining.
  13.        ' Value = Use HTTP pipelining for secure websites or not.
  14.        Gecko.GeckoPreferences.Default("network.http.pipelining.ssl") = True
  15.  
  16.        ' Value = The maximum number of requests to pipeline at once when pipelining is enabled.
  17.        Gecko.GeckoPreferences.Default("network.http.pipelining.maxrequests") = 10
  18.  
  19.        ' Value = Total number of HTTP connections the application can make to a single server.
  20.        Gecko.GeckoPreferences.Default("network.http.max-connections-per-server") = 20
  21.  
  22.        ' HTTP keep-alive connections can be re-used for multiple requests,
  23.        ' as opposed to non-keep-alive connections, which are limited to one request.
  24.        ' Using keep-alive connections improves performance.
  25.        ' Value = The maximum number of HTTP keep-alive connections the application can have open at once to a single server. (Default: 2)
  26.        Gecko.GeckoPreferences.Default("network.http.max-persistent-connections-per-server") = 5
  27.  
  28.        ' Display what's been received of a page before the entire page has been downloaded.
  29.        ' Value = The number of milliseconds to wait before first displaying the page. (Default: 250)
  30.        Gecko.GeckoPreferences.Default("nglayout.initialpaint.delay") = 0
  31.  
  32.        ' Value = Attempt to use pipelining in HTTP 1.1 connections to the proxy server or not.
  33.        Gecko.GeckoPreferences.Default("network.http.proxy.pipelining") = True
  34.  
  35.        ' Rather than wait until a page has completely downloaded to display it to the user,
  36.        ' Mozilla applications will periodically render what has been received to that point.
  37.        ' Because reflowing the page every time additional data is received greatly slows down total page load time,
  38.        ' a timer was added so that the page would not reflow too often.
  39.        ' Value = The maximum number of times the content will do timer-based reflows.
  40.        ' After this number has been reached, the page will only reflow once it is finished downloading.
  41.        Gecko.GeckoPreferences.Default("content.notify.backoffcount") = 5
  42.  
  43.        ' Value = Displays the full path of a installed plugin file or not.
  44.        Gecko.GeckoPreferences.Default("plugin.expose_full_path") = True
  45.  
  46.        ' Value = The delay in milliseconds between hovering over a menu option with a submenu and the submenu appearing.
  47.        Gecko.GeckoPreferences.Default("ui.submenuDelay") = 0
  48.  
  49.        ' Pages that were recently visited are stored in memory in such a way that they don't have to be re-parsed (this is different from the memory cache).
  50.        ' This improves performance when pressing Back and Forward.
  51.        ' Value = The maximum number of pages stored in memory.
  52.        Gecko.GeckoPreferences.Default("Browser.sessionhistory.max_total_viewers") = 5
  53.  
  54.        ' Value = The maximum number of pages in the browser's session history,
  55.        ' the maximum number of URLs you can traverse purely through the Back/Forward buttons. Default value is 50.
  56.        Gecko.GeckoPreferences.Default("Browser.sessionhistory.max_entries") = 60
  57.  
  58.        ' When a program is minimized and left for a period of time,
  59.        ' Windows will swap memory the program is using from RAM onto the hard disk in anticipation that other programs might need RAM.
  60.        ' Value = Determines whether to mark memory as preferably swappable, from a minimized Mozilla Windows application.
  61.        Gecko.GeckoPreferences.Default("config.trim_on_minimize") = True
  62.  
  63.        ' Mozilla applications will periodically retrieve a blocklist from the server specified in extensions.blocklist.url.
  64.        ' While Mozilla 's add-on system is a powerful feature, it can also be a vector for malware.
  65.        ' Specific extensions can be blocklisted from a central server (by default, addons.mozilla.org).
  66.        ' Value = Determines wheter to retrieve a blocklist to restrict extension installation.
  67.        Gecko.GeckoPreferences.Default("extensions.blocklist.enabled") = False
  68.  
  69.    End Sub
« Última modificación: 13 Diciembre 2013, 15:42 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #357 en: 14 Diciembre 2013, 18:02 pm »

Para comprobar si la conectividad a una web está disponible y mostrar un mensaje de Status en un control...

Ejemplo de uso:

Código
  1.    Private Sub Test()
  2.  
  3.        MsgBox(Is_Connectivity_Avaliable("Google.com"))
  4.  
  5.        Dim t As New Threading.Thread(AddressOf CheckConnectivity)
  6.        t.Start()
  7.  
  8.    End Sub
  9.  
  10.    Private Sub CheckConnectivity()
  11.        Do Until Is_Connectivity_Avaliable("qwertyqwertyqwerty.com", 10, Label1)
  12.            Application.DoEvents()
  13.        Loop
  14.    End Sub

Código
  1.    Private Function Is_Connectivity_Avaliable(ByVal url As String,
  2.                                               Optional ByVal RetryInterval As Integer = -1,
  3.                                               Optional ByVal StatusControl As Control = Nothing) As Boolean
  4.  
  5.        Dim NoNetworkMessage As String = "Network connection is not avaliable."
  6.        Dim NoWebsiteMessage As String = "WebSite is not avaliable."
  7.        Dim NoNetworkRetryMessage As String = "Network connection is not avaliable, retrying in {0} seconds..."
  8.        Dim NoWebsiteRetryMessage As String = "WebSite is not avaliable, retrying in {0} seconds..."
  9.        Dim YesNetworkMessage As String = "Network connection established."
  10.        Dim YesWebsiteMessage As String = "WebSite connection established."
  11.  
  12.        Select Case My.Computer.Network.IsAvailable
  13.  
  14.            Case False ' No network device avaliable
  15.  
  16.                If RetryInterval = -1 Then ' Do not retry
  17.                    NetworkAvaliable(NoNetworkMessage, False, StatusControl)
  18.                    Return False
  19.  
  20.                Else ' Retry
  21.  
  22.                    For X As Integer = 0 To RetryInterval
  23.                        NetworkAvaliable(String.Format(NoNetworkRetryMessage, RetryInterval - X), True, StatusControl)
  24.                    Next X
  25.  
  26.                    Is_Connectivity_Avaliable(url, RetryInterval, StatusControl)
  27.  
  28.                End If ' RetryInterval
  29.  
  30.            Case True ' Network device is avaliable
  31.  
  32.                ' Inform that network device is avaliable.
  33.                NetworkAvaliable(YesNetworkMessage, False, StatusControl)
  34.  
  35.                Try ' Try connect to the given url
  36.                    My.Computer.Network.Ping(url)
  37.  
  38.                    ' Inform that Website connection is avaliable.
  39.                    NetworkAvaliable(YesWebsiteMessage, False, StatusControl)
  40.                    Return True
  41.  
  42.                Catch ex As Net.NetworkInformation.PingException
  43.  
  44.                    If RetryInterval = -1 Then ' Do not retry
  45.                        NetworkAvaliable(NoWebsiteMessage, False, StatusControl)
  46.                        Return False
  47.  
  48.                    Else ' Retry
  49.  
  50.                        For X As Integer = 0 To RetryInterval
  51.                            NetworkAvaliable(String.Format(NoWebsiteRetryMessage, RetryInterval - X), True, StatusControl)
  52.                        Next X
  53.  
  54.                        Is_Connectivity_Avaliable(url, RetryInterval, StatusControl)
  55.  
  56.                    End If ' RetryInterval
  57.  
  58.                Catch ex As InvalidOperationException
  59.  
  60.                    If RetryInterval = -1 Then ' Do not retry
  61.                        NetworkAvaliable(NoNetworkMessage, False, StatusControl)
  62.                        Return False
  63.  
  64.                    Else ' Retry
  65.  
  66.                        For X As Integer = 0 To RetryInterval
  67.                            NetworkAvaliable(String.Format(NoNetworkRetryMessage, RetryInterval - X), True, StatusControl)
  68.                        Next
  69.  
  70.                        Is_Connectivity_Avaliable(url, RetryInterval, StatusControl)
  71.  
  72.                    End If ' RetryInterval
  73.  
  74.                End Try
  75.  
  76.        End Select
  77.  
  78.    End Function
  79.  
  80.    Private Sub NetworkAvaliable(ByVal Message As String,
  81.                                 ByVal Wait As Boolean,
  82.                                 Optional ByVal StatusControl As Control = Nothing)
  83.  
  84.        If Wait Then Threading.Thread.Sleep(1000)
  85.  
  86.        If StatusControl IsNot Nothing Then
  87.            StatusControl.Invoke(Sub() StatusControl.Text = Message)
  88.        Else
  89.            Debug.WriteLine(Message)
  90.        End If
  91.  
  92.    End Sub



Un snippet para colorear los elementos de un Listbox, esto lo posteé hace tiempo pero lo he extendido...

Código
  1. #Region " [ListBox] Colorize Items "
  2.  
  3. ' [ [ListBox] Colorize Items ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions:
  8. ' 1. Set ListBox "Drawmode" property to "OwnerDrawFixed" to make this work.
  9. '    ListBox1.DrawMode = DrawMode.OwnerDrawFixed
  10. '
  11. ' Examples :
  12. '
  13. ' Colorize only selected item:
  14. ' Colorize_Item(ListBox1, Colorize_ListBox_Items.Selected, Brushes.YellowGreen, Brushes.Black)
  15. '
  16. ' Colorize all Non-Selected items
  17. ' Colorize_Item(ListBox1, Colorize_ListBox_Items.Non_Selected, Brushes.Red, Brushes.YellowGreen)
  18. '
  19. ' Colorize all items:
  20. ' Colorize_Item(ListBox1, Colorize_ListBox_Items.All, Brushes.Yellow, Brushes.Yellow)
  21. '
  22. ' Colorize any item:
  23. ' Colorize_Item(ListBox1, Colorize_ListBox_Items.None, Nothing, Nothing)
  24. '
  25. ' Colorize specific items:
  26. ' Colorize_Item(ListBox1, {0, (ListBox1.Items.Count \ 2), (ListBox1.Items.Count - 1)}, Brushes.HotPink, Nothing)
  27.  
  28.  
  29.    ' Stores the brush colors to paint their items
  30.    Private ListBox_BackColor As Brush = Brushes.YellowGreen
  31.    Private ListBox_ForeColor As Brush = Brushes.Black
  32.  
  33.    Private Enum ListBoxItems As Short
  34.        Selected = 0
  35.        Non_Selected = 1
  36.        All = 2
  37.        None = 3
  38.    End Enum
  39.  
  40.    ''' <summary>
  41.    ''' Colorizes the items of a ListBox.
  42.    ''' </summary>
  43.    ''' <param name="ListBox">Indicates the ListBox control.</param>
  44.    ''' <param name="Colorize">Indicates the items to colorize them.</param>
  45.    ''' <param name="BackColor">Indicates the backcolor for the colorized items.</param>
  46.    ''' <param name="Forecolor">Indicates the forecolor for the colorized items.</param>
  47.    Private Sub Colorize_Item(ByVal ListBox As ListBox, _
  48.                              ByVal Colorize As ListBoxItems, _
  49.                              ByVal BackColor As Brush,
  50.                              ByVal Forecolor As Brush)
  51.  
  52.        ' Stores the Enum value
  53.        ListBox.Tag = Colorize.ToString
  54.  
  55.        ListBox_BackColor = BackColor
  56.        ListBox_ForeColor = Forecolor
  57.  
  58.    End Sub
  59.  
  60.    ''' <summary>
  61.    ''' Colorizes the items of a ListBox.
  62.    ''' </summary>
  63.    ''' <param name="ListBox">Indicates the ListBox control.</param>
  64.    ''' <param name="Colorize">Indicates the items to colorize them.</param>
  65.    ''' <param name="BackColor">Indicates the backcolor for the colorized items.</param>
  66.    ''' <param name="Forecolor">Indicates the forecolor for the colorized items.</param>
  67.    Private Sub Colorize_Item(ByVal ListBox As ListBox,
  68.                              ByVal Colorize As Integer(),
  69.                              ByVal BackColor As Brush,
  70.                              ByVal Forecolor As Brush)
  71.  
  72.        ' Stores the index items
  73.        ListBox.Tag = String.Join(Convert.ToChar(Keys.Space), Colorize)
  74.  
  75.        ListBox_BackColor = BackColor
  76.        ListBox_ForeColor = Forecolor
  77.  
  78.    End Sub
  79.  
  80.    ' ListBox [DrawItem]
  81.    Private Sub ListBox_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) _
  82.    Handles ListBox_Genres.DrawItem
  83.  
  84.        e.DrawBackground()
  85.  
  86.        Select Case sender.tag
  87.  
  88.            Case ListBoxItems.Selected.ToString ' Colorize Selected Items
  89.  
  90.                If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
  91.                    e.Graphics.FillRectangle(ListBox_BackColor, e.Bounds)
  92.                    e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, ListBox_ForeColor, e.Bounds)
  93.                Else
  94.                    Using b As New SolidBrush(e.ForeColor)
  95.                        e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, b, e.Bounds)
  96.                    End Using
  97.                End If
  98.  
  99.            Case ListBoxItems.Non_Selected.ToString ' Colorize Non-Selected Items
  100.  
  101.                If (e.State And DrawItemState.Selected) = DrawItemState.None Then
  102.                    e.Graphics.FillRectangle(ListBox_BackColor, e.Bounds)
  103.                    e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, ListBox_ForeColor, e.Bounds)
  104.                Else
  105.                    Using b As New SolidBrush(e.ForeColor)
  106.                        e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, b, e.Bounds)
  107.                    End Using
  108.                End If
  109.  
  110.            Case ListBoxItems.All.ToString ' Colorize all
  111.  
  112.                e.Graphics.FillRectangle(ListBox_BackColor, e.Bounds)
  113.                e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, ListBox_ForeColor, e.Bounds)
  114.  
  115.            Case ListBoxItems.None.ToString ' Colorize none
  116.  
  117.                Using b As New SolidBrush(ListBox.DefaultBackColor)
  118.                    e.Graphics.FillRectangle(b, e.Bounds)
  119.                End Using
  120.  
  121.                Using b As New SolidBrush(ListBox.DefaultForeColor)
  122.                    e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, b, e.Bounds)
  123.                End Using
  124.  
  125.            Case Else ' Colorize at specific index
  126.  
  127.                If Not String.IsNullOrEmpty(sender.tag) _
  128.                AndAlso sender.tag.ToString.Split.Contains(CStr(e.Index)) Then
  129.  
  130.                    e.Graphics.FillRectangle(ListBox_BackColor, e.Bounds)
  131.                    e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, ListBox_ForeColor, e.Bounds)
  132.  
  133.                Else
  134.  
  135.                    Using b As New SolidBrush(e.ForeColor)
  136.                        e.Graphics.DrawString(sender.GetItemText(sender.Items(e.Index)), e.Font, b, e.Bounds)
  137.                    End Using
  138.  
  139.                End If
  140.  
  141.        End Select
  142.  
  143.        e.DrawFocusRectangle()
  144.  
  145.    End Sub
  146.  
  147. #End Region



Otro snippet que he extendido, para ordenar los los items de un ListView:

Código
  1.    ''' <summary>
  2.    ''' Sorts the column content of a ListView.
  3.    ''' </summary>
  4.    ''' <param name="LV">Indicates the ListView to sort.</param>
  5.    ''' <param name="Column">Indicates the columnd to index.</param>
  6.    ''' <param name="Order">Indicates the sort order.</param>
  7.    Private Sub SortListView(ByVal LV As ListView,
  8.                             ByVal Column As Integer,
  9.                             ByVal Order As SortOrder)
  10.  
  11.        LV.ListViewItemSorter = New ListViewSorter(Column, Order)
  12.        LV.Sort()
  13.  
  14.    End Sub
  15.  
  16.    ' ListView [ColumnClick]
  17.    Private Sub ListView_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs) _
  18.    Handles ListView1.ColumnClick
  19.  
  20.        If String.IsNullOrEmpty(sender.Columns.Item(0).Tag) Then
  21.            sender.Columns.Item(0).Tag = SortOrder.Ascending.ToString
  22.        Else
  23.            sender.Columns.Item(0).Tag =
  24.                [Enum].GetValues(GetType(SortOrder)).
  25.                Cast(Of Integer).
  26.                Where(Function(n) n <> [Enum].Parse(GetType(SortOrder), sender.Columns.Item(0).Tag)).
  27.                First()
  28.        End If
  29.  
  30.        SortListView(sender, e.Column, [Enum].Parse(GetType(SortOrder), sender.Columns.Item(0).Tag))
  31.  
  32.    End Sub
  33.  
  34. #Region " ListViewSorter "
  35.  
  36.    Public Class ListViewSorter : Implements IComparer
  37.  
  38.        Private ColumnIndex As Integer
  39.        Private SortOrder As SortOrder
  40.  
  41.        Public Sub New(ByVal ColumnIndex As Integer,
  42.                       ByVal SortOrder As SortOrder)
  43.  
  44.            Me.ColumnIndex = ColumnIndex
  45.            Me.SortOrder = SortOrder
  46.  
  47.        End Sub
  48.  
  49.        Public Function Sort(ByVal x As Object,
  50.                             ByVal y As Object) As Integer _
  51.        Implements IComparer.Compare
  52.  
  53.            Dim item_x As ListViewItem = DirectCast(x, ListViewItem)
  54.            Dim item_y As ListViewItem = DirectCast(y, ListViewItem)
  55.            Dim string_x As String
  56.            Dim string_y As String
  57.  
  58.            string_x = If(Not item_x.SubItems.Count <= ColumnIndex,
  59.                          item_x.SubItems(ColumnIndex).Text,
  60.                          "")
  61.  
  62.            string_y = If(Not item_y.SubItems.Count <= ColumnIndex,
  63.                          item_y.SubItems(ColumnIndex).Text,
  64.                          "")
  65.  
  66.            Select Case SortOrder
  67.  
  68.                Case SortOrder.Ascending
  69.  
  70.                    If Double.TryParse(string_x, New Double) AndAlso Double.TryParse(string_y, New Double) Then
  71.                        Return Double.Parse(string_x).CompareTo(Double.Parse(string_y))
  72.  
  73.                    ElseIf Date.TryParse(string_x, New Date) AndAlso Date.TryParse(string_y, New Date) Then
  74.                        Return DateTime.Parse(string_x).CompareTo(DateTime.Parse(string_y))
  75.  
  76.                    Else
  77.                        Return String.Compare(string_x, string_y, False)
  78.  
  79.                    End If
  80.  
  81.                Case Else
  82.  
  83.                    If Double.TryParse(string_x, New Double) AndAlso Double.TryParse(string_y, New Double) Then
  84.                        Return Double.Parse(string_y).CompareTo(Double.Parse(string_x))
  85.  
  86.                    ElseIf Date.TryParse(string_x, New Date) AndAlso Date.TryParse(string_y, New Date) Then
  87.                        Return DateTime.Parse(string_y).CompareTo(DateTime.Parse(string_x))
  88.  
  89.                    Else
  90.                        Return String.Compare(string_y, string_x, False)
  91.  
  92.                    End If
  93.  
  94.            End Select
  95.  
  96.        End Function
  97.  
  98.    End Class
  99.  
  100. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #358 en: 15 Diciembre 2013, 18:10 pm »

Elektro Listbox, un ListBox User Control para WindowsForms.

Características:

· Estado ReadOnly, al activarse no se podrá seleccionar ningún item, pero a diferencia del estado Disabled se podrá seguir usando la scrollbar.
· Propiedades para especificar un color para los items seleccionados/deseleccionados en diferentes estados (Enabled / Disabled / ReadOnly)
· Método para seleccionar múltiples items sin saltar a la posición del item como sucede con el ListBox por defecto.
· Método para comprobar si existen duplicados en los items.
· Método para eliminar los items duplicados.
· Método para Seleccionar/Deseleccionar todos los items de una vez.

Una imagen:



Que lo disfruteis.

EDITO: Código extendido y mejorado.

Código
  1. '  /*                   *\
  2. ' |#*  Elektro ListBox  *#|
  3. '  \*  ***************  */
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' -----------
  8. ' Properties:
  9. ' -----------
  10. '
  11. ' ReadOnly
  12. ' ReadOnly_Enabled_Cursor
  13. ' ReadOnly_Disabled_Cursor
  14. ' State_Enabled_ItemSelected_BackColor
  15. ' State_Enabled_ItemSelected_ForeColor
  16. ' State_Enabled_ItemUnselected_BackColor
  17. ' State_Enabled_ItemUnselected_ForeColor
  18. ' State_Disabled_ItemSelected_BackColor
  19. ' State_Disabled_ItemSelected_ForeColor
  20. ' State_Disabled_ItemUnselected_BackColor
  21. ' State_Disabled_ItemUnselected_ForeColor
  22. ' State_ReadOnly_ItemSelected_BackColor
  23. ' State_ReadOnly_ItemSelected_ForeColor
  24. ' State_ReadOnly_ItemUnselected_BackColor
  25. ' State_ReadOnly_ItemUnselected_ForeColor
  26. '
  27. ' --------
  28. ' Methods:
  29. ' --------
  30. '
  31. ' HasDuplicatedItems
  32. ' RemoveDuplicatedItems
  33. ' SetSelected_WithoutJump
  34. ' MoveItem
  35. '
  36. ' -------
  37. ' Events:
  38. ' -------
  39. '
  40. ' ReadOnlyChanged
  41.  
  42. Public Class ElektroListBox : Inherits ListBox
  43.  
  44. #Region " Members "
  45.  
  46. #Region " Variables "
  47.  
  48.    ''' <summary>
  49.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is enabled.
  50.    ''' </summary>
  51.    Private _State_Enabled_ItemSelected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  52.  
  53.    ''' <summary>
  54.    ''' Indicates the ForeColor to paint the selected ListBox items when the ListBox is enabled.
  55.    ''' </summary>
  56.    Private _State_Enabled_ItemSelected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  57.  
  58.    ''' <summary>
  59.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is enabled.
  60.    ''' </summary>
  61.    Private _State_Enabled_ItemUnselected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  62.  
  63.    ''' <summary>
  64.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is enabled.
  65.    ''' </summary>
  66.    Private _State_Enabled_ItemUnselected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  67.  
  68.    ''' <summary>
  69.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is disabled.
  70.    ''' </summary>
  71.    Private _State_Disabled_ItemSelected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  72.  
  73.    ''' <summary>
  74.    ''' Indicates the Forecolor to paint the selected ListBox items when the ListBox is disabled.
  75.    ''' </summary>
  76.    Private _State_Disabled_ItemSelected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  77.  
  78.    ''' <summary>
  79.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is disabled.
  80.    ''' </summary>
  81.    Private _State_Disabled_ItemUnselected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  82.  
  83.    ''' <summary>
  84.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is disabled.
  85.    ''' </summary>
  86.    Private _State_Disabled_ItemUnselected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  87.  
  88.    ''' <summary>
  89.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is ReadOnly.
  90.    ''' </summary>
  91.    Private _State_ReadOnly_ItemSelected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  92.  
  93.    ''' <summary>
  94.    ''' Indicates the Forecolor to paint the selected ListBox items when the ListBox is ReadOnly.
  95.    ''' </summary>
  96.    Private _State_ReadOnly_ItemSelected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  97.  
  98.    ''' <summary>
  99.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is ReadOnly.
  100.    ''' </summary>
  101.    Private _State_ReadOnly_ItemUnselected_BackColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
  102.  
  103.    ''' <summary>
  104.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is ReadOnly.
  105.    ''' </summary>
  106.    Private _State_ReadOnly_ItemUnselected_ForeColor As SolidBrush = New SolidBrush(ListBox.DefaultForeColor)
  107.  
  108.    ''' <summary>
  109.    ''' Stores a value indicating whether the Listbox is in ReadOnly mode.
  110.    ''' </summary>
  111.    Private _ReadOnly As Boolean = False
  112.  
  113.    ''' <summary>
  114.    ''' Stores the Cursor to use when the ListBox enters to ReadOnly mode.
  115.    ''' </summary>
  116.    Private _ReadOnly_Enabled_Cursor As Cursor = Cursors.No
  117.  
  118.    ''' <summary>
  119.    ''' Stores the Cursor to use when the ListBox exits from ReadOnly mode.
  120.    ''' </summary>
  121.    Private _ReadOnly_Disabled_Cursor As Cursor = Cursors.Default
  122.  
  123. #End Region
  124.  
  125. #Region " Properties "
  126.  
  127.    ''' <summary>
  128.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is enabled.
  129.    ''' </summary>
  130.    Public Property State_Enabled_ItemSelected_BackColor As Color
  131.        Get
  132.            Return _State_Enabled_ItemSelected_BackColor.Color
  133.        End Get
  134.        Set(value As Color)
  135.            If Not _State_Enabled_ItemSelected_BackColor.Color = value Then
  136.                _State_Enabled_ItemSelected_BackColor = New SolidBrush(value)
  137.                Me.Invalidate(False)
  138.            End If
  139.        End Set
  140.    End Property
  141.  
  142.    ''' <summary>
  143.    ''' Indicates the ForeColor to paint the selected ListBox items when the ListBox is enabled.
  144.    ''' </summary>
  145.    Public Property State_Enabled_ItemSelected_ForeColor As Color
  146.        Get
  147.            Return _State_Enabled_ItemSelected_ForeColor.Color
  148.        End Get
  149.        Set(value As Color)
  150.            If Not _State_Enabled_ItemSelected_ForeColor.Color = value Then
  151.                _State_Enabled_ItemSelected_ForeColor = New SolidBrush(value)
  152.                Me.Invalidate(False)
  153.            End If
  154.        End Set
  155.    End Property
  156.  
  157.    ''' <summary>
  158.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is enabled.
  159.    ''' </summary>
  160.    Public Property State_Enabled_ItemUnselected_BackColor As Color
  161.        Get
  162.            Return _State_Enabled_ItemUnselected_BackColor.Color
  163.        End Get
  164.        Set(value As Color)
  165.            If Not _State_Enabled_ItemUnselected_BackColor.Color = value Then
  166.                _State_Enabled_ItemUnselected_BackColor = New SolidBrush(value)
  167.                Me.Invalidate(False)
  168.            End If
  169.        End Set
  170.    End Property
  171.  
  172.    ''' <summary>
  173.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is enabled.
  174.    ''' </summary>
  175.    Public Property State_Enabled_ItemUnselected_ForeColor As Color
  176.        Get
  177.            Return _State_Enabled_ItemUnselected_ForeColor.Color
  178.        End Get
  179.        Set(value As Color)
  180.            If Not _State_Enabled_ItemUnselected_ForeColor.Color = value Then
  181.                _State_Enabled_ItemUnselected_ForeColor = New SolidBrush(value)
  182.                Me.Invalidate(False)
  183.            End If
  184.        End Set
  185.    End Property
  186.  
  187.    ''' <summary>
  188.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is disabled.
  189.    ''' </summary>
  190.    Public Property State_Disabled_ItemSelected_BackColor As Color
  191.        Get
  192.            Return _State_Disabled_ItemSelected_BackColor.Color
  193.        End Get
  194.        Set(value As Color)
  195.            If Not _State_Disabled_ItemSelected_BackColor.Color = value Then
  196.                _State_Disabled_ItemSelected_BackColor = New SolidBrush(value)
  197.                Me.Invalidate(False)
  198.            End If
  199.        End Set
  200.    End Property
  201.  
  202.    ''' <summary>
  203.    ''' Indicates the Forecolor to paint the selected ListBox items when the ListBox is disabled.
  204.    ''' </summary>
  205.    Public Property State_Disabled_ItemSelected_ForeColor As Color
  206.        Get
  207.            Return _State_Disabled_ItemSelected_ForeColor.Color
  208.        End Get
  209.        Set(value As Color)
  210.            If Not _State_Disabled_ItemSelected_ForeColor.Color = value Then
  211.                _State_Disabled_ItemSelected_ForeColor = New SolidBrush(value)
  212.                Me.Invalidate(False)
  213.            End If
  214.        End Set
  215.    End Property
  216.  
  217.    ''' <summary>
  218.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is disabled.
  219.    ''' </summary>
  220.    Public Property State_Disabled_ItemUnselected_BackColor As Color
  221.        Get
  222.            Return _State_Disabled_ItemUnselected_BackColor.Color
  223.        End Get
  224.        Set(value As Color)
  225.            If Not _State_Disabled_ItemUnselected_BackColor.Color = value Then
  226.                _State_Disabled_ItemUnselected_BackColor = New SolidBrush(value)
  227.                Me.Invalidate(False)
  228.            End If
  229.        End Set
  230.    End Property
  231.  
  232.    ''' <summary>
  233.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is disabled.
  234.    ''' </summary>
  235.    Public Property State_Disabled_ItemUnselected_ForeColor As Color
  236.        Get
  237.            Return _State_Disabled_ItemUnselected_ForeColor.Color
  238.        End Get
  239.        Set(value As Color)
  240.            If Not _State_Disabled_ItemUnselected_ForeColor.Color = value Then
  241.                _State_Disabled_ItemUnselected_ForeColor = New SolidBrush(value)
  242.                Me.Invalidate(False)
  243.            End If
  244.        End Set
  245.    End Property
  246.  
  247.    ''' <summary>
  248.    ''' Indicates the BackColor to paint the selected ListBox items when the ListBox is ReadOnly.
  249.    ''' </summary>
  250.    Public Property State_ReadOnly_ItemSelected_BackColor As Color
  251.        Get
  252.            Return _State_ReadOnly_ItemSelected_BackColor.Color
  253.        End Get
  254.        Set(value As Color)
  255.            If Not _State_ReadOnly_ItemSelected_BackColor.Color = value Then
  256.                _State_ReadOnly_ItemSelected_BackColor = New SolidBrush(value)
  257.                Me.Invalidate(False)
  258.            End If
  259.        End Set
  260.    End Property
  261.  
  262.    ''' <summary>
  263.    ''' Indicates the Forecolor to paint the selected ListBox items when the ListBox is ReadOnly.
  264.    ''' </summary>
  265.    Public Property State_ReadOnly_ItemSelected_ForeColor As Color
  266.        Get
  267.            Return _State_ReadOnly_ItemSelected_ForeColor.Color
  268.        End Get
  269.        Set(value As Color)
  270.            If Not _State_ReadOnly_ItemSelected_ForeColor.Color = value Then
  271.                _State_ReadOnly_ItemSelected_ForeColor = New SolidBrush(value)
  272.                Me.Invalidate(False)
  273.            End If
  274.        End Set
  275.    End Property
  276.  
  277.    ''' <summary>
  278.    ''' Indicates the BackColor to paint the unselected ListBox items when the ListBox is ReadOnly.
  279.    ''' </summary>
  280.    Public Property State_ReadOnly_ItemUnselected_BackColor As Color
  281.        Get
  282.            Return _State_ReadOnly_ItemUnselected_BackColor.Color
  283.        End Get
  284.        Set(value As Color)
  285.            If Not _State_ReadOnly_ItemUnselected_BackColor.Color = value Then
  286.                _State_ReadOnly_ItemUnselected_BackColor = New SolidBrush(value)
  287.                Me.Invalidate(False)
  288.            End If
  289.        End Set
  290.    End Property
  291.  
  292.    ''' <summary>
  293.    ''' Indicates the Forecolor to paint the unselected ListBox items when the ListBox is ReadOnly.
  294.    ''' </summary>
  295.    Public Property State_ReadOnly_ItemUnselected_ForeColor As Color
  296.        Get
  297.            Return _State_ReadOnly_ItemUnselected_ForeColor.Color
  298.        End Get
  299.        Set(value As Color)
  300.            If Not _State_ReadOnly_ItemUnselected_ForeColor.Color = value Then
  301.                _State_ReadOnly_ItemUnselected_ForeColor = New SolidBrush(value)
  302.                Me.Invalidate(False)
  303.            End If
  304.        End Set
  305.    End Property
  306.  
  307.    ''' <summary>
  308.    ''' Gets or sets a value indicating whether the Listbox is in ReadOnly mode.
  309.    ''' </summary>
  310.    Public Property [ReadOnly]() As Boolean
  311.        Get
  312.            Return _ReadOnly
  313.        End Get
  314.        Set(value As Boolean)
  315.            If Not _ReadOnly = value Then
  316.                _ReadOnly = value
  317.                RaiseEvent ReadOnlyChanged(Me, New ReadOnlyChangedEventArgs With
  318.                                               {.IsReadOnly = value})
  319.            End If
  320.        End Set
  321.    End Property
  322.  
  323.    ''' <summary>
  324.    ''' Gets or sets the Cursor to use when the ListBox enters in ReadOnly mode.
  325.    ''' </summary>
  326.    Public Property ReadOnly_Enabled_Cursor As Cursor
  327.        Get
  328.            Return _ReadOnly_Enabled_Cursor
  329.        End Get
  330.        Set(value As Cursor)
  331.            If Not _ReadOnly_Enabled_Cursor = value Then
  332.                _ReadOnly_Enabled_Cursor = value
  333.                DesignTimeInvalidator(False)
  334.            End If
  335.        End Set
  336.    End Property
  337.  
  338.    ''' <summary>
  339.    ''' Gets or sets the Cursor to use when the ListBox exits from ReadOnly mode.
  340.    ''' </summary>
  341.    Public Property ReadOnly_Disabled_Cursor As Cursor
  342.        Get
  343.            Return _ReadOnly_Disabled_Cursor
  344.        End Get
  345.        Set(value As Cursor)
  346.            If Not _ReadOnly_Disabled_Cursor = value Then
  347.                _ReadOnly_Disabled_Cursor = value
  348.                DesignTimeInvalidator(False)
  349.            End If
  350.        End Set
  351.    End Property
  352.  
  353. #End Region
  354.  
  355. #Region " Enumerations "
  356.  
  357.    ''' <summary>
  358.    ''' Indicates the state of a Listbox Item.
  359.    ''' </summary>
  360.    Public Enum ItemState
  361.  
  362.        ''' <summary>
  363.        ''' Select the listbox Item.
  364.        ''' </summary>
  365.        Selected = 0
  366.  
  367.        ''' <summary>
  368.        ''' Unselect the listbox Item.
  369.        ''' </summary>
  370.        Unselected = 1
  371.  
  372.    End Enum
  373.  
  374.    ''' <summary>
  375.    ''' Indicates the items to select.
  376.    ''' </summary>
  377.    Public Enum ListBoxItems As Short
  378.  
  379.        ''' <summary>
  380.        ''' Select all items of the ListBox.
  381.        ''' </summary>
  382.        All = 1
  383.  
  384.        ''' <summary>
  385.        ''' Select any ListBox items.
  386.        ''' </summary>
  387.        None = 2
  388.  
  389.    End Enum
  390.  
  391.    ''' <summary>
  392.    ''' Indicates some Known Windows Message Identifiers to manage.
  393.    ''' </summary>
  394.    Private Enum KnownMessages As Integer
  395.        WM_LBUTTONDOWN = &H201
  396.        WM_KEYDOWN = &H100
  397.    End Enum
  398.  
  399. #End Region
  400.  
  401. #Region " Events "
  402.  
  403.    ''' <summary>
  404.    ''' Event raised when the ReadOnly state of the ListBox changes.
  405.    ''' </summary>
  406.    Private Event ReadOnlyChanged As EventHandler(Of ReadOnlyChangedEventArgs)
  407.    Private Class ReadOnlyChangedEventArgs : Inherits EventArgs
  408.        Public Property IsReadOnly As Boolean
  409.    End Class
  410.  
  411. #End Region
  412.  
  413. #End Region
  414.  
  415. #Region " Constructor "
  416.  
  417.    Public Sub New()
  418.        Me.DoubleBuffered = True
  419.        Me.DrawMode = DrawMode.OwnerDrawFixed
  420.    End Sub
  421.  
  422. #End Region
  423.  
  424. #Region " Public Methods "
  425.  
  426.    ''' <summary>
  427.    ''' Returns a value indicating whether the ListBox items contains duplicates.
  428.    ''' </summary>
  429.    Public Function HasDuplicatedItems() As Boolean
  430.        Return Me.Items.Count - Me.Items.Cast(Of String).Distinct().Count
  431.    End Function
  432.  
  433.    ''' <summary>
  434.    ''' Remove all duplicated items in ListBox.
  435.    ''' </summary>
  436.    Public Sub RemoveDuplicatedItems()
  437.  
  438.        If HasDuplicatedItems() Then
  439.            Dim ItemArray As IEnumerable(Of String) = Me.Items.Cast(Of String).Distinct()
  440.            Me.Items.Clear()
  441.            Me.Items.AddRange(ItemArray.ToArray)
  442.        End If
  443.  
  444.    End Sub
  445.  
  446.    ''' <summary>
  447.    ''' Selects or unselects a ListBox Item without jumping to the Item position.
  448.    ''' </summary>
  449.    ''' <param name="ItemIndex">Indicates the index of the Item to set.</param>
  450.    ''' <param name="ItemState">Indicates the state for the item.</param>
  451.    Public Sub SetSelected_WithoutJump(ItemIndex As Integer, ItemState As ItemState)
  452.  
  453.        Dim i As Integer = Me.TopIndex ' Store the selected item index.
  454.        Me.BeginUpdate() ' Disable drawing on control.
  455.        Me.SetSelected(ItemIndex, ItemState) ' Select the item.
  456.        Me.TopIndex = i ' Jump to the previous selected item.
  457.        Me.EndUpdate() ' Eenable drawing.
  458.  
  459.    End Sub
  460.  
  461.    ''' <summary>
  462.    ''' Selects or unselects ListBox Items without jumping to the Item position.
  463.    ''' </summary>
  464.    ''' <param name="ItemIndex">Indicates the index of the Items to set.</param>
  465.    ''' <param name="ItemState">Indicates the state for the items.</param>
  466.    Public Sub SetSelected_WithoutJump(ItemIndex As Integer(), ItemState As ItemState)
  467.  
  468.        Dim i As Integer = Me.TopIndex ' Store the selected item index.
  469.        Me.BeginUpdate() ' Disable drawing on control.
  470.  
  471.        For Each Index As Integer In ItemIndex
  472.  
  473.            Select Case ItemState
  474.  
  475.                Case ItemState.Selected
  476.                    Me.SetSelected(Index, True) ' Select the item.
  477.  
  478.                Case ItemState.Unselected
  479.                    Me.SetSelected(Index, False) ' Unselect the item.
  480.  
  481.            End Select
  482.  
  483.        Next Index
  484.  
  485.        Me.TopIndex = i ' Jump to the previous selected item.
  486.        Me.EndUpdate() ' Eenable drawing.
  487.  
  488.    End Sub
  489.  
  490.    ''' <summary>
  491.    ''' Selects or unselects all ListBox Item without jumping to the Item position.
  492.    ''' </summary>
  493.    ''' <param name="ListBoxItems">Indicates the Items to set.</param>
  494.    ''' <param name="ItemState">Indicates the state for the items.</param>
  495.    Public Sub SetSelected_WithoutJump(ListBoxItems As ListBoxItems, ItemState As ItemState)
  496.  
  497.        Dim i As Integer = Me.TopIndex ' Store the selected item index.
  498.        Me.BeginUpdate() ' Disable drawing on control.
  499.  
  500.        Select Case ItemState
  501.  
  502.            Case ItemState.Selected ' Select all the items.
  503.  
  504.                For Item As Integer = 0 To Me.Items.Count - 1
  505.                    Me.SetSelected(Item, True)
  506.                Next Item
  507.  
  508.            Case ItemState.Unselected ' Unselect all the items.
  509.                Me.SelectedItems.Clear()
  510.  
  511.        End Select
  512.  
  513.        Me.TopIndex = i ' Jump to the previous selected item.
  514.        Me.EndUpdate() ' Eenable drawing.
  515.  
  516.    End Sub
  517.  
  518.    ''' <summary>
  519.    ''' Moves an item to other position.
  520.    ''' </summary>
  521.    ''' <param name="ItemPosition">Indicates the position to move from.</param>
  522.    ''' <param name="NewItemPosition">Indicates the new position for the item.</param>
  523.    Public Sub MoveItem(ByVal ItemPosition As Integer, ByVal NewItemPosition As Integer)
  524.  
  525.        Dim oldItem As Object = Me.Items.Item(ItemPosition)
  526.        Dim newItem As Object = Me.Items.Item(NewItemPosition)
  527.  
  528.        Me.Items.Item(ItemPosition) = newItem
  529.        Me.Items.Item(NewItemPosition) = oldItem
  530.  
  531.    End Sub
  532.  
  533. #End Region
  534.  
  535. #Region " Private Methods "
  536.  
  537.    ''' <summary>
  538.    ''' Invalidates the Control to update changes at Design-Time.
  539.    ''' </summary>
  540.    ''' <param name="InvalidateChildren">Indicates whether to invalidate the child controls of the control.</param>
  541.    Private Sub DesignTimeInvalidator(InvalidateChildren As Boolean)
  542.  
  543.        If Me.DesignMode Then
  544.            Me.Invalidate(InvalidateChildren)
  545.        End If
  546.  
  547.    End Sub
  548.  
  549. #End Region
  550.  
  551. #Region " Event Handlers "
  552.  
  553.    ''' <summary>
  554.    ''' This happens when the ListBox 'ReadOnly' state has changed.
  555.    ''' </summary>
  556.    Private Sub OnReadOnly() _
  557.    Handles Me.ReadOnlyChanged
  558.  
  559.        Me.BeginUpdate()
  560.  
  561.        If Me.ReadOnly Then
  562.            Me.Cursor = _ReadOnly_Enabled_Cursor
  563.        Else
  564.            Me.Cursor = _ReadOnly_Disabled_Cursor
  565.        End If
  566.  
  567.        Me.EndUpdate()
  568.  
  569.    End Sub
  570.  
  571.    ''' <summary>
  572.    ''' Colorize the ListBox Items.
  573.    ''' </summary>
  574.    Private Sub Colorize(ByVal sender As Object, ByVal e As DrawItemEventArgs) _
  575.    Handles Me.DrawItem
  576.  
  577.        If Me.Items.Count <> 0 Then
  578.  
  579.            If Me.Enabled AndAlso Not Me.ReadOnly Then
  580.  
  581.                e.DrawBackground()
  582.  
  583.                If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
  584.                    e.Graphics.FillRectangle(_State_Enabled_ItemSelected_BackColor, e.Bounds)
  585.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_Enabled_ItemSelected_ForeColor, e.Bounds)
  586.  
  587.                ElseIf (e.State And DrawItemState.Selected) = DrawItemState.None Then
  588.                    e.Graphics.FillRectangle(_State_Enabled_ItemUnselected_BackColor, e.Bounds)
  589.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_Enabled_ItemUnselected_ForeColor, e.Bounds)
  590.  
  591.                End If
  592.  
  593.                e.DrawFocusRectangle()
  594.  
  595.            ElseIf Not Me.Enabled Then
  596.  
  597.                e.DrawBackground()
  598.  
  599.                If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
  600.                    e.Graphics.FillRectangle(_State_Disabled_ItemSelected_BackColor, e.Bounds)
  601.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_Disabled_ItemSelected_ForeColor, e.Bounds)
  602.  
  603.                ElseIf (e.State And DrawItemState.Selected) = DrawItemState.None Then
  604.                    e.Graphics.FillRectangle(_State_Disabled_ItemUnselected_BackColor, e.Bounds)
  605.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_Disabled_ItemUnselected_ForeColor, e.Bounds)
  606.  
  607.                End If
  608.  
  609.                e.DrawFocusRectangle()
  610.  
  611.            ElseIf Me.ReadOnly Then
  612.  
  613.                e.DrawBackground()
  614.  
  615.                If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
  616.                    e.Graphics.FillRectangle(_State_ReadOnly_ItemSelected_BackColor, e.Bounds)
  617.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_ReadOnly_ItemSelected_ForeColor, e.Bounds)
  618.  
  619.                ElseIf (e.State And DrawItemState.Selected) = DrawItemState.None Then
  620.                    e.Graphics.FillRectangle(_State_ReadOnly_ItemUnselected_BackColor, e.Bounds)
  621.                    e.Graphics.DrawString(Me.GetItemText(Me.Items(e.Index)), e.Font, _State_ReadOnly_ItemUnselected_ForeColor, e.Bounds)
  622.  
  623.                End If
  624.  
  625.                e.DrawFocusRectangle()
  626.  
  627.            End If
  628.  
  629.        End If
  630.  
  631.    End Sub
  632.  
  633. #End Region
  634.  
  635. #Region " Windows Messages "
  636.  
  637.    ''' <summary>
  638.    ''' Processes the Windows Messages for this window.
  639.    ''' </summary>
  640.    Protected Overrides Sub WndProc(ByRef m As Message)
  641.  
  642.        If Me.[ReadOnly] AndAlso (m.Msg = KnownMessages.WM_LBUTTONDOWN OrElse m.Msg = KnownMessages.WM_KEYDOWN) Then
  643.            Return ' Disable left click on the ListBox.
  644.        End If
  645.  
  646.        MyBase.WndProc(m)
  647.  
  648.    End Sub
  649.  
  650. #End Region
  651.  
  652. End Class
« Última modificación: 19 Diciembre 2013, 12:37 pm por ElektroSoft » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #359 en: 11 Enero 2014, 13:32 pm »

Una nueva versión actualizada de mi Helper Class para manejar hotkeys globales.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Created  : 01-09-2014
  4. ' Modified : 01-11-2014
  5. ' ***********************************************************************
  6. ' <copyright file="GlobalHotkeys.vb" company="Elektro Studios">
  7. '     Copyright (c) Elektro Studios. All rights reserved.
  8. ' </copyright>
  9. ' ***********************************************************************
  10.  
  11. #Region " Usage Examples "
  12.  
  13. 'Public Class Form1
  14.  
  15. '    ''' <summary>
  16. '    ''' Define the system-wide hotkey object.
  17. '    ''' </summary>
  18. '    Private WithEvents Hotkey As GlobalHotkey = Nothing
  19.  
  20. '    ''' <summary>
  21. '    ''' Initializes a new instance of this class.
  22. '    ''' </summary>
  23. '    Public Sub New()
  24.  
  25. '        InitializeComponent()
  26.  
  27. '        ' Registers a new global hotkey on the system. (Alt + Ctrl + A)
  28. '        Hotkey = New GlobalHotkey(GlobalHotkey.KeyModifier.Alt Or GlobalHotkey.KeyModifier.Ctrl, Keys.A)
  29.  
  30. '        ' Replaces the current registered hotkey with a new one. (Alt + Escape)
  31. '        Hotkey = New GlobalHotkey([Enum].Parse(GetType(GlobalHotkey.KeyModifier), "Alt", True),
  32. '                                  [Enum].Parse(GetType(Keys), "Escape", True))
  33.  
  34. '        ' Set the tag property.
  35. '        Hotkey.Tag = "I'm an example tag"
  36.  
  37. '    End Sub
  38.  
  39. '    ''' <summary>
  40. '    ''' Handles the Press event of the HotKey object.
  41. '    ''' </summary>
  42. '    Private Sub HotKey_Press(ByVal sender As GlobalHotkey, ByVal e As GlobalHotkey.HotKeyEventArgs) _
  43. '    Handles Hotkey.Press
  44.  
  45. '        MsgBox(e.Count) ' The times that the hotkey was pressed.
  46. '        MsgBox(e.ID) ' The unique hotkey identifier.
  47. '        MsgBox(e.Key.ToString) ' The assigned key.
  48. '        MsgBox(e.Modifier.ToString) ' The assigned key-modifier.
  49.  
  50. '        MsgBox(sender.Tag) ' The hotkey tag object.
  51.  
  52. '        ' Unregister the hotkey.
  53. '        Hotkey.Unregister()
  54.  
  55. '        ' Register it again.
  56. '        Hotkey.Register()
  57.  
  58. '        ' Is Registered?
  59. '        MsgBox(Hotkey.IsRegistered)
  60.  
  61. '    End Sub
  62.  
  63. 'End Class
  64.  
  65. #End Region
  66.  
  67. #Region " Imports "
  68.  
  69. Imports System.ComponentModel
  70. Imports System.Runtime.InteropServices
  71.  
  72. #End Region
  73.  
  74. #Region " Global Hotkey "
  75.  
  76. ''' <summary>
  77. ''' Class to perform system-wide hotkey operations.
  78. ''' </summary>
  79. Friend NotInheritable Class GlobalHotkey : Inherits NativeWindow : Implements IDisposable
  80.  
  81. #Region " API "
  82.  
  83.    ''' <summary>
  84.    ''' Native API Methods.
  85.    ''' </summary>
  86.    Private Class NativeMethods
  87.  
  88.        ''' <summary>
  89.        ''' Defines a system-wide hotkey.
  90.        ''' </summary>
  91.        ''' <param name="hWnd">The hWND.</param>
  92.        ''' <param name="id">The identifier of the hotkey.
  93.        ''' If the hWnd parameter is NULL, then the hotkey is associated with the current thread rather than with a particular window.
  94.        ''' If a hotkey already exists with the same hWnd and id parameters.</param>
  95.        ''' <param name="fsModifiers">The keys that must be pressed in combination with the key specified by the uVirtKey parameter
  96.        ''' in order to generate the WM_HOTKEY message.
  97.        ''' The fsModifiers parameter can be a combination of the following values.</param>
  98.        ''' <param name="vk">The virtual-key code of the hotkey.</param>
  99.        ''' <returns>
  100.        ''' <c>true</c> if the function succeeds, otherwise <c>false</c>
  101.        ''' </returns>
  102.        <DllImport("user32.dll", SetLastError:=True)>
  103.        Public Shared Function RegisterHotKey(
  104.                      ByVal hWnd As IntPtr,
  105.                      ByVal id As Integer,
  106.                      ByVal fsModifiers As UInteger,
  107.                      ByVal vk As UInteger
  108.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  109.        End Function
  110.  
  111.        ''' <summary>
  112.        ''' Unregisters a hotkey previously registered.
  113.        ''' </summary>
  114.        ''' <param name="hWnd">The hWND.</param>
  115.        ''' <param name="id">The identifier of the hotkey to be unregistered.</param>
  116.        ''' <returns>
  117.        ''' <c>true</c> if the function succeeds, otherwise <c>false</c>
  118.        ''' </returns>
  119.        <DllImport("user32.dll", SetLastError:=True)>
  120.        Public Shared Function UnregisterHotKey(
  121.                      ByVal hWnd As IntPtr,
  122.                      ByVal id As Integer
  123.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  124.        End Function
  125.  
  126.    End Class
  127.  
  128. #End Region
  129.  
  130. #Region " Members "
  131.  
  132. #Region " Properties "
  133.  
  134.    ''' <summary>
  135.    ''' Indicates the key assigned to the hotkey.
  136.    ''' </summary>
  137.    Public ReadOnly Property Key As Keys
  138.        Get
  139.            Return Me.PressEventArgs.Key
  140.        End Get
  141.    End Property
  142.  
  143.    ''' <summary>
  144.    ''' Indicates the Key-Modifier assigned to the hotkey.
  145.    ''' </summary>
  146.    Public ReadOnly Property Modifier As KeyModifier
  147.        Get
  148.            Return Me.PressEventArgs.Modifier
  149.        End Get
  150.    End Property
  151.  
  152.    ''' <summary>
  153.    ''' Indicates the unique identifier assigned to the hotkey.
  154.    ''' </summary>
  155.    Public ReadOnly Property ID As Integer
  156.        Get
  157.            Return Me.PressEventArgs.ID
  158.        End Get
  159.    End Property
  160.  
  161.    ''' <summary>
  162.    ''' Indicates user-defined data associated with this object.
  163.    ''' </summary>
  164.    Public Property Tag As Object = Nothing
  165.  
  166.    ''' <summary>
  167.    ''' Indicates how many times was pressed the hotkey.
  168.    ''' </summary>
  169.    Public ReadOnly Property Count As Integer
  170.        Get
  171.            Return _Count
  172.        End Get
  173.    End Property
  174.  
  175. #End Region
  176.  
  177. #Region " Enumerations "
  178.  
  179.    ''' <summary>
  180.    ''' Key-modifiers to assign to a hotkey.
  181.    ''' </summary>
  182.    <Flags>
  183.    Public Enum KeyModifier As Integer
  184.  
  185.        ''' <summary>
  186.        ''' Any modifier.
  187.        ''' </summary>
  188.        None = &H0
  189.  
  190.        ''' <summary>
  191.        ''' The Alt key.
  192.        ''' </summary>
  193.        Alt = &H1
  194.  
  195.        ''' <summary>
  196.        ''' The Control key.
  197.        ''' </summary>
  198.        Ctrl = &H2
  199.  
  200.        ''' <summary>
  201.        ''' The Shift key.
  202.        ''' </summary>
  203.        Shift = &H4
  204.  
  205.        ''' <summary>
  206.        ''' The Windows key.
  207.        ''' </summary>
  208.        Win = &H8
  209.  
  210.    End Enum
  211.  
  212.    ''' <summary>
  213.    ''' Known Windows Message Identifiers.
  214.    ''' </summary>
  215.    <Description("Messages to process in WndProc")>
  216.    Public Enum KnownMessages As Integer
  217.  
  218.        ''' <summary>
  219.        ''' Posted when the user presses a hot key registered by the RegisterHotKey function.
  220.        ''' The message is placed at the top of the message queue associated with the thread that registered the hot key.
  221.        ''' <paramref name="WParam"/>
  222.        ''' The identifier of the hot key that generated the message.
  223.        ''' If the message was generated by a system-defined hot key.
  224.        ''' <paramref name="LParam"/>
  225.        ''' The low-order word specifies the keys that were to be pressed in
  226.        ''' combination with the key specified by the high-order word to generate the WM_HOTKEY message.
  227.        ''' </summary>
  228.        WM_HOTKEY = &H312
  229.  
  230.    End Enum
  231.  
  232. #End Region
  233.  
  234. #Region " Events "
  235.  
  236.    ''' <summary>
  237.    ''' Event that is raised when a hotkey is pressed.
  238.    ''' </summary>
  239.    Public Event Press As EventHandler(Of HotKeyEventArgs)
  240.  
  241.    ''' <summary>
  242.    ''' Event arguments for the Press event.
  243.    ''' </summary>
  244.    Public Class HotKeyEventArgs : Inherits EventArgs
  245.  
  246.        ''' <summary>
  247.        ''' Indicates the Key assigned to the hotkey.
  248.        ''' </summary>
  249.        ''' <value>The key.</value>
  250.        Friend Property Key As Keys
  251.  
  252.        ''' <summary>
  253.        ''' Indicates the Key-Modifier assigned to the hotkey.
  254.        ''' </summary>
  255.        ''' <value>The modifier.</value>
  256.        Friend Property Modifier As KeyModifier
  257.  
  258.        ''' <summary>
  259.        ''' Indicates the unique identifier assigned to the hotkey.
  260.        ''' </summary>
  261.        ''' <value>The identifier.</value>
  262.        Friend Property ID As Integer
  263.  
  264.        ''' <summary>
  265.        ''' Indicates how many times was pressed the hotkey.
  266.        ''' </summary>
  267.        Friend Property Count As Integer
  268.  
  269.    End Class
  270.  
  271. #End Region
  272.  
  273. #Region " Exceptions "
  274.  
  275.    ''' <summary>
  276.    ''' Exception that is thrown when a hotkey tries to register but is already registered.
  277.    ''' </summary>
  278.    <Serializable>
  279.    Private Class IsRegisteredException : Inherits Exception
  280.  
  281.        ''' <summary>
  282.        ''' Initializes a new instance of the <see cref="IsRegisteredException"/> class.
  283.        ''' </summary>
  284.        Sub New()
  285.            MyBase.New("Unable to register. Hotkey is already registered.")
  286.        End Sub
  287.  
  288.    End Class
  289.  
  290.    ''' <summary>
  291.    ''' Exception that is thrown when a hotkey tries to unregister but is not registered.
  292.    ''' </summary>
  293.    <Serializable>
  294.    Private Class IsNotRegisteredException : Inherits Exception
  295.  
  296.        ''' <summary>
  297.        ''' Initializes a new instance of the <see cref="IsNotRegisteredException"/> class.
  298.        ''' </summary>
  299.        Sub New()
  300.            MyBase.New("Unable to unregister. Hotkey is not registered.")
  301.        End Sub
  302.  
  303.    End Class
  304.  
  305. #End Region
  306.  
  307. #Region " Other "
  308.  
  309.    ''' <summary>
  310.    ''' Stores an counter indicating how many times was pressed the hotkey.
  311.    ''' </summary>
  312.    Private _Count As Integer = 0
  313.  
  314.    ''' <summary>
  315.    ''' Stores the Press Event Arguments.
  316.    ''' </summary>
  317.    Protected PressEventArgs As New HotKeyEventArgs
  318.  
  319. #End Region
  320.  
  321. #End Region
  322.  
  323. #Region " Constructor "
  324.  
  325.    ''' <summary>
  326.    ''' Creates a new system-wide hotkey.
  327.    ''' </summary>
  328.    ''' <param name="Modifier">
  329.    ''' Indicates the key-modifier to assign to the hotkey.
  330.    ''' ( Can use one or more modifiers )
  331.    ''' </param>
  332.    ''' <param name="Key">
  333.    ''' Indicates the key to assign to the hotkey.
  334.    ''' </param>
  335.    ''' <exception cref="IsRegisteredException"></exception>
  336.    <DebuggerStepperBoundary()>
  337.    Public Sub New(ByVal Modifier As KeyModifier, ByVal Key As Keys)
  338.  
  339.        MyBase.CreateHandle(New CreateParams)
  340.  
  341.        Me.PressEventArgs.ID = MyBase.GetHashCode()
  342.        Me.PressEventArgs.Key = Key
  343.        Me.PressEventArgs.Modifier = Modifier
  344.        Me.PressEventArgs.Count = 0
  345.  
  346.        If Not NativeMethods.RegisterHotKey(MyBase.Handle,
  347.                                            Me.ID,
  348.                                            Me.Modifier,
  349.                                            Me.Key) Then
  350.  
  351.            Throw New IsRegisteredException
  352.  
  353.        End If
  354.  
  355.    End Sub
  356.  
  357. #End Region
  358.  
  359. #Region " Event Handlers "
  360.  
  361.    ''' <summary>
  362.    ''' Occurs when a hotkey is pressed.
  363.    ''' </summary>
  364.    Private Sub OnHotkeyPress() Handles Me.Press
  365.        _Count += 1
  366.    End Sub
  367.  
  368. #End Region
  369.  
  370. #Region "Public Methods "
  371.  
  372.    ''' <summary>
  373.    ''' Determines whether this hotkey is registered on the system.
  374.    ''' </summary>
  375.    ''' <returns>
  376.    ''' <c>true</c> if this hotkey is registered; otherwise, <c>false</c>.
  377.    ''' </returns>
  378.    Public Function IsRegistered() As Boolean
  379.  
  380.        DisposedCheck()
  381.  
  382.        ' Try to unregister the hotkey.
  383.        Select Case NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID)
  384.  
  385.            Case False ' Unregistration failed.
  386.                Return False ' Hotkey is not registered.
  387.  
  388.            Case Else ' Unregistration succeeds.
  389.                Register() ' Re-Register the hotkey before return.
  390.                Return True ' Hotkey is registeres.
  391.  
  392.        End Select
  393.  
  394.    End Function
  395.  
  396.    ''' <summary>
  397.    ''' Registers this hotkey on the system.
  398.    ''' </summary>
  399.    ''' <exception cref="IsRegisteredException"></exception>
  400.    Public Sub Register()
  401.  
  402.        DisposedCheck()
  403.  
  404.        If Not NativeMethods.RegisterHotKey(MyBase.Handle,
  405.                                            Me.ID,
  406.                                            Me.Modifier,
  407.                                            Me.Key) Then
  408.  
  409.            Throw New IsRegisteredException
  410.  
  411.        End If
  412.  
  413.    End Sub
  414.  
  415.    ''' <summary>
  416.    ''' Unregisters this hotkey from the system.
  417.    ''' After calling this method the hotkey turns unavaliable.
  418.    ''' </summary>
  419.    ''' <returns>
  420.    ''' <c>true</c> if unregistration succeeds, <c>false</c> otherwise.
  421.    ''' </returns>
  422.    Public Function Unregister() As Boolean
  423.  
  424.        DisposedCheck()
  425.  
  426.        If Not NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID) Then
  427.  
  428.            Throw New IsNotRegisteredException
  429.  
  430.        End If
  431.  
  432.    End Function
  433.  
  434. #End Region
  435.  
  436. #Region " Hidden methods "
  437.  
  438.    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
  439.    ' NOTE: The methods can be re-enabled at any-time if needed.
  440.  
  441.    ''' <summary>
  442.    ''' Assigns the handle.
  443.    ''' </summary>
  444.    <EditorBrowsable(EditorBrowsableState.Never)>
  445.    Public Shadows Sub AssignHandle()
  446.    End Sub
  447.  
  448.    ''' <summary>
  449.    ''' Creates the handle.
  450.    ''' </summary>
  451.    <EditorBrowsable(EditorBrowsableState.Never)>
  452.    Public Shadows Sub CreateHandle()
  453.    End Sub
  454.  
  455.    ''' <summary>
  456.    ''' Creates the object reference.
  457.    ''' </summary>
  458.    <EditorBrowsable(EditorBrowsableState.Never)>
  459.    Public Shadows Sub CreateObjRef()
  460.    End Sub
  461.  
  462.    ''' <summary>
  463.    ''' Definitions the WND proc.
  464.    ''' </summary>
  465.    <EditorBrowsable(EditorBrowsableState.Never)>
  466.    Public Shadows Sub DefWndProc()
  467.    End Sub
  468.  
  469.    ''' <summary>
  470.    ''' Destroys the window and its handle.
  471.    ''' </summary>
  472.    <EditorBrowsable(EditorBrowsableState.Never)>
  473.    Public Shadows Sub DestroyHandle()
  474.    End Sub
  475.  
  476.    ''' <summary>
  477.    ''' Equalses this instance.
  478.    ''' </summary>
  479.    <EditorBrowsable(EditorBrowsableState.Never)>
  480.    Public Shadows Sub Equals()
  481.    End Sub
  482.  
  483.    ''' <summary>
  484.    ''' Gets the hash code.
  485.    ''' </summary>
  486.    <EditorBrowsable(EditorBrowsableState.Never)>
  487.    Public Shadows Sub GetHashCode()
  488.    End Sub
  489.  
  490.    ''' <summary>
  491.    ''' Gets the lifetime service.
  492.    ''' </summary>
  493.    <EditorBrowsable(EditorBrowsableState.Never)>
  494.    Public Shadows Sub GetLifetimeService()
  495.    End Sub
  496.  
  497.    ''' <summary>
  498.    ''' Initializes the lifetime service.
  499.    ''' </summary>
  500.    <EditorBrowsable(EditorBrowsableState.Never)>
  501.    Public Shadows Sub InitializeLifetimeService()
  502.    End Sub
  503.  
  504.    ''' <summary>
  505.    ''' Releases the handle associated with this window.
  506.    ''' </summary>
  507.    <EditorBrowsable(EditorBrowsableState.Never)>
  508.    Public Shadows Sub ReleaseHandle()
  509.    End Sub
  510.  
  511.    ''' <summary>
  512.    ''' Gets the handle for this window.
  513.    ''' </summary>
  514.    <EditorBrowsable(EditorBrowsableState.Never)>
  515.    Public Shadows Property Handle()
  516.  
  517. #End Region
  518.  
  519. #Region " WndProc "
  520.  
  521.    ''' <summary>
  522.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  523.    ''' </summary>
  524.    ''' <param name="m">
  525.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  526.    ''' </param>
  527.    Protected Overrides Sub WndProc(ByRef m As Message)
  528.  
  529.        Select Case m.Msg
  530.  
  531.            Case KnownMessages.WM_HOTKEY  ' A hotkey is pressed.
  532.  
  533.                ' Update the pressed counter.
  534.                Me.PressEventArgs.Count += 1
  535.  
  536.                ' Raise the Event
  537.                RaiseEvent Press(Me, Me.PressEventArgs)
  538.  
  539.            Case Else
  540.                MyBase.WndProc(m)
  541.  
  542.        End Select
  543.  
  544.    End Sub
  545.  
  546. #End Region
  547.  
  548. #Region " IDisposable "
  549.  
  550.    ''' <summary>
  551.    ''' To detect redundant calls when disposing.
  552.    ''' </summary>
  553.    Private IsDisposed As Boolean = False
  554.  
  555.    ''' <summary>
  556.    ''' Prevent calls to methods after disposing.
  557.    ''' </summary>
  558.    ''' <exception cref="System.ObjectDisposedException"></exception>
  559.    Private Sub DisposedCheck()
  560.  
  561.        If Me.IsDisposed Then
  562.            Throw New ObjectDisposedException(Me.GetType().FullName)
  563.        End If
  564.  
  565.    End Sub
  566.  
  567.    ''' <summary>
  568.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  569.    ''' </summary>
  570.    Public Sub Dispose() Implements IDisposable.Dispose
  571.        Dispose(True)
  572.        GC.SuppressFinalize(Me)
  573.    End Sub
  574.  
  575.    ''' <summary>
  576.    ''' Releases unmanaged and - optionally - managed resources.
  577.    ''' </summary>
  578.    ''' <param name="IsDisposing">
  579.    ''' <c>true</c> to release both managed and unmanaged resources;
  580.    ''' <c>false</c> to release only unmanaged resources.
  581.    ''' </param>
  582.    Protected Sub Dispose(IsDisposing As Boolean)
  583.  
  584.        If Not Me.IsDisposed Then
  585.  
  586.            If IsDisposing Then
  587.                NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID)
  588.            End If
  589.  
  590.        End If
  591.  
  592.        Me.IsDisposed = True
  593.  
  594.    End Sub
  595.  
  596. #End Region
  597.  
  598. End Class
  599.  
  600. #End Region
« Última modificación: 12 Enero 2014, 09:28 am por Eleкtro » En línea

Páginas: 1 ... 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 49 50 51 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

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