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

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  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 ... 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 [34] 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,092 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



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

Una función genérica para agregar un item a un array de 2 dimensiones

Código
  1. #Region " Add Item Array 2D "
  2.  
  3.    ' [ Add Item Array 2D ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    '// Create an Array 2D (2,2)
  10.    ' Dim MyArray As String(,) = {{"Item 0,0", "Item 0,1"}, {"Item 1,0", "Item 1,1"}, {"Item 2,0", "Item 2,1"}}
  11.    '// Add an Item
  12.    ' Add_Item_Array_2D(MyArray, {"Item 3,0", "Item 3,1"})
  13.  
  14.    Private Sub Add_Item_Array_2D(ByRef Array_2D As String(,), _
  15.                                  ByVal Items As String())
  16.  
  17.        Dim tmp_array(Array_2D.GetUpperBound(0) + 1, Array_2D.GetUpperBound(1)) As String
  18.  
  19.        For x As Integer = 0 To Array_2D.GetUpperBound(0)
  20.            tmp_array(x, 0) = Array_2D(x, 0)
  21.            tmp_array(x, 1) = Array_2D(x, 1)
  22.        Next
  23.  
  24.        For x As Integer = 0 To Items.Count - 1
  25.            tmp_array(tmp_array.GetUpperBound(0), x) = Items(x)
  26.        Next
  27.  
  28.        Array_2D = tmp_array
  29.  
  30.    End Sub
  31.  
  32. #End Region





Un ejemplo de como ordenar un documento XML según un elemento dado:

Código
  1. #Region " Sort XML By Element "
  2.  
  3.    ' [ Sort XML By Element ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Example usage :
  8.    ' Dim XML As XDocument = Sort_XML_By_Element(XDocument.Load("C:\File.xml"), "Song", "Name")
  9.  
  10.    ' Example XML File:
  11.    '
  12.    '<?xml version="1.0" encoding="Windows-1252"?>
  13.    '<Songs>
  14.    '    <Song><Name>My Song 2.mp3</Name><Year>2007</Year></Song>
  15.    '    <Song><Name>My Song 1.mp3</Name><Year>2009</Year></Song>
  16.    '    <Song><Name>My Song 3.mp3</Name><Year>2008</Year></Song>
  17.    '</Songs>
  18.  
  19.    ' Example output:
  20.    '
  21.    '<?xml version="1.0" encoding="Windows-1252"?>
  22.    '<Songs>
  23.    '    <Song><Name>My Song 1.mp3</Name><Year>2009</Year></Song>
  24.    '    <Song><Name>My Song 2.mp3</Name><Year>2007</Year></Song>
  25.    '    <Song><Name>My Song 3.mp3</Name><Year>2008</Year></Song>
  26.    '</Songs>
  27.  
  28.    Private Function Sort_XML_By_Element(ByVal XML As XDocument, _
  29.                                     ByVal Root_Element As String, _
  30.                                     ByVal Element_to_sort As String) As XDocument
  31.  
  32.        Dim xdoc As XDocument
  33.  
  34.        Try
  35.  
  36.            xdoc = XML
  37.            xdoc.Root.ReplaceNodes(XML.Root.Elements(Root_Element) _
  38.                                  .OrderBy(Function(sort) sort.Element(Element_to_sort).Value))
  39.  
  40.            Return xdoc
  41.  
  42.        Catch ex As Exception
  43.            Throw New Exception(ex.Message)
  44.  
  45.        Finally
  46.            xdoc = Nothing
  47.  
  48.        End Try
  49.  
  50.    End Function
  51.  
  52. #End Region





Un ejemplo de como convertir los elementos de un documento XML a un type anónimo:

Código
  1. #Region " Convert XML to Anonymous Type "
  2.  
  3.        'Dim xml As XDocument = XDocument.Load(xmlfile)
  4.  
  5.        Dim xml As XDocument = _
  6.        <?xml version="1.0" encoding="Windows-1252"?>
  7.        <!--XML Songs Database.-->
  8.        <Songs>
  9.            <Song><Name>My Song 1.mp3</Name><Year>2007</Year><Genre>Dance</Genre><Bitrate>320</Bitrate><Length>04:55</Length><Size>4,80</Size></Song>
  10.            <Song><Name>My Song 2.mp3</Name><Year>2009</Year><Genre>Electro</Genre><Bitrate>192</Bitrate><Length>06:44</Length><Size>8,43</Size></Song>
  11.            <Song><Name>My Song 3.mp3</Name><Year>2008</Year><Genre>UK Hardcore</Genre><Bitrate>128</Bitrate><Length>05:12</Length><Size>4,20</Size></Song>
  12.        </Songs>
  13.  
  14.        Dim SongsList = From song In xml.<Songs>.<Song>
  15.                        Select New With { _
  16.                                          song.<Name>.Value,
  17.                                          song.<Year>.Value,
  18.                                          song.<Genre>.Value,
  19.                                          song.<Bitrate>.Value,
  20.                                          song.<Length>.Value,
  21.                                          song.<Size>.Value _
  22.                                       }
  23.  
  24.        For Each song In SongsList
  25.  
  26.            MsgBox(String.Format("Name:{1}{0}Year:{2}{0}Genre:{3}{0}Bitrate:{4}{0}Length:{5}{0}Size:{6}", _
  27.                                 Environment.NewLine, _
  28.                                 song.Name, song.Year, song.Genre, song.Bitrate, song.Length, song.Size))
  29.  
  30.            ' Output:
  31.            '
  32.            'Name:My Song 1.mp3
  33.            'Year:2007
  34.            'Genre:Dance
  35.            'Bitrate:320
  36.            'Length:04:55
  37.            'Size:4,80
  38.  
  39.        Next
  40.  
  41. #End Region





Un ejemplo de como convertir los elementos de un documento XML a Tuplas

Código
  1. #Region " Convert XML to IEnumerable(Of Tuple) "
  2.  
  3.        'Dim xml As XDocument = XDocument.Load(xmlfile)
  4.  
  5.        Dim xml As XDocument = _
  6.        <?xml version="1.0" encoding="Windows-1252"?>
  7.        <!--XML Songs Database.-->
  8.        <Songs>
  9.            <Song><Name>My Song 1.mp3</Name><Year>2007</Year><Genre>Dance</Genre><Bitrate>320</Bitrate><Length>04:55</Length><Size>4,80</Size></Song>
  10.            <Song><Name>My Song 2.mp3</Name><Year>2009</Year><Genre>Electro</Genre><Bitrate>192</Bitrate><Length>06:44</Length><Size>8,43</Size></Song>
  11.            <Song><Name>My Song 3.mp3</Name><Year>2008</Year><Genre>UK Hardcore</Genre><Bitrate>128</Bitrate><Length>05:12</Length><Size>4,20</Size></Song>
  12.        </Songs>
  13.  
  14.        Dim SongsList As IEnumerable(Of Tuple(Of String, String, String, String, String, String)) = _
  15.            From song In xml.<Songs>.<Song>
  16.            Select Tuple.Create( _
  17.                                 song.<Name>.Value,
  18.                                 song.<Year>.Value,
  19.                                 song.<Genre>.Value,
  20.                                 song.<Bitrate>.Value,
  21.                                 song.<Length>.Value,
  22.                                 song.<Size>.Value _
  23.                               )
  24.  
  25.        For Each song In SongsList
  26.  
  27.            MsgBox(String.Format("Name:{1}{0}Year:{2}{0}Genre:{3}{0}Bitrate:{4}{0}Length:{5}{0}Size:{6}", _
  28.                                 Environment.NewLine, _
  29.                                 song.Item1, song.Item2, song.Item3, song.Item4, song.Item5, song.Item6))
  30.  
  31.            ' Output:
  32.            '
  33.            'Name:My Song 1.mp3
  34.            'Year:2007
  35.            'Genre:Dance
  36.            'Bitrate:320
  37.            'Length:04:55
  38.            'Size:4,80
  39.  
  40.        Next
  41.  
  42. #End Region





Un ejemplo de como usar Arrays 2D

Código
  1.        ' Create Array 2D (2,2)
  2.        Dim MyArray As String(,) = {{"Item 0,0", "Item 0,1"}, {"Item 1,0", "Item 1,1"}, {"Item 2,0", "Item 2,1"}}
  3.  
  4.        ' Set value
  5.        MyArray(0, 1) = "New Item 0,1"
  6.  
  7.        ' Get Value
  8.        MsgBox(MyArray(0, 1))
  9.  
  10.        ' Loop over the Array 2D
  11.        For x As Integer = 0 To MyArray.GetUpperBound(0)
  12.            MsgBox(String.Format("Array 2D {1},0: {2}{0}Array 2D {1},1: {3}", Environment.NewLine, _
  13.                                x, MyArray(x, 0), MyArray(x, 1)))
  14.        Next





Un ejemplo de como crear un Type propio:

Código
  1.    Public Class Type1
  2.  
  3.        Private _Name As String
  4.        Private _Age As Short
  5.  
  6.        Public Property Name() As String
  7.            Get
  8.                Return _Name
  9.            End Get
  10.            Set(ByVal value As String)
  11.                _Name = value
  12.            End Set
  13.        End Property
  14.  
  15.        Public Property Age() As Short
  16.            Get
  17.                Return _Age
  18.            End Get
  19.            Set(ByVal value As Short)
  20.                _Age = value
  21.            End Set
  22.        End Property
  23.  
  24.    End Class
  25.  
  26.    'Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  27.    '
  28.    '    ' Create a list of our own Type and add Elements:
  29.    '    Dim Contacts As New List(Of Type1) From { _
  30.    '        New Type1 With {.Name = "Lucia", .Age = 19}, _
  31.    '        New Type1 With {.Name = "Pepe", .Age = 40} _
  32.    '    }
  33.    '
  34.    '    ' Add another Element
  35.    '    Contacts.Add(New Type1 With {.Name = "Pablo", .Age = 32})
  36.    '
  37.    '    ' Find an Element:
  38.    '    Dim Contact As Type1 = Contacts.Find(Function(x) x.Name = "Lucia")
  39.    '
  40.    '    ' Display Element members:
  41.    '    MsgBox(String.Format("Name: {1}{0}Age: {2}", _
  42.    '                         Environment.NewLine, _
  43.    '                         Contact.Name, Contact.Age))
  44.    '
  45.    '    ' Loop over all Elements:
  46.    '    For Each Element As Type1 In Contacts
  47.    '        MsgBox(String.Format("Name: {1}{0}Age: {2}", _
  48.    '                        Environment.NewLine, _
  49.    '                        Element.Name, Element.Age))
  50.    '    Next
  51.    '
  52.    'End Sub




Una función genérica para obtener el serial de la CPU
(Este snippet fue de los primeros que posteé, le he dado un repaso al código)

Código
  1.    #Region " Get CPU ID "
  2.  
  3.       ' [ Get CPU ID ]
  4.       '
  5.       '// By Elektro H@cker
  6.       '
  7.       ' INSTRUCTIONS:
  8.       ' 1. Add a reference to "System.Management"
  9.       '
  10.       ' Examples :
  11.       ' Dim ProcID As String = Get_CPU_ID()
  12.       ' MsgBox(Get_CPU_ID())
  13.  
  14.    Private Function Get_CPU_ID() As String
  15.  
  16.        Dim wmi As Management.ManagementObjectSearcher = _
  17.            New Management.ManagementObjectSearcher("select * from Win32_Processor")
  18.  
  19.        Dim val As String = wmi.Get(0)("ProcessorID")
  20.  
  21.        wmi.Dispose()
  22.  
  23.        Return val.ToString
  24.  
  25.    End Function
  26.  
  27.    #End Region





Una función genérica para obtener el serial de la placa base
(Este snippet fue de los primeros que posteé, le he dado un repaso al código)

Código
  1.    #Region " Get Motherboard ID "
  2.  
  3.       ' [ Get Motherboard ID ]
  4.       '
  5.       '// By Elektro H@cker
  6.       '
  7.       ' INSTRUCTIONS:
  8.       ' 1. Add a reference to "System.Management"
  9.       '
  10.       ' Examples :
  11.       ' Dim MotherID As String = Get_Motherboard_ID()
  12.       ' MsgBox(Get_Motherboard_ID())
  13.  
  14.    Private Function Get_Motherboard_ID() As String
  15.  
  16.        Dim wmi As Management.ManagementObjectSearcher = _
  17.            New Management.ManagementObjectSearcher("select * from Win32_BaseBoard")
  18.  
  19.        Dim val As String = wmi.Get(0)("SerialNumber")
  20.  
  21.        wmi.Dispose()
  22.  
  23.        Return val
  24.  
  25.    End Function
  26.  
  27.    #End Region





Y por último, unos ejemplos muy sencillos de como manejar un documento XML (sencillo)...
(Uso un XMLTextWritter en lugar de un XMLWriter por la libertad de indentación)

Código
  1. ' [ Song XML Writer Helper ]
  2. '
  3. ' // By Elektro H@cker
  4. '
  5. ' Example usage :
  6. '
  7. 'Private Sub Test()
  8. '
  9. '    ' Set an XML file to create
  10. '    Dim xmlfile As String = "C:\My XML File.xml"
  11. '
  12. '    ' Create the XmlWriter object
  13. '    Dim XmlWriter As Xml.XmlTextWriter = _
  14. '        New Xml.XmlTextWriter(xmlfile, System.Text.Encoding.Default) _
  15. '        With {.Formatting = Xml.Formatting.Indented}
  16. '
  17. '    ' Write the Xml declaration.
  18. '    XMLHelper.Write_Beginning(XmlWriter)
  19. '    ' Output at this point:
  20. '    ' <?xml version="1.0" encoding="Windows-1252"?>
  21. '
  22. '    ' Write a comment.
  23. '    XMLHelper.Write_Comment(XmlWriter, "XML Songs Database", Xml.Formatting.Indented)
  24. '    ' Output at this point:
  25. '    ' <!--XML Songs Database-->
  26. '
  27. '    ' Write the root element.
  28. '    XMLHelper.Write_Beginning_Root_Element(XmlWriter, "Songs", Xml.Formatting.Indented)
  29. '    ' Output at this point:
  30. '    ' <Songs>
  31. '
  32. '    ' Write the start of a song element.
  33. '    XMLHelper.Write_Beginning_Root_Element(XmlWriter, "Song", Xml.Formatting.Indented)
  34. '    ' Output at this point:
  35. '    ' <Song>
  36. '
  37. '    ' Write a song element.
  38. '    XMLHelper.Write_Elements(XmlWriter, { _
  39. '                                         {"Name", "My Song file.mp3"}, _
  40. '                                         {"Year", "2013"}, _
  41. '                                         {"Genre", "Rock"} _
  42. '                                        }, Xml.Formatting.None)        
  43. '    ' Output at this point:
  44. '    ' <Name>My Song file.mp3</Name><Year>2007</Year><Genre>Dance</Genre>
  45. '
  46. '    ' Write the end of a song element.
  47. '    XMLHelper.Write_End_Root_Element(XmlWriter, Xml.Formatting.None)
  48. '    ' Output at this point:
  49. '    ' </Song>
  50. '
  51. '    ' Write the end of the Root element.
  52. '    XMLHelper.Write_End_Root_Element(XmlWriter, Xml.Formatting.Indented)
  53. '    ' Output at this point:
  54. '    ' </Songs>
  55. '
  56. '    ' Write the xml end of file.
  57. '    XMLHelper.Write_End(XmlWriter)
  58. '
  59. '    ' Start the file and exit
  60. '    Process.Start(xmlfile) : Application.Exit()
  61. '
  62. '    ' Final output:
  63. '    '
  64. '    '<?xml version="1.0" encoding="Windows-1252"?>
  65. '    '<!--XML Songs Database-->
  66. '    '<Songs>
  67. '    '  <Song><Name>My Song file.mp3</Name><Year>2007</Year><Genre>Dance</Genre></Song>
  68. '    '</Songs>
  69. '
  70. 'End Sub
  71.  
  72. #Region " XML Helper "
  73.  
  74. Class XMLHelper
  75.  
  76.    ''' <summary>
  77.    ''' Writes the Xml beginning declaration.
  78.    ''' </summary>
  79.    Shared Sub Write_Beginning(ByVal XmlWriter As Xml.XmlTextWriter)
  80.  
  81.        Try
  82.            XmlWriter.WriteStartDocument()
  83.  
  84.        Catch ex As InvalidOperationException
  85.            Dim errormsg As String = "This is not the first write method called after the constructor. "
  86.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  87.            ' MessageBox.Show(errormsg)
  88.  
  89.        Catch ex As Exception
  90.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  91.  
  92.        End Try
  93.  
  94.    End Sub
  95.  
  96.    ''' <summary>
  97.    ''' Writes a comment.
  98.    ''' </summary>
  99.    Shared Sub Write_Comment(ByVal XmlWriter As Xml.XmlTextWriter, _
  100.                                  ByVal Comment As String, _
  101.                                  Optional ByVal Indentation As Xml.Formatting = Xml.Formatting.Indented)
  102.  
  103.        Try
  104.            XmlWriter.Formatting = Indentation
  105.            XmlWriter.WriteComment(Comment)
  106.            XmlWriter.Formatting = Not Indentation
  107.  
  108.        Catch ex As ArgumentException
  109.            Dim errormsg As String = "The text would result in a non-well formed XML document"
  110.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  111.            ' MessageBox.Show(errormsg)
  112.  
  113.        Catch ex As InvalidOperationException
  114.            Dim errormsg As String = "The ""WriteState"" property is Closed"
  115.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  116.            ' MessageBox.Show(errormsg)
  117.  
  118.        Catch ex As Exception
  119.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  120.  
  121.        End Try
  122.  
  123.    End Sub
  124.  
  125.    ''' <summary>
  126.    ''' Writes the beginning of a root element.
  127.    ''' </summary>
  128.    Shared Sub Write_Beginning_Root_Element(ByVal XmlWriter As Xml.XmlTextWriter, _
  129.                                                 ByVal Element As String, _
  130.                                                 Optional ByVal Indentation As Xml.Formatting = Xml.Formatting.Indented)
  131.  
  132.        Try
  133.            XmlWriter.Formatting = Indentation
  134.            XmlWriter.WriteStartElement(Element)
  135.            XmlWriter.Formatting = Not Indentation
  136.  
  137.        Catch ex As System.Text.EncoderFallbackException
  138.            Dim errormsg As String = "There is a character in the buffer that is a valid XML character but is not valid for the output encoding."
  139.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  140.            ' MessageBox.Show(errormsg)
  141.  
  142.        Catch ex As InvalidOperationException
  143.            Dim errormsg As String = "The XmlTextWriter is closed or An XmlTextWriter method was called before a previous asynchronous operation finished."
  144.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  145.            ' MessageBox.Show(errormsg)
  146.  
  147.        Catch ex As Exception
  148.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  149.  
  150.        End Try
  151.  
  152.    End Sub
  153.  
  154.    ''' <summary>
  155.    ''' Writes the end of a root element.
  156.    ''' </summary>
  157.    Shared Sub Write_End_Root_Element(ByVal XmlWriter As Xml.XmlTextWriter, _
  158.                                           Optional ByVal Indentation As Xml.Formatting = Xml.Formatting.Indented)
  159.  
  160.        Try
  161.            XmlWriter.Formatting = Indentation
  162.            XmlWriter.WriteEndElement()
  163.            XmlWriter.Formatting = Not Indentation
  164.  
  165.        Catch ex As System.Text.EncoderFallbackException
  166.            Dim errormsg As String = "There is a character in the buffer that is a valid XML character but is not valid for the output encoding."
  167.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  168.            ' MessageBox.Show(errormsg)
  169.  
  170.        Catch ex As InvalidOperationException
  171.            Dim errormsg As String = "The XmlTextWriter is closed or An XmlTextWriter method was called before a previous asynchronous operation finished."
  172.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  173.            ' MessageBox.Show(errormsg)
  174.  
  175.        Catch ex As Exception
  176.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  177.  
  178.        End Try
  179.  
  180.    End Sub
  181.  
  182.    ''' <summary>
  183.    ''' Writes an element.
  184.    ''' </summary>
  185.    Shared Sub Write_Element(ByVal XmlWriter As Xml.XmlTextWriter, _
  186.                                  ByVal StartElement As String, _
  187.                                  ByVal Element As String, _
  188.                                  Optional ByVal Indentation As Xml.Formatting = Xml.Formatting.Indented)
  189.  
  190.        Try
  191.            XmlWriter.Formatting = Indentation
  192.            XmlWriter.WriteStartElement(StartElement)
  193.            XmlWriter.WriteString(Element)
  194.            XmlWriter.WriteEndElement()
  195.            XmlWriter.Formatting = Not Indentation
  196.  
  197.        Catch ex As System.Text.EncoderFallbackException
  198.            Dim errormsg As String = "There is a character in the buffer that is a valid XML character but is not valid for the output encoding."
  199.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  200.            ' MessageBox.Show(errormsg)
  201.  
  202.        Catch ex As InvalidOperationException
  203.            Dim errormsg As String = "The XmlTextWriter is closed or An XmlTextWriter method was called before a previous asynchronous operation finished."
  204.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  205.            ' MessageBox.Show(errormsg)
  206.  
  207.        Catch ex As Exception
  208.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  209.  
  210.        End Try
  211.  
  212.    End Sub
  213.  
  214.    ''' <summary>
  215.    ''' Writes multiple elements.
  216.    ''' </summary>
  217.    Shared Sub Write_Elements(ByVal XmlWriter As Xml.XmlTextWriter, _
  218.                                   ByVal Elements As String(,), _
  219.                                   Optional ByVal Indentation As Xml.Formatting = Xml.Formatting.Indented)
  220.  
  221.        Try
  222.  
  223.            XmlWriter.Formatting = Indentation
  224.  
  225.            For x As Integer = 0 To Elements.GetUpperBound(0)
  226.                XmlWriter.WriteStartElement(Elements(x, 0))
  227.                XmlWriter.WriteString(Elements(x, 1))
  228.                XmlWriter.WriteEndElement()
  229.            Next
  230.  
  231.            XmlWriter.Formatting = Not Indentation
  232.  
  233.        Catch ex As System.Text.EncoderFallbackException
  234.            Dim errormsg As String = "There is a character in the buffer that is a valid XML character but is not valid for the output encoding."
  235.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  236.            ' MessageBox.Show(errormsg)
  237.  
  238.        Catch ex As InvalidOperationException
  239.            Dim errormsg As String = "The XmlTextWriter is closed or An XmlTextWriter method was called before a previous asynchronous operation finished."
  240.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  241.            ' MessageBox.Show(errormsg)
  242.  
  243.        Catch ex As Exception
  244.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  245.  
  246.        End Try
  247.  
  248.    End Sub
  249.  
  250.    ''' <summary>
  251.    ''' Writes the xml end of file.
  252.    ''' </summary>
  253.    Shared Sub Write_End(ByVal XmlWriter As Xml.XmlTextWriter)
  254.  
  255.        Try
  256.            XmlWriter.WriteEndDocument()
  257.            XmlWriter.Close()
  258.  
  259.        Catch ex As ArgumentException
  260.            Dim errormsg As String = "The XML document is invalid."
  261.            Throw New Exception(errormsg & Environment.NewLine & ex.StackTrace)
  262.            ' MessageBox.Show(errormsg)
  263.  
  264.        Catch ex As Exception
  265.            Throw New Exception(ex.Message & Environment.NewLine & ex.StackTrace)
  266.  
  267.        End Try
  268.  
  269.    End Sub
  270.  
  271. End Class
  272.  
  273. #End Region


« Última modificación: 25 Octubre 2013, 17:43 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 #331 en: 1 Noviembre 2013, 14:56 pm »

Dado un número, devuelve el valor más próximo de un Enum.

Código
  1.    #Region " Get Nearest Enum Value "
  2.  
  3.       ' [ Get Nearest Enum Value ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       '
  9.       ' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
  10.       ' MsgBox(Get_Nearest_Enum_Value(Of Bitrate)(133).ToString) ' Result: kbps_128
  11.       ' MsgBox(Get_Nearest_Enum_Value(Of KnownColor)(1000)) ' Result: 174
  12.  
  13.    Private Function Get_Nearest_Enum_Value(Of T)(ByVal value As Long) As T
  14.  
  15.        Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  16.                                               Cast(Of Object).
  17.                                               OrderBy(Function(br) Math.Abs(value - br)).
  18.                                               First)
  19.  
  20.    End Function
  21.  
  22.    #End Region



Dado un número, devuelve el valor próximo más bajo de un Enum.

Código
  1.    #Region " Get Nearest Lower Enum Value "
  2.  
  3.       ' [ Get Nearest Lower Enum Value ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       '
  9.       ' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
  10.       ' MsgBox(Get_Nearest_Lower_Enum_Value(Of Bitrate)(190).ToString) ' Result: kbps_128
  11.       ' MsgBox(Get_Nearest_Lower_Enum_Value(Of Bitrate)(196).ToString) ' Result: kbps_192
  12.  
  13.    Private Function Get_Nearest_Lower_Enum_Value(Of T)(ByVal value As Integer) As T
  14.  
  15.        Select Case value
  16.  
  17.            Case Is < [Enum].GetValues(GetType(T)).Cast(Of Object).First
  18.                Return Nothing
  19.  
  20.            Case Else
  21.                Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  22.                                                       Cast(Of Object)().
  23.                                                       Where(Function(enum_value) enum_value <= value).
  24.                                                       Last)
  25.        End Select
  26.  
  27.    End Function
  28.  
  29.    #End Region




Dado un número, devuelve el valor próximo más alto de un Enum.

Código
  1.    #Region " Get Nearest Higher Enum Value "
  2.  
  3.       ' [ Get Nearest Higher Enum Value ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       '
  9.       ' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
  10.       ' MsgBox(Get_Nearest_Higher_Enum_Value(Of Bitrate)(196).ToString) ' Result: kbps_256
  11.       ' MsgBox(Get_Nearest_Higher_Enum_Value(Of KnownColor)(1000)) ' Result: 0
  12.  
  13.    Private Function Get_Nearest_Higher_Enum_Value(Of T)(ByVal value As Integer) As T
  14.  
  15.        Select Case value
  16.  
  17.            Case Is > [Enum].GetValues(GetType(T)).Cast(Of Object).Last
  18.                Return Nothing
  19.  
  20.            Case Else
  21.  
  22.                Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  23.                                                       Cast(Of Object).
  24.                                                       Where(Function(enum_value) enum_value >= value).
  25.                                                       FirstOrDefault)
  26.        End Select
  27.  
  28.    End Function
  29.  
  30.    #End Region

EDITO:

Aquí todos juntos:

Código
  1.    #Region " Get Nearest Enum Value "
  2.  
  3.        ' [ Get Nearest Enum Value ]
  4.        '
  5.        ' // By Elektro H@cker
  6.        '
  7.        ' Examples :
  8.        '
  9.        ' MsgBox(Get_Nearest_Enum_Value(Of Bitrate)(133, Enum_Direction.Nearest).ToString) ' Result: kbps_128
  10.        ' MsgBox(Get_Nearest_Enum_Value(Of KnownColor)(1000, Enum_Direction.Nearest)) ' Result: 174
  11.        '
  12.        ' MsgBox(Get_Nearest_Enum_Value(Of Bitrate)(190, Enum_Direction.Down).ToString) ' Result: kbps_128
  13.        ' MsgBox(Get_Nearest_Enum_Value(Of KnownColor)(-1, Enum_Direction.Down).ToString) ' Result: 0
  14.        '
  15.        ' MsgBox(Get_Nearest_Enum_Value(Of Bitrate)(196, Enum_Direction.Up).ToString) ' Result: kbps_256
  16.        ' MsgBox(Get_Nearest_Enum_Value(Of KnownColor)(1000, Enum_Direction.Up)) ' Result: 0
  17.  
  18.    Private Enum Enum_Direction As Short
  19.        Down = 1
  20.        Up = 2
  21.        Nearest = 0
  22.    End Enum
  23.  
  24.    Private Function Get_Nearest_Enum_Value(Of T)(ByVal value As Long, _
  25.                                                  Optional ByVal direction As Enum_Direction = Enum_Direction.Nearest) As T
  26.  
  27.        Select Case direction
  28.  
  29.            Case Enum_Direction.Nearest ' Return nearest Enum value
  30.                Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  31.                                                       Cast(Of Object).
  32.                                                       OrderBy(Function(br) Math.Abs(value - br)).
  33.                                                       First)
  34.  
  35.            Case Enum_Direction.Down ' Return nearest lower Enum value
  36.                If value < [Enum].GetValues(GetType(T)).Cast(Of Object).First Then
  37.                    Return Nothing
  38.                Else
  39.                    Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  40.                                                           Cast(Of Object)().
  41.                                                           Where(Function(enum_value) enum_value <= value).
  42.                                                           Last)
  43.                End If
  44.  
  45.            Case Enum_Direction.Up ' Return nearest higher Enum value
  46.                If value > [Enum].GetValues(GetType(T)).Cast(Of Object).Last Then
  47.                    Return Nothing
  48.                Else
  49.                    Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)).
  50.                                                           Cast(Of Object).
  51.                                                           Where(Function(enum_value) enum_value >= value).
  52.                                                           FirstOrDefault)
  53.                End If
  54.  
  55.        End Select
  56.  
  57.    End Function
  58.  
  59.    #End Region


« Última modificación: 1 Noviembre 2013, 15:36 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 #332 en: 10 Noviembre 2013, 21:04 pm »

· Juntar múltiples listas:

Código
  1. #Region " Join Lists "
  2.  
  3.    ' [ Join Lists ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim list_A As New List(Of String) From {"a", "b"}
  10.    ' Dim list_B As New List(Of String) From {"c", "d"}
  11.    ' Dim newlist As List(Of String) = Join_Lists(Of String)({list_A, list_B}) ' Result: {"a", "b", "c", "d"}
  12.  
  13.    Private Function Join_Lists(Of T)(ByVal Lists() As List(Of T)) As List(Of T)
  14.        Return Lists.SelectMany(Function(l) l).ToList
  15.    End Function
  16.  
  17. #End Region





· Revertir un Stack:

Código
  1. #Region " Reverse Stack "
  2.  
  3.    ' [ Reverse Stack ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim MyStack As New Stack(Of String)
  8.    '
  9.    ' MyStack.Push("S") : MyStack.Push("T") : MyStack.Push("A") : MyStack.Push("C") : MyStack.Push("K")
  10.    '
  11.    ' MyStack = Reverse_Stack(Of String)(MyStack)
  12.    '
  13.    ' For Each value In MyStack
  14.    '     MsgBox(value)
  15.    ' Next
  16.  
  17.    Private Function Reverse_Stack(Of T)(stack As Stack(Of T)) As Stack(Of T)
  18.        Return New Stack(Of T)(stack)
  19.    End Function
  20.  
  21. #End Region





· Eliminar las lineas vacias de un archivo de texto:

Código
  1. #Region " Delete Empty Lines In TextFile "
  2.  
  3.    ' [ Delete Empty Lines In TextFile ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Delete_Empty_Lines_In_TextFile("C:\File.txt")
  10.    ' Delete_Empty_Lines_In_TextFile("C:\File.txt", System.Text.Encoding.GetEncoding(1252))
  11.  
  12.    Private Sub Delete_Empty_Lines_In_TextFile(ByVal file As String, _
  13.                                               Optional ByVal encoding As System.Text.Encoding = Nothing)
  14.  
  15.        IO.File.WriteAllLines(file, IO.File.ReadAllLines(file) _
  16.                                    .Where(Function(line) Not String.IsNullOrEmpty(line)) _
  17.                                    , If(encoding Is Nothing, System.Text.Encoding.Default, encoding))
  18.  
  19.    End Sub
  20.  
  21. #End Region




Y por último esta Class para dockear un Form,
le añadí lo necesario para poder bloquear la posición del form (no el tamaño, me parece irrelevante).

Código
  1. ' [ Form Dock ]
  2. '
  3. ' // By Elektro H@cker
  4.  
  5. #Region " Usage Examples "
  6.  
  7. ' Private _formdock As New FormDock(Me) With {.LockPosition = True}
  8. '
  9. ' Private Shadows Sub Shown() Handles MyBase.Shown
  10. '
  11. '   _formdock.Dock(FormDock.DockPosition.WorkingArea_BottomRight)
  12. '
  13. ' End Sub
  14.  
  15. #End Region
  16.  
  17. #Region " Form Dock "
  18.  
  19. Public Class FormDock
  20.    Inherits NativeWindow
  21.    Implements IDisposable
  22.  
  23. #Region " Variables, Properties and Enumerations "
  24.  
  25.    ''' <summary>
  26.    ''' While the property still Enabled it will locks the formulary position.
  27.    ''' </summary>
  28.    Public Property LockPosition As Boolean = False
  29.  
  30.    ''' <summary>
  31.    ''' Stores the formulary to Dock.
  32.    ''' </summary>
  33.    Private WithEvents form As Form = Nothing
  34.  
  35.    ''' <summary>
  36.    ''' Stores the size of the formulary to Dock.
  37.    ''' </summary>
  38.    Private UI_Size As Size = Nothing
  39.  
  40.    ''' <summary>
  41.    ''' Stores the Dock positions.
  42.    ''' </summary>
  43.    Private Dock_Positions As Dictionary(Of DockPosition, Point)
  44.  
  45.    ''' <summary>
  46.    ''' Dock Positions.
  47.    ''' </summary>
  48.    Public Enum DockPosition As Short
  49.        Center_Screen = 0
  50.        Bounds_BottomLeft = 1
  51.        Bounds_BottomRight = 2
  52.        Bounds_TopLeft = 3
  53.        Bounds_TopRight = 4
  54.        WorkingArea_BottomLeft = 5
  55.        WorkingArea_BottomRight = 6
  56.        WorkingArea_TopLeft = 7
  57.        WorkingArea_TopRight = 8
  58.    End Enum
  59.  
  60. #End Region
  61.  
  62. #Region " New Constructor "
  63.  
  64.    Public Sub New(ByVal form As Form)
  65.  
  66.        Me.form = form
  67.        SetHandle()
  68.  
  69.    End Sub
  70.  
  71. #End Region
  72.  
  73. #Region " Public Procedures "
  74.  
  75.    ''' <summary>
  76.    ''' Docks the form.
  77.    ''' </summary>
  78.    Public Sub Dock(ByVal Position As DockPosition)
  79.  
  80.        If Dock_Positions Is Nothing Then
  81.            Renew_Positions(form)
  82.        End If
  83.  
  84.        form.Location = Dock_Positions(Position)
  85.  
  86.    End Sub
  87.  
  88. #End Region
  89.  
  90. #Region " Miscellaneous Procedures "
  91.  
  92.    ''' <summary>
  93.    ''' Renews the Dock positions according to the the current form Size.
  94.    ''' </summary>
  95.    Private Sub Renew_Positions(ByVal form As Form)
  96.  
  97.        UI_Size = form.Size
  98.  
  99.        Dock_Positions = New Dictionary(Of DockPosition, Point) _
  100.        From {
  101.                 {DockPosition.Center_Screen,
  102.                               New Point((Screen.PrimaryScreen.Bounds.Width - UI_Size.Width) \ 2,
  103.                                         (Screen.PrimaryScreen.Bounds.Height - UI_Size.Height) \ 2)},
  104.                 {DockPosition.Bounds_BottomLeft,
  105.                               New Point(Screen.PrimaryScreen.Bounds.X,
  106.                                         Screen.PrimaryScreen.Bounds.Height - UI_Size.Height)},
  107.                 {DockPosition.Bounds_BottomRight,
  108.                           New Point(Screen.PrimaryScreen.Bounds.Width - UI_Size.Width,
  109.                                     Screen.PrimaryScreen.Bounds.Height - UI_Size.Height)},
  110.                 {DockPosition.Bounds_TopLeft,
  111.                               New Point(Screen.PrimaryScreen.Bounds.X,
  112.                                         Screen.PrimaryScreen.Bounds.Y)},
  113.                 {DockPosition.Bounds_TopRight,
  114.                               New Point(Screen.PrimaryScreen.Bounds.Width - UI_Size.Width,
  115.                                         Screen.PrimaryScreen.Bounds.Y)},
  116.                 {DockPosition.WorkingArea_BottomLeft,
  117.                               New Point(Screen.PrimaryScreen.WorkingArea.X,
  118.                                         Screen.PrimaryScreen.WorkingArea.Height - UI_Size.Height)},
  119.                 {DockPosition.WorkingArea_BottomRight,
  120.                               New Point(Screen.PrimaryScreen.WorkingArea.Width - UI_Size.Width,
  121.                                         Screen.PrimaryScreen.WorkingArea.Height - UI_Size.Height)},
  122.                 {DockPosition.WorkingArea_TopLeft,
  123.                               New Point(Screen.PrimaryScreen.WorkingArea.X,
  124.                                         Screen.PrimaryScreen.WorkingArea.Y)},
  125.                 {DockPosition.WorkingArea_TopRight,
  126.                               New Point(Screen.PrimaryScreen.WorkingArea.Width - UI_Size.Width,
  127.                                         Screen.PrimaryScreen.WorkingArea.Y)}
  128.            }
  129.  
  130.    End Sub
  131.  
  132. #End Region
  133.  
  134. #Region " Form EventHandlers "
  135.  
  136.    ''' <summary>
  137.    ''' Renews the Dock positions according to the the current form Size,
  138.    ''' when Form is Shown.
  139.    ''' </summary>
  140.    Private Sub OnShown() _
  141.    Handles form.Shown
  142.  
  143.        If Not UI_Size.Equals(Me.form.Size) Then
  144.            Renew_Positions(Me.form)
  145.        End If
  146.  
  147.    End Sub
  148.  
  149.    ''' <summary>
  150.    ''' Renews the Dock positions according to the the current form Size,
  151.    ''' When Form is resized.
  152.    ''' </summary>
  153.    Private Sub OnResizeEnd() _
  154.    Handles form.ResizeEnd
  155.  
  156.        If Not UI_Size.Equals(Me.form.Size) Then
  157.            Renew_Positions(Me.form)
  158.        End If
  159.  
  160.    End Sub
  161.  
  162.    ''' <summary>
  163.    ''' SetHandle
  164.    ''' Assign the handle of the target form to this NativeWindow,
  165.    ''' necessary to override WndProc.
  166.    ''' </summary>
  167.    Private Sub SetHandle() Handles _
  168.        form.HandleCreated,
  169.        form.Load,
  170.        form.Shown
  171.  
  172.        Try
  173.            If Not Me.Handle.Equals(Me.form.Handle) Then
  174.                Me.AssignHandle(Me.form.Handle)
  175.            End If
  176.        Catch ex As InvalidOperationException
  177.        End Try
  178.  
  179.    End Sub
  180.  
  181.    ''' <summary>
  182.    ''' Releases the Handle.
  183.    ''' </summary>
  184.    Private Sub OnHandleDestroyed() _
  185.    Handles form.HandleDestroyed
  186.  
  187.        Me.ReleaseHandle()
  188.  
  189.    End Sub
  190.  
  191. #End Region
  192.  
  193. #Region " Windows Messages "
  194.  
  195.    ''' <summary>
  196.    ''' WndProc Message Interception.
  197.    ''' </summary>
  198.    Protected Overrides Sub WndProc(ByRef m As Message)
  199.  
  200.        If Me.LockPosition Then
  201.  
  202.            Select Case m.Msg
  203.  
  204.                Case &HA1
  205.                    ' Cancels any attempt to drag the window by it's caption.
  206.                    If m.WParam.ToInt32 = &H2 Then Return
  207.  
  208.                Case &H112
  209.                    ' Cancels any clicks on the Move system menu item.
  210.                    If (m.WParam.ToInt32 And &HFFF0) = &HF010& Then Return
  211.  
  212.            End Select
  213.  
  214.        End If
  215.  
  216.        ' Return control to base message handler.
  217.        MyBase.WndProc(m)
  218.  
  219.    End Sub
  220.  
  221. #End Region
  222.  
  223. #Region " IDisposable "
  224.  
  225.    ''' <summary>
  226.    ''' Disposes the objects generated by this instance.
  227.    ''' </summary>
  228.    Public Sub Dispose() Implements IDisposable.Dispose
  229.        Dispose(True)
  230.        GC.SuppressFinalize(Me)
  231.    End Sub
  232.  
  233.    Protected Overridable Sub Dispose(IsDisposing As Boolean)
  234.  
  235.        Static IsBusy As Boolean ' To detect redundant calls.
  236.  
  237.        If Not IsBusy AndAlso IsDisposing Then
  238.  
  239.            Me.LockPosition = False
  240.            Me.ReleaseHandle()
  241.  
  242.        End If
  243.  
  244.        IsBusy = True
  245.  
  246.    End Sub
  247.  
  248. #End Region
  249.  
  250. End Class
  251.  
  252. #End Region
« Última modificación: 11 Noviembre 2013, 16:38 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 #333 en: 11 Noviembre 2013, 01:15 am »

Una nueva versión de mi Listview, que tiene muchas cosas interesantes como poder dibujar una barra de progreso en una celda...

Ahora le añadí lo básico para hacer undo/redo para añadir o eliminar items.

Una pequeña demostración:



Un ejemplo de uso:

Código
  1. Public Class Form1
  2.  
  3.    Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  4.  
  5.        ' Enable the Undo/Redo Manager
  6.        ListView_Elektro1.Enable_UndoRedo_Manager = True
  7.  
  8.        ' Create an Item
  9.        Dim LVItem As New ListViewItem With {.Text = "Hello World"}
  10.  
  11.        ' Add the item
  12.        ListView_Elektro1.AddItem(LVItem)
  13.  
  14.        ' Remove the item
  15.        'ListView_Elektro1.RemoveItem(LVItem)
  16.  
  17.    End Sub
  18.  
  19.    ' Undo an operation
  20.    Private Sub Button_Undo_Click(sender As Object, e As EventArgs) Handles Button_Undo.Click
  21.        ListView_Elektro1.Undo()
  22.    End Sub
  23.  
  24.    ' Redo an operation
  25.    Private Sub Button_Redo_Click(sender As Object, e As EventArgs) Handles Button_Redo.Click
  26.        ListView_Elektro1.Redo()
  27.    End Sub
  28.  
  29.    ' Handles when an Undo or Redo operation is performed
  30.    Private Sub UndoRedo_Performed(sender As Object, e As ListView_Elektro.UndoneRedoneEventArgs) _
  31.    Handles ListView_Elektro1.UndoRedo_IsPerformed
  32.  
  33.        MsgBox(e.Operation.ToString)
  34.        MsgBox(e.Method.ToString)
  35.        MsgBox(e.Item.Text)
  36.  
  37.    End Sub
  38.  
  39.    ' Handles when a Undo or Redo stack size changed
  40.    Private Sub UndoRedo_StackSizeChanged(sender As Object, e As ListView_Elektro.StackSizeChangedEventArgs) _
  41.    Handles ListView_Elektro1.UndoRedo_StackSizeChanged
  42.  
  43.        MsgBox(e.UndoStackIsEmpty)
  44.        MsgBox(e.RedoStackIsEmpty)
  45.  
  46.    End Sub
  47.  
  48. End Class


El código completo del UserControl listo para ser compilado:

Código
  1. '  /*                  *\
  2. ' |#* ListView Elektro *#|
  3. '  \*                  */
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. '   Properties:
  8. '   -----------
  9. ' · Disable_Flickering
  10. ' · Double_Buffer
  11. ' · GridLineColor
  12. ' · ItemHighlightColor
  13. ' · ItemNotFocusedHighlighColor
  14. ' · DrawCustomGridLines
  15. ' · UseDefaultGridLines
  16. ' · Enable_ProgressBar
  17. ' · Progressbar_Column
  18. ' · ProgressBar_BackColor
  19. ' · ProgressBar_BorderColor
  20. ' · ProgressBar_FillColor1
  21. ' · ProgressBar_FillColor2
  22. ' · Percent
  23. ' · Percent_Decimal
  24. ' · Percent_Font
  25. ' · Percent_Text
  26. ' · Percent_Forecolor
  27. ' · Percent_Text_Allignment
  28. ' · Enable_UndoRedo_Manager
  29.  
  30. '   Events:
  31. '   -------
  32. ' · ItemAdded
  33. ' · ItemRemoved
  34. ' · UndoRedo_IsPerformed
  35. ' · UndoRedo_StackSizeChanged
  36. '
  37. '   Methods:
  38. '   --------
  39. ' · AddItem
  40. ' · AddItems
  41. ' · RemoveItem
  42. ' · RemoveItems
  43. ' · Undo
  44. ' · Redo
  45.  
  46. Public Class ListView_Elektro : Inherits ListView
  47.  
  48.    Public Event ItemAdded As EventHandler(Of ItemAddedEventArgs)
  49.    Public Class ItemAddedEventArgs : Inherits EventArgs
  50.        Property Item As ListViewItem
  51.    End Class
  52.  
  53.    Public Event ItemRemoved As EventHandler(Of ItemRemovedEventArgs)
  54.    Public Class ItemRemovedEventArgs : Inherits EventArgs
  55.        Property Item As ListViewItem
  56.    End Class
  57.  
  58.    Private _Disable_Flickering As Boolean = True
  59.    Private _gridLines As Boolean = False
  60.    Private _useDefaultGridLines As Boolean = False
  61.    Private _gridLineColor As Color = Color.Black
  62.    Private _itemHighlightColor As Color = Color.FromKnownColor(KnownColor.Highlight)
  63.    Private _itemNotFocusedHighlighColor As Color = Color.FromKnownColor(KnownColor.MenuBar)
  64.  
  65.    Private _enable_progressbar As Boolean = False
  66.    Private _progressbar_column As Integer = Nothing
  67.  
  68.    Private _percent As Double = 0
  69.    Private _percent_decimal As Short = 2
  70.    Private _percent_text As String = "%"
  71.    Private _percent_text_allignment As StringAlignment = StringAlignment.Center
  72.    Private _percent_stringformat As StringFormat = New StringFormat With {.Alignment = _percent_text_allignment}
  73.    Private _percent_font As Font = Me.Font
  74.    Private _percent_forecolor As SolidBrush = New SolidBrush(Color.Black)
  75.  
  76.    Private _progressBar_backcolor As SolidBrush = New SolidBrush(Color.Red)
  77.    Private _progressBar_bordercolor As Pen = New Pen(Color.LightGray)
  78.    Private _progressBar_fillcolor1 As Color = Color.YellowGreen
  79.    Private _progressBar_fillcolor2 As Color = Color.White
  80.  
  81.    Public Sub New()
  82.  
  83.        Me.Name = "ListView_Elektro"
  84.        Me.DoubleBuffered = True
  85.        Me.UseDefaultGridLines = True
  86.  
  87.        ' Set Listview OwnerDraw to True, so we can draw the progressbar inside.
  88.        If Me.Enable_ProgressBar Then Me.OwnerDraw = True
  89.  
  90.        Me.GridLines = True
  91.        Me.FullRowSelect = True
  92.        Me.MultiSelect = True
  93.        Me.View = View.Details
  94.  
  95.    End Sub
  96.  
  97. #Region " Properties "
  98.  
  99.    ''' <summary>
  100.    ''' Enable/Disable any flickering effect on the ListView.
  101.    ''' </summary>
  102.    Protected Overrides ReadOnly Property CreateParams() As CreateParams
  103.        Get
  104.            If _Disable_Flickering Then
  105.                Dim cp As CreateParams = MyBase.CreateParams
  106.                cp.ExStyle = cp.ExStyle Or &H2000000
  107.                Return cp
  108.            Else
  109.                Return MyBase.CreateParams
  110.            End If
  111.        End Get
  112.    End Property
  113.  
  114.    ''' <summary>
  115.    ''' Set the Double Buffer.
  116.    ''' </summary>
  117.    Public Property Double_Buffer() As Boolean
  118.        Get
  119.            Return Me.DoubleBuffered
  120.        End Get
  121.        Set(ByVal Value As Boolean)
  122.            Me.DoubleBuffered = Value
  123.        End Set
  124.    End Property
  125.  
  126.    ''' <summary>
  127.    ''' Enable/Disable the flickering effects on this ListView.
  128.    '''
  129.    ''' This property turns off any Flicker effect on the ListView
  130.    ''' ...but also reduces the performance (speed) of the ListView about 30% slower.
  131.    ''' This don't affect to the performance of the application itself, only to the performance of this control.
  132.    ''' </summary>
  133.    Public Property Disable_Flickering() As Boolean
  134.        Get
  135.            Return _Disable_Flickering
  136.        End Get
  137.        Set(ByVal Value As Boolean)
  138.            Me._Disable_Flickering = Value
  139.        End Set
  140.    End Property
  141.  
  142.    ''' <summary>
  143.    ''' Changes the gridline color.
  144.    ''' </summary>
  145.    Public Property GridLineColor() As Color
  146.        Get
  147.            Return _gridLineColor
  148.        End Get
  149.        Set(ByVal value As Color)
  150.            If value <> _gridLineColor Then
  151.                _gridLineColor = value
  152.                If _gridLines Then
  153.                    Me.Invalidate()
  154.                End If
  155.            End If
  156.        End Set
  157.    End Property
  158.  
  159.    ''' <summary>
  160.    ''' Changes the color when item is highlighted.
  161.    ''' </summary>
  162.    Public Property ItemHighlightColor() As Color
  163.        Get
  164.            Return _itemHighlightColor
  165.        End Get
  166.        Set(ByVal value As Color)
  167.            If value <> _itemHighlightColor Then
  168.                _itemHighlightColor = value
  169.                Me.Invalidate()
  170.            End If
  171.        End Set
  172.    End Property
  173.  
  174.    ''' <summary>
  175.    ''' Changes the color when the item is not focused.
  176.    ''' </summary>
  177.    Public Property ItemNotFocusedHighlighColor() As Color
  178.        Get
  179.            Return _itemNotFocusedHighlighColor
  180.        End Get
  181.        Set(ByVal value As Color)
  182.            If value <> _itemNotFocusedHighlighColor Then
  183.                _itemNotFocusedHighlighColor = value
  184.                Me.Invalidate()
  185.            End If
  186.        End Set
  187.    End Property
  188.  
  189.    Private ReadOnly Property DrawCustomGridLines() As Boolean
  190.        Get
  191.            Return (_gridLines And Not _useDefaultGridLines)
  192.        End Get
  193.    End Property
  194.  
  195.    Public Shadows Property GridLines() As Boolean
  196.        Get
  197.            Return _gridLines
  198.        End Get
  199.        Set(ByVal value As Boolean)
  200.            _gridLines = value
  201.        End Set
  202.    End Property
  203.  
  204.    ''' <summary>
  205.    ''' use the default gridlines.
  206.    ''' </summary>
  207.    Public Property UseDefaultGridLines() As Boolean
  208.        Get
  209.            Return _useDefaultGridLines
  210.        End Get
  211.        Set(ByVal value As Boolean)
  212.            If _useDefaultGridLines <> value Then
  213.                _useDefaultGridLines = value
  214.            End If
  215.            MyBase.GridLines = value
  216.            MyBase.OwnerDraw = Not value
  217.        End Set
  218.    End Property
  219. #End Region
  220.  
  221. #Region " Procedures "
  222.  
  223.    ''' <summary>
  224.    ''' Adds an Item to the ListView,
  225.    ''' to monitor when an Item is added to the ListView.
  226.    ''' </summary>
  227.    Public Function AddItem(ByVal Item As ListViewItem) As ListViewItem
  228.        Me.Items.Add(Item)
  229.        RaiseEvent ItemAdded(Me, New ItemAddedEventArgs With {.Item = Item})
  230.        Return Item
  231.    End Function
  232.    Public Function AddItem(ByVal Text As String) As ListViewItem
  233.        Dim NewItem As New ListViewItem(Text)
  234.        Me.Items.Add(NewItem)
  235.        RaiseEvent ItemAdded(Me, New ItemAddedEventArgs With {.Item = NewItem})
  236.        Return NewItem
  237.    End Function
  238.  
  239.    ''' <summary>
  240.    ''' Removes an Item from the ListView
  241.    ''' to monitor when an Item is removed from the ListView.
  242.    ''' </summary>
  243.    Public Sub RemoveItem(ByVal Item As ListViewItem)
  244.        Me.Items.Remove(Item)
  245.        RaiseEvent ItemRemoved(Me, New ItemRemovedEventArgs With {.Item = Item})
  246.    End Sub
  247.  
  248.    ''' <summary>
  249.    ''' Removes an Item from the ListView at given Index
  250.    ''' to monitor when an Item is removed from the ListView.
  251.    ''' </summary>
  252.    Public Sub RemoveItem_At(ByVal Index As Integer)
  253.        RemoveItem(Me.Items.Item(Index))
  254.    End Sub
  255.  
  256.    ''' <summary>
  257.    ''' Removes an Item from the ListView at given Index
  258.    ''' to monitor when an Item is removed from the ListView.
  259.    ''' </summary>
  260.    Public Sub RemoveItems_At(ByVal Indexes As Integer())
  261.        Array.Sort(Indexes)
  262.        Array.Reverse(Indexes)
  263.        For Each Index As Integer In Indexes
  264.            RemoveItem(Me.Items.Item(Index))
  265.        Next
  266.    End Sub
  267.  
  268.    ''' <summary>
  269.    ''' Adds a range of Items to the ListView,
  270.    ''' to monitor when an Item is added to the ListView.
  271.    ''' </summary>
  272.    Public Sub AddItems(ByVal Items As ListViewItem())
  273.        For Each item As ListViewItem In Items
  274.            AddItem(item)
  275.        Next
  276.    End Sub
  277.    Public Sub AddItems(ByVal Items As ListViewItemCollection)
  278.        For Each item As ListViewItem In Items
  279.            AddItem(item)
  280.        Next
  281.    End Sub
  282.  
  283.    ''' <summary>
  284.    ''' Removes a range of Items from the ListView
  285.    ''' to monitor when an Item is removed from the ListView.
  286.    ''' </summary>
  287.    Public Sub RemoveItems(ByVal Items As ListViewItem())
  288.        For Each item As ListViewItem In Items
  289.            RemoveItem(item)
  290.        Next
  291.    End Sub
  292.    Public Sub RemoveItems(ByVal Items As ListViewItemCollection)
  293.        For Each item As ListViewItem In Items
  294.            RemoveItem(item)
  295.        Next
  296.    End Sub
  297.    Public Sub RemoveItems(ByVal Items As SelectedListViewItemCollection)
  298.        For Each item As ListViewItem In Items
  299.            RemoveItem(item)
  300.        Next
  301.    End Sub
  302.  
  303.    Protected Overrides Sub OnDrawColumnHeader(ByVal e As System.Windows.Forms.DrawListViewColumnHeaderEventArgs)
  304.        e.DrawDefault = True
  305.        MyBase.OnDrawColumnHeader(e)
  306.    End Sub
  307.  
  308.    Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
  309.        For Each selectedIndex As Integer In MyBase.SelectedIndices
  310.            MyBase.RedrawItems(selectedIndex, selectedIndex, False)
  311.        Next
  312.        MyBase.OnLostFocus(e)
  313.    End Sub
  314.  
  315.    Protected Overrides Sub OnDrawSubItem(ByVal e As System.Windows.Forms.DrawListViewSubItemEventArgs)
  316.  
  317.        Dim drawAsDefault As Boolean = False
  318.        Dim highlightBounds As Rectangle = Nothing
  319.        Dim highlightBrush As SolidBrush = Nothing
  320.  
  321.        'FIRST DETERMINE THE COLOR
  322.        If e.Item.Selected Then
  323.            If MyBase.Focused Then
  324.                highlightBrush = New SolidBrush(_itemHighlightColor)
  325.            ElseIf HideSelection Then
  326.                drawAsDefault = True
  327.            Else
  328.                highlightBrush = New SolidBrush(_itemNotFocusedHighlighColor)
  329.            End If
  330.        Else
  331.            drawAsDefault = True
  332.        End If
  333.  
  334.        If drawAsDefault Then
  335.            e.DrawBackground()
  336.        Else
  337.            'NEXT DETERMINE THE BOUNDS IN WHICH TO DRAW THE BACKGROUND
  338.            If FullRowSelect Then
  339.                highlightBounds = e.Bounds
  340.            Else
  341.                highlightBounds = e.Item.GetBounds(ItemBoundsPortion.Label)
  342.            End If
  343.  
  344.            'ONLY DRAW HIGHLIGHT IN 1 OF 2 CASES
  345.            'CASE 1 - FULL ROW SELECT (AND DRAWING ANY ITEM)
  346.            'CASE 2 - NOT FULL ROW SELECT (AND DRAWING 1ST ITEM)
  347.            If FullRowSelect Then
  348.                e.Graphics.FillRectangle(highlightBrush, highlightBounds)
  349.            ElseIf e.ColumnIndex = 0 Then
  350.                e.Graphics.FillRectangle(highlightBrush, highlightBounds)
  351.            Else
  352.                e.DrawBackground()
  353.            End If
  354.        End If
  355.  
  356.        e.DrawText()
  357.  
  358.        If _gridLines Then
  359.            e.Graphics.DrawRectangle(New Pen(_gridLineColor), e.Bounds)
  360.        End If
  361.  
  362.  
  363.        If FullRowSelect Then
  364.            e.DrawFocusRectangle(e.Item.GetBounds(ItemBoundsPortion.Entire))
  365.        Else
  366.            e.DrawFocusRectangle(e.Item.GetBounds(ItemBoundsPortion.Label))
  367.        End If
  368.  
  369.        MyBase.OnDrawSubItem(e)
  370.  
  371.    End Sub
  372.  
  373. #End Region
  374.  
  375. #Region " ProgressBar Properties "
  376.  
  377.    ''' <summary>
  378.    ''' Enables the drawing of a ProgressBar
  379.    ''' This property should be "True" to use any of the ProgressBar properties.
  380.    ''' </summary>
  381.    Public Property Enable_ProgressBar As Boolean
  382.        Get
  383.            Return _enable_progressbar
  384.        End Get
  385.        Set(ByVal value As Boolean)
  386.            Me.OwnerDraw = value
  387.            _enable_progressbar = value
  388.        End Set
  389.    End Property
  390.  
  391.    ''' <summary>
  392.    ''' The column index to draw the ProgressBar
  393.    ''' </summary>
  394.    Public Property Progressbar_Column As Integer
  395.        Get
  396.            Return _progressbar_column
  397.        End Get
  398.        Set(ByVal value As Integer)
  399.            _progressbar_column = value
  400.        End Set
  401.    End Property
  402.  
  403.    ''' <summary>
  404.    ''' The ProgressBar progress percentage
  405.    ''' </summary>
  406.    Public Property Percent As Double
  407.        Get
  408.            Return _percent
  409.        End Get
  410.        Set(ByVal value As Double)
  411.            _percent = value
  412.        End Set
  413.    End Property
  414.  
  415.    ''' <summary>
  416.    ''' The decimal factor which should be displayed for the ProgressBar progress percentage
  417.    ''' </summary>
  418.    Public Property Percent_Decimal As Short
  419.        Get
  420.            Return _percent_decimal
  421.        End Get
  422.        Set(ByVal value As Short)
  423.            _percent_decimal = value
  424.        End Set
  425.    End Property
  426.  
  427.    ''' <summary>
  428.    ''' The Font to be used as the ProgressBar Percent text
  429.    ''' </summary>
  430.    Public Property Percent_Font As Font
  431.        Get
  432.            Return _percent_font
  433.        End Get
  434.        Set(ByVal value As Font)
  435.            _percent_font = value
  436.        End Set
  437.    End Property
  438.  
  439.    ''' <summary>
  440.    ''' The additional text to add to the ProgressBar Percent value
  441.    ''' </summary>
  442.    Public Property Percent_Text As String
  443.        Get
  444.            Return _percent_text
  445.        End Get
  446.        Set(ByVal value As String)
  447.            _percent_text = value
  448.        End Set
  449.    End Property
  450.  
  451.    ''' <summary>
  452.    ''' The ForeColor of the ProgressBar Percent Text
  453.    ''' </summary>
  454.    Public Property Percent_Forecolor As Color
  455.        Get
  456.            Return _percent_forecolor.Color
  457.        End Get
  458.        Set(ByVal value As Color)
  459.            _percent_forecolor = New SolidBrush(value)
  460.        End Set
  461.    End Property
  462.  
  463.    ''' <summary>
  464.    ''' The text allignment to use for the ProgressBar
  465.    ''' </summary>
  466.    Public Property Percent_Text_Allignment As StringAlignment
  467.        Get
  468.            Return _percent_stringformat.Alignment
  469.        End Get
  470.        Set(ByVal value As StringAlignment)
  471.            _percent_stringformat.Alignment = value
  472.        End Set
  473.    End Property
  474.  
  475.    ''' <summary>
  476.    ''' The ProgressBar BackColor
  477.    ''' </summary>
  478.    Public Property ProgressBar_BackColor As Color
  479.        Get
  480.            Return _progressBar_backcolor.Color
  481.        End Get
  482.        Set(ByVal value As Color)
  483.            _progressBar_backcolor = New SolidBrush(value)
  484.        End Set
  485.    End Property
  486.  
  487.    ''' <summary>
  488.    ''' The ProgressBar BorderColor
  489.    ''' </summary>
  490.    Public Property ProgressBar_BorderColor As Color
  491.        Get
  492.            Return _progressBar_bordercolor.Color
  493.        End Get
  494.        Set(ByVal value As Color)
  495.            _progressBar_bordercolor = New Pen(value)
  496.        End Set
  497.    End Property
  498.  
  499.    ''' <summary>
  500.    ''' The First ProgressBar Gradient color
  501.    ''' </summary>
  502.    Public Property ProgressBar_FillColor1 As Color
  503.        Get
  504.            Return _progressBar_fillcolor1
  505.        End Get
  506.        Set(ByVal value As Color)
  507.            _progressBar_fillcolor1 = value
  508.        End Set
  509.    End Property
  510.  
  511.    ''' <summary>
  512.    ''' The Last ProgressBar Gradient color
  513.    ''' </summary>
  514.    Public Property ProgressBar_FillColor2 As Color
  515.        Get
  516.            Return _progressBar_fillcolor2
  517.        End Get
  518.        Set(ByVal value As Color)
  519.            _progressBar_fillcolor2 = value
  520.        End Set
  521.    End Property
  522.  
  523. #End Region
  524.  
  525. #Region " ProgressBar EventHandlers "
  526.  
  527.    ' ListView [DrawColumnHeader]
  528.    Public Sub Me_DrawColumnHeader(ByVal sender As Object, ByVal e As DrawListViewColumnHeaderEventArgs) _
  529.    Handles Me.DrawColumnHeader
  530.  
  531.        e.DrawDefault = True ' Draw default ColumnHeader.
  532.  
  533.    End Sub
  534.  
  535.    ' ListView [DrawItem]
  536.    Public Sub Me_DrawItem(ByVal sender As Object, ByVal e As DrawListViewItemEventArgs) _
  537.    Handles Me.DrawItem
  538.  
  539.        e.DrawDefault = False ' Draw default main item.
  540.  
  541.    End Sub
  542.  
  543.    ' ListView [DrawSubItem]
  544.    Public Sub Me_DrawSubItem(ByVal sender As Object, ByVal e As DrawListViewSubItemEventArgs) _
  545.    Handles Me.DrawSubItem
  546.  
  547.        If Not Enable_ProgressBar OrElse Progressbar_Column = Nothing Then
  548.            Exit Sub
  549.        End If
  550.  
  551.        ' Item is highlighted.
  552.        ' If (e.ItemState And ListViewItemStates.Selected) <> 0 Then
  553.        '     e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds)
  554.        ' End If
  555.  
  556.        ' Draw the progressbar.
  557.        If e.ColumnIndex = Progressbar_Column Then
  558.  
  559.            ' Background color of the progressbar.
  560.            e.Graphics.FillRectangle(_progressBar_backcolor, e.Bounds)
  561.  
  562.            ' Gradient to fill the progressbar.
  563.            Dim brGradient As Brush = _
  564.                New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), _
  565.                                                                 ProgressBar_FillColor1, ProgressBar_FillColor2, 270, True)
  566.            ' Draw the actual progressbar.
  567.            e.Graphics.FillRectangle(brGradient, _
  568.                                     e.Bounds.X + 1, e.Bounds.Y + 2, _
  569.                                     CInt(((Percent) / 100) * (e.Bounds.Width - 2)), e.Bounds.Height - 3)
  570.  
  571.            ' Draw the percentage number and percent sign.
  572.            e.Graphics.DrawString(Percent.ToString("n" & Percent_Decimal) & Percent_Text, _
  573.                                  Percent_Font, _percent_forecolor, _
  574.                                  CSng(e.Bounds.X + (e.Bounds.Width / 2)), e.Bounds.Y + 3, _
  575.                                  _percent_stringformat)
  576.  
  577.            ' Draw a light gray rectangle/border around the progressbar.
  578.            e.Graphics.DrawRectangle(_progressBar_bordercolor, _
  579.                                     e.Bounds.X, e.Bounds.Y + 1, _
  580.                                     e.Bounds.Width - 1, e.Bounds.Height - 2)
  581.        Else
  582.  
  583.            ' e.DrawDefault = True
  584.  
  585.        End If
  586.  
  587.    End Sub
  588.  
  589. #End Region
  590.  
  591. #Region " Undo/Redo Manager "
  592.  
  593.    ''' <summary>
  594.    ''' Enable or disble the Undo/Redo monitoring.
  595.    ''' </summary>
  596.    Public Property Enable_UndoRedo_Manager As Boolean = False
  597.  
  598.    ' Stacks to store Undo/Redo actions.
  599.    Public Undostack As New Stack(Of ListView_Action)
  600.    Public Redostack As New Stack(Of ListView_Action)
  601.  
  602.    ' Flags to check if it is doing a Undo/Redo operation.
  603.    Private IsDoingUndo As Boolean = False
  604.    Private IsDoingRedo As Boolean = False
  605.  
  606.    ' Delegate to Add an Item for Undo/Redo operations.
  607.    Private Delegate Sub AddDelegate(item As ListViewItem)
  608.  
  609.    ' Delegate to Remove an Item for Undo/Redo operations.
  610.    Private Delegate Sub RemoveDelegate(item As ListViewItem)
  611.  
  612.    ' The Undo/Redo action.
  613.    Private action As ListView_Action = Nothing
  614.  
  615.    ' The operation.
  616.    Public Enum Operation As Short
  617.        Undo = 0
  618.        Redo = 1
  619.    End Enum
  620.  
  621.    ' The method for the Undo/Redo operation.
  622.    Public Enum Method As Short
  623.        Add = 0
  624.        Remove = 1
  625.    End Enum
  626.  
  627.    ''' <summary>
  628.    ''' Creates a Undo/Redo Action.
  629.    ''' </summary>
  630.    Class ListView_Action
  631.  
  632.        ''' <summary>
  633.        ''' Names the Undo/Redo Action.
  634.        ''' </summary>
  635.        Property Name As String
  636.  
  637.        ''' <summary>
  638.        ''' Points to a method to excecute.
  639.        ''' </summary>
  640.        Property Operation As [Delegate]
  641.  
  642.        ''' <summary>
  643.        ''' Method of the Undo/Redo operation.
  644.        ''' </summary>
  645.        Property Method As Method
  646.  
  647.        ''' <summary>
  648.        ''' Data Array for the method to excecute.
  649.        ''' </summary>
  650.        Property Data As ListViewItem
  651.  
  652.    End Class
  653.  
  654.    ''' <summary>
  655.    ''' This event is raised after an Undo/Redo action is performed.
  656.    ''' </summary>
  657.    Public Event UndoRedo_IsPerformed As EventHandler(Of UndoneRedoneEventArgs)
  658.    Public Class UndoneRedoneEventArgs : Inherits EventArgs
  659.        Property Operation As Operation
  660.        Property Method As Method
  661.        Property Item As ListViewItem
  662.        Property UndoStack As Stack(Of ListView_Action)
  663.        Property RedoStack As Stack(Of ListView_Action)
  664.    End Class
  665.  
  666.    ''' <summary>
  667.    ''' This event is raised when Undo/Redo Stack size changed.
  668.    ''' </summary>
  669.    Public Event UndoRedo_StackSizeChanged As EventHandler(Of StackSizeChangedEventArgs)
  670.    Public Class StackSizeChangedEventArgs : Inherits EventArgs
  671.        Property UndoStack As Stack(Of ListView_Action)
  672.        Property RedoStack As Stack(Of ListView_Action)
  673.        Property UndoStackIsEmpty As Boolean
  674.        Property RedoStackIsEmpty As Boolean
  675.    End Class
  676.  
  677.    ''' <summary>
  678.    ''' Undo the last action.
  679.    ''' </summary>
  680.    Public Sub Undo()
  681.  
  682.        If Me.Undostack.Count = 0 Then Exit Sub ' Nothing to Undo.
  683.  
  684.        Me.IsDoingUndo = True
  685.        Me.action = Me.Undostack.Pop ' Get the Action from the Stack and remove it.
  686.        Me.action.Operation.DynamicInvoke(Me.action.Data) ' Invoke the undo Action.
  687.        Me.IsDoingUndo = False
  688.  
  689.        Raise_UndoRedo_IsPerformed(Operation.Undo, Me.action.Method, Me.action.Data)
  690.  
  691.    End Sub
  692.  
  693.    ''' <summary>
  694.    ''' Redo the last action.
  695.    ''' </summary>
  696.    Public Sub Redo()
  697.  
  698.        If Me.Redostack.Count = 0 Then Exit Sub ' Nothing to Redo.
  699.  
  700.        Me.IsDoingRedo = True
  701.        Me.action = Me.Redostack.Pop() ' Get the Action from the Stack and remove it.
  702.        Me.action.Operation.DynamicInvoke(Me.action.Data) ' Invoke the redo Action.
  703.        Me.IsDoingRedo = False
  704.  
  705.        Raise_UndoRedo_IsPerformed(Operation.Redo, Me.action.Method, Me.action.Data)
  706.  
  707.    End Sub
  708.  
  709.    ' Reverses an Undo/Redo action
  710.    Private Function GetReverseAction(ByVal e As UndoneRedoneEventArgs) As ListView_Action
  711.  
  712.        Me.action = New ListView_Action
  713.  
  714.        Me.action.Name = e.Item.Text
  715.        Me.action.Data = e.Item
  716.  
  717.        Me.action.Operation = If(e.Method = Method.Add, _
  718.                        New RemoveDelegate(AddressOf Me.RemoveItem), _
  719.                        New AddDelegate(AddressOf Me.AddItem))
  720.  
  721.        Me.action.Method = If(e.Method = Method.Add, _
  722.                     Method.Remove, _
  723.                     Method.Add)
  724.  
  725.        Return Me.action
  726.  
  727.    End Function
  728.  
  729.    ' Raises the "UndoRedo_IsPerformed" Event
  730.    Private Sub Raise_UndoRedo_IsPerformed(ByVal Operation As Operation, _
  731.                                           ByVal Method As Method, _
  732.                                           ByVal Item As ListViewItem)
  733.  
  734.        RaiseEvent UndoRedo_IsPerformed(Me, New UndoneRedoneEventArgs _
  735.                   With {.Item = Item, _
  736.                         .Method = Method, _
  737.                         .Operation = Operation, _
  738.                         .UndoStack = Me.Undostack, _
  739.                         .RedoStack = Me.Redostack})
  740.  
  741.        Raise_UndoRedo_StackSizeChanged()
  742.  
  743.    End Sub
  744.  
  745.    ' Raises the "UndoRedo_StackSizeChanged" Event
  746.    Private Sub Raise_UndoRedo_StackSizeChanged()
  747.  
  748.        RaiseEvent UndoRedo_StackSizeChanged(Me, New StackSizeChangedEventArgs _
  749.                   With {.UndoStack = Me.Undostack, _
  750.                         .RedoStack = Me.Redostack, _
  751.                         .UndoStackIsEmpty = Me.Undostack.Count = 0, _
  752.                         .RedoStackIsEmpty = Me.Redostack.Count = 0})
  753.  
  754.    End Sub
  755.  
  756.    ' This handles when an Undo or Redo operation is performed.
  757.    Private Sub UndoneRedone(ByVal sender As Object, ByVal e As UndoneRedoneEventArgs) _
  758.    Handles Me.UndoRedo_IsPerformed
  759.  
  760.        Select Case e.Operation
  761.  
  762.            Case Operation.Undo
  763.                ' Create a Redo Action for the undone action.
  764.                Me.Redostack.Push(GetReverseAction(e))
  765.  
  766.            Case Operation.Redo
  767.                ' Create a Undo Action for the redone action.
  768.                Me.Undostack.Push(GetReverseAction(e))
  769.  
  770.        End Select
  771.  
  772.    End Sub
  773.  
  774.    ' Monitors when an Item is added to create an Undo Operation.
  775.    Private Sub OnItemAdded(sender As Object, e As ItemAddedEventArgs) _
  776.    Handles Me.ItemAdded
  777.  
  778.        If Me.Enable_UndoRedo_Manager _
  779.            AndAlso (Not Me.IsDoingUndo And Not Me.IsDoingRedo) Then
  780.  
  781.            Me.Redostack.Clear()
  782.  
  783.            ' // Crate an Undo Action
  784.            Me.action = New ListView_Action
  785.            Me.action.Name = e.Item.Text
  786.            Me.action.Operation = New RemoveDelegate(AddressOf Me.RemoveItem)
  787.            Me.action.Data = e.Item
  788.            Me.action.Method = Method.Remove
  789.  
  790.            Me.Undostack.Push(action)
  791.  
  792.            Raise_UndoRedo_StackSizeChanged()
  793.  
  794.        End If
  795.  
  796.    End Sub
  797.  
  798.    ' Monitors when an Item is removed to create an Undo Operation.
  799.    Private Sub OnItemRemoved(sender As Object, e As ItemRemovedEventArgs) _
  800.    Handles Me.ItemRemoved
  801.  
  802.        If Me.Enable_UndoRedo_Manager _
  803.            AndAlso (Not Me.IsDoingUndo And Not Me.IsDoingRedo) Then
  804.  
  805.            Me.Redostack.Clear()
  806.  
  807.            ' // Crate an Undo Action
  808.            Me.action = New ListView_Action
  809.            Me.action.Name = e.Item.Text
  810.            Me.action.Operation = New AddDelegate(AddressOf Me.AddItem)
  811.            Me.action.Data = e.Item
  812.            Me.action.Method = Method.Add
  813.  
  814.            Me.Undostack.Push(action)
  815.  
  816.            Raise_UndoRedo_StackSizeChanged()
  817.  
  818.        End If
  819.  
  820.    End Sub
  821.  
  822. #End Region
  823.  
  824. End Class
« Última modificación: 11 Noviembre 2013, 01:26 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 #334 en: 11 Noviembre 2013, 01:34 am »

Una versión mejorada de mi ayudante para la aplicación mp3gain... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _mp3gain As New mp3gain _
  4.                With {.mp3gain_location = "C:\windows\system32\mp3gain.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            ' Checks if mp3gain executable is avaliable.
  10.            MsgBox(_mp3gain.Is_Avaliable())
  11.  
  12.            ' Checks if file contains APEv2 mp3gain tag
  13.            MsgBox(_mp3gain.File_Has_MP3Gain_Tag("C:\File.mp3"))
  14.  
  15.            ' Set the global volume Gain of file to "89" db (In a scale of "0-100"),
  16.            ' and preserve the datetime of file.
  17.            _mp3gain.Set_Gain("C:\File.mp3", 89, True)
  18.  
  19.            ' Apply a volume change of +5 db,
  20.            ' in the curent global volume gain of file.
  21.            _mp3gain.Apply_Gain("C:\File.mp3", +5)
  22.  
  23.            ' Apply a volume change of -5 db,
  24.            ' in the curent global volume gain of file.
  25.            _mp3gain.Apply_Gain("C:\File.mp3", -5)
  26.  
  27.            ' Apply a volume change of +10 db,
  28.            ' in the curent volume gain of the Left channel of an Stereo file.
  29.            _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Left, +10)
  30.  
  31.            ' Apply a volume change of -10 db,
  32.            ' in the curent volume gain of the Right channel of an Stereo file.
  33.            _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Right, -10)
  34.  
  35.            ' Undos all volume gain changes made in file.
  36.            _mp3gain.Undo_Gain("C:\File.mp3")
  37.  
  38.        End Sub
  39.  
  40.        ' mp3gain [Started]
  41.        Private Sub mp3gain_Started(ByVal sender As Process, ByVal e As mp3gain.StartedEventArgs) _
  42.        Handles _mp3gain.Started
  43.  
  44.            ProgressBar1.Value = ProgressBar1.Minimum
  45.  
  46.            Dim sb As New System.Text.StringBuilder
  47.  
  48.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  49.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  50.            sb.AppendLine(String.Format("mp3gain process PID is: ""{0}""", CStr(sender.Id)))
  51.  
  52.            MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information)
  53.  
  54.        End Sub
  55.  
  56.        ' mp3gain [Exited]
  57.        Private Sub mp3gain_Exited(ByVal sender As Process, ByVal e As mp3gain.ExitedEventArgs) _
  58.        Handles _mp3gain.Exited
  59.  
  60.            Dim sb As New System.Text.StringBuilder
  61.  
  62.            If e.Operation <> mp3gain.Operation.Check_Tag Then
  63.  
  64.                sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  65.                sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  66.                sb.AppendLine(String.Format("mp3gain process PID is: {0}", CStr(sender.Id)))
  67.  
  68.                If Not String.IsNullOrEmpty(e.InfoMessage) Then
  69.                    sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage))
  70.                End If
  71.  
  72.                If Not String.IsNullOrEmpty(e.ErrorMessage) Then
  73.                    sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage))
  74.                End If
  75.  
  76.                If e.db <> 0 Then
  77.                    sb.AppendLine(String.Format("Volume gain change: {0}", CStr(e.db)))
  78.                End If
  79.  
  80.                MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information)
  81.  
  82.            End If
  83.  
  84.        End Sub
  85.  
  86.        ' mp3gain [Progress]
  87.        Sub mp3gain_Progress(sender As Process, e As mp3gain.ProgressEventArgs) _
  88.        Handles _mp3gain.Progress
  89.  
  90.            ProgressBar1.Value = e.Percent
  91.  
  92.        End Sub
  93.  
  94.    End Class

El ayudante:

Código:
' [ mp3gain Helper ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "mp3gain.exe" into the project.

Código
  1. #region " mp3gain Helper "
  2.  
  3. Public Class mp3gain : Implements IDisposable
  4.  
  5. #Region " CommandLine parametter legend "
  6.  
  7.    ' /c   - Ignore clipping warning when applying gain.
  8.    ' /d   - Set global gain.
  9.    ' /e   - Skip Album analysis, even if multiple files listed.
  10.    ' /g   - apply gain
  11.    ' /p   - Preserve original file timestamp.
  12.    ' /r   - apply Track gain automatically (all files set to equal loudness)
  13.    ' /t   - Writes modified data to temp file, then deletes original instead of modifying bytes in original file.
  14.    ' /u   - Undo changes made (based on stored APEv2 mp3gain tag info).
  15.    ' /s c - Check stored APEv2 mp3gain tag info.
  16.  
  17. #End Region
  18.  
  19. #Region " Variables, Properties, Enumerations "
  20.  
  21.    ''' <summary>
  22.    ''' Gets or sets the mp3gain.exe executable path.
  23.    ''' </summary>
  24.    Public Property mp3gain_location As String = ".\mp3gain.exe"
  25.  
  26.    ''' <summary>
  27.    ''' Indicates if should check that the file exist before realize an operation.
  28.    ''' If True, an exception would be launched if file does not exist.
  29.    ''' </summary>
  30.    Public Property CheckFileExist As Boolean = False
  31.  
  32.    ''' <summary>
  33.    ''' Sets a Flag to indicate if file has APEv2 mp3gain tag or not.
  34.    ''' </summary>
  35.    Private HasTag As Boolean = False
  36.  
  37.    ''' <summary>
  38.    ''' Stores the StandardOutput.
  39.    ''' </summary>
  40.    Private Output As String() = Nothing
  41.  
  42.    ''' <summary>
  43.    ''' Stores an information message of the realized operation (if any).
  44.    ''' </summary>
  45.    Private InfoMessage As String = String.Empty
  46.  
  47.    ''' <summary>
  48.    ''' Stores an error message of the realized operation (if any).
  49.    ''' </summary>
  50.    Private ErrorMessage As String = String.Empty
  51.  
  52.    ''' <summary>
  53.    ''' Stores the volume gain level change applied to file (if any).
  54.    ''' </summary>
  55.    Private db As Integer = 0
  56.  
  57.    ''' <summary>
  58.    ''' Gets some information about the file.
  59.    ''' </summary>
  60.    Private db_RegEx As New System.Text.RegularExpressions.Regex("Applying.+change of (.*) to",
  61.                            System.Text.RegularExpressions.RegexOptions.None)
  62.  
  63.    ''' <summary>
  64.    ''' Process to realize an operation,
  65.    ''' for files that already contains APEv2 mp3gain tag.
  66.    ''' Also is used to realize a single TagCheck operation.
  67.    ''' </summary>
  68.    Private Process_For_Tag As Process =
  69.        New Process With {.StartInfo =
  70.            New ProcessStartInfo With {
  71.                .CreateNoWindow = True,
  72.                .UseShellExecute = False,
  73.                .RedirectStandardError = False,
  74.                .RedirectStandardOutput = True
  75.           }
  76.        }
  77.  
  78.    ''' <summary>
  79.    ''' Process to realize an operation,
  80.    ''' for files that does not contains mp3gain Tag.
  81.    ''' </summary>
  82.    Private Process_For_NonTag As Process =
  83.        New Process With {.StartInfo =
  84.            New ProcessStartInfo With {
  85.                .CreateNoWindow = True,
  86.                .UseShellExecute = False,
  87.                .RedirectStandardError = True,
  88.                .RedirectStandardOutput = True
  89.           }
  90.        }
  91.  
  92.    ''' <summary>
  93.    ''' Stores the StartedEventArgs Arguments.
  94.    ''' </summary>
  95.    Private StartedArgs As New StartedEventArgs
  96.  
  97.    ''' <summary>
  98.    ''' Stores the ExitedEventArgs Arguments.
  99.    ''' </summary>
  100.    Private ExitedArgs As New ExitedEventArgs
  101.  
  102.    ''' <summary>
  103.    ''' Stores the ProgressEventArgs Arguments.
  104.    ''' </summary>
  105.    Private ProgressArgs As New ProgressEventArgs
  106.  
  107.    ''' <summary>
  108.    ''' File Stereo Channel.
  109.    ''' </summary>
  110.    Public Enum Channel As Short
  111.        Left = 0  ' /l 0
  112.        Right = 1 ' /l 1
  113.    End Enum
  114.  
  115.    ''' <summary>
  116.    ''' MP3Gain Type Of Operation.
  117.    ''' </summary>
  118.    Public Enum Operation
  119.        Check_Tag = 0
  120.        Apply_Gain = 1
  121.        Apply_Channel_Gain = 2
  122.        Set_Gain = 3
  123.        Undo_Gain = 4
  124.    End Enum
  125.  
  126. #End Region
  127.  
  128. #Region " Events "
  129.  
  130.    ''' <summary>
  131.    ''' Event raised when the process has started.
  132.    ''' </summary>
  133.    Public Event Started As EventHandler(Of StartedEventArgs)
  134.    Public Class StartedEventArgs : Inherits EventArgs
  135.        ''' <summary>
  136.        ''' Gets the file that was passed as argument to the process.
  137.        ''' </summary>
  138.        Public Property File As String
  139.        ''' <summary>
  140.        ''' Gets the type of operation to realize.
  141.        ''' </summary>
  142.        Public Property Operation As Operation
  143.    End Class
  144.  
  145.    ''' <summary>
  146.    ''' Event raised when the process has exited.
  147.    ''' </summary>
  148.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  149.    Public Class ExitedEventArgs : Inherits EventArgs
  150.        ''' <summary>
  151.        ''' Gets the file that was passed as argument to the process.
  152.        ''' </summary>
  153.        Public Property File As String
  154.        ''' <summary>
  155.        ''' Gets the type of operation to realize.
  156.        ''' </summary>
  157.        Public Property Operation As Operation
  158.        ''' <summary>
  159.        ''' Gets the information message of the realized operation (if any).
  160.        ''' </summary>
  161.        Public Property InfoMessage As String
  162.        ''' <summary>
  163.        ''' Gets the error message of the realized operation (if any).
  164.        ''' </summary>
  165.        Public Property ErrorMessage As String
  166.        ''' <summary>
  167.        ''' Gets the volume gain level change applied to file (if any).
  168.        ''' </summary>
  169.        Public Property db As Integer
  170.    End Class
  171.  
  172.    ''' <summary>
  173.    ''' Event raised when the process progress changes.
  174.    ''' </summary>
  175.    Public Event Progress As EventHandler(Of ProgressEventArgs)
  176.    Public Class ProgressEventArgs : Inherits EventArgs
  177.        ''' <summary>
  178.        ''' Gets the process operation percent done.
  179.        ''' </summary>
  180.        Public Property Percent As Integer
  181.    End Class
  182.  
  183. #End Region
  184.  
  185. #Region " MP3Gain Procedures "
  186.  
  187.    ''' <summary>
  188.    ''' Checks if mp3gain.exe process is avaliable.
  189.    ''' </summary>
  190.    Public Function Is_Avaliable() As Boolean
  191.        Return IO.File.Exists(Me.mp3gain_location)
  192.    End Function
  193.  
  194.    ''' <summary>
  195.    ''' Checks if APEv2 mp3gain tag exists in file.
  196.    ''' </summary>
  197.    Public Function File_Has_MP3Gain_Tag(ByVal MP3_File As String) As Boolean
  198.  
  199.        Run_MP3Gain(MP3_File,
  200.                    Operation.Check_Tag,
  201.                    String.Format("/s c ""{0}""", MP3_File),
  202.                    True)
  203.  
  204.        Return HasTag
  205.  
  206.    End Function
  207.  
  208.    ''' <summary>
  209.    ''' Set the global volume gain of file.
  210.    ''' </summary>
  211.    Public Sub Set_Gain(ByVal MP3_File As String,
  212.                        ByVal Gain As Integer,
  213.                        Optional ByVal Preserve_Datestamp As Boolean = True)
  214.  
  215.        File_Has_MP3Gain_Tag(MP3_File)
  216.  
  217.        Run_MP3Gain(MP3_File,
  218.                    Operation.Set_Gain,
  219.                    String.Format("/c /e /r /t {1} /d {2} ""{0}""",
  220.                                  MP3_File,
  221.                                  If(Preserve_Datestamp, "/p", ""),
  222.                                  If(Gain < 0, Gain + 89.0, Gain - 89.0)),
  223.                    False)
  224.  
  225.    End Sub
  226.  
  227.    ''' <summary>
  228.    ''' Apply a volume gain change to file.
  229.    ''' </summary>
  230.    Public Sub Apply_Gain(ByVal MP3_File As String,
  231.                          ByVal Gain As Integer,
  232.                          Optional ByVal Preserve_Datestamp As Boolean = True)
  233.  
  234.        File_Has_MP3Gain_Tag(MP3_File)
  235.  
  236.        Run_MP3Gain(MP3_File,
  237.                    Operation.Apply_Gain,
  238.                    String.Format("/c /e /r /t {1} /g {2} ""{0}""",
  239.                                  MP3_File,
  240.                                  If(Preserve_Datestamp, "/p", ""),
  241.                                  Gain),
  242.                    False)
  243.  
  244.    End Sub
  245.  
  246.    ''' <summary>
  247.    ''' Apply a volume gain change to file only in left or right channel.
  248.    ''' Only works for Stereo MP3 files.
  249.    ''' </summary>
  250.    Public Sub Apply_Channel_Gain(ByVal MP3_File As String,
  251.                                  ByVal Channel As Channel,
  252.                                  ByVal Gain As Integer,
  253.                                  Optional ByVal Preserve_Datestamp As Boolean = True)
  254.  
  255.        File_Has_MP3Gain_Tag(MP3_File)
  256.  
  257.        Run_MP3Gain(MP3_File,
  258.                    Operation.Apply_Channel_Gain,
  259.                    String.Format("/c /e /r /l {2} {3} ""{0}""",
  260.                                  MP3_File,
  261.                                  If(Preserve_Datestamp, "/p", ""),
  262.                                  If(Channel = Channel.Left, 0, 1),
  263.                                  Gain),
  264.                    False)
  265.  
  266.    End Sub
  267.  
  268.    ''' <summary>
  269.    ''' Undos all mp3gain volume changes made in a file,
  270.    ''' based on stored APEv2 mp3gain tag info.
  271.    ''' </summary>
  272.    Public Sub Undo_Gain(ByVal MP3_File As String,
  273.                         Optional ByVal Preserve_Datestamp As Boolean = True)
  274.  
  275.        File_Has_MP3Gain_Tag(MP3_File)
  276.  
  277.        Run_MP3Gain(MP3_File,
  278.                    Operation.Undo_Gain,
  279.                    String.Format("/c /t {1} /u ""{0}""",
  280.                                  MP3_File,
  281.                                  If(Preserve_Datestamp, "/p", "")),
  282.                    False)
  283.  
  284.    End Sub
  285.  
  286. #End Region
  287.  
  288. #Region " Run Procedures "
  289.  
  290.    ''' <summary>
  291.    ''' Run MP3Gain process.
  292.    ''' </summary>
  293.    Private Sub Run_MP3Gain(ByVal MP3_File As String,
  294.                            ByVal operation As Operation,
  295.                            ByVal Parametters As String,
  296.                            ByVal IsCheckTagOperation As Boolean)
  297.  
  298.        If Me.CheckFileExist Then
  299.            FileExist(MP3_File)
  300.        End If
  301.  
  302.        With Process_For_Tag.StartInfo
  303.            .FileName = Me.mp3gain_location
  304.            .Arguments = Parametters
  305.        End With
  306.  
  307.        With Process_For_NonTag.StartInfo
  308.            .FileName = Me.mp3gain_location
  309.            .Arguments = Parametters
  310.        End With
  311.  
  312.        ' Reset Variables before relaize the operation.
  313.        InfoMessage = Nothing
  314.        ErrorMessage = Nothing
  315.        db = 0
  316.  
  317.        ' Check if file has APEv2 mp3gain tag or not,
  318.        ' before doing any other operation.
  319.        If IsCheckTagOperation Then
  320.  
  321.            Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation.Check_Tag, True)
  322.            Exit Sub ' If only would to check the tag then exit from this sub.
  323.  
  324.        Else ' Else, continue with the operation (Modify volume gain)...
  325.  
  326.            Select Case HasTag
  327.  
  328.                Case True
  329.                    Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation, False)
  330.  
  331.                Case False
  332.                    Run_MP3Gain_For_NonTag(Process_For_NonTag, MP3_File, operation)
  333.  
  334.            End Select ' HasTag
  335.  
  336.        End If ' IsCheckTagOperation
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Runs mp3gain for files that already contains APEv2 mp3gain tag.
  342.    ''' </summary>
  343.    Private Sub Run_MP3Gain_For_Tag(ByVal p As Process,
  344.                                    ByVal MP3_File As String,
  345.                                    ByVal operation As Operation,
  346.                                    ByVal IsTagCheckOperation As Boolean)
  347.  
  348.        p.Start()
  349.        RaiseEvent_Started(p, MP3_File, operation)
  350.        p.WaitForExit()
  351.  
  352.        If IsTagCheckOperation Then
  353.            HasTag = CBool(p.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).Count - 1)
  354.        End If
  355.  
  356.        ProgressArgs.Percent = 100
  357.        RaiseEvent Progress(p, ProgressArgs)
  358.  
  359.        SetMessages(p.StandardOutput.ReadToEnd())
  360.  
  361.        RaiseEvent_Exited(p,
  362.                          MP3_File,
  363.                          operation,
  364.                          If(IsTagCheckOperation, "File Has Tag?: " & CStr(HasTag), InfoMessage),
  365.                          ErrorMessage,
  366.                          db)
  367.  
  368.        ' p.Close()
  369.  
  370.    End Sub
  371.  
  372.    ''' <summary>
  373.    ''' Runs mp3gain for files that doesn't contains APEv2 mp3gain tag.
  374.    ''' </summary>
  375.    Private Sub Run_MP3Gain_For_NonTag(ByVal p As Process,
  376.                                       ByVal MP3_File As String,
  377.                                       ByVal operation As Operation)
  378.  
  379.        p.Start()
  380.        RaiseEvent_Started(p, MP3_File, operation)
  381.  
  382.        Do Until p.HasExited
  383.  
  384.            Try
  385.  
  386.                ProgressArgs.Percent = CInt(p.StandardError.ReadLine.Split("%").First.Trim)
  387.  
  388.                If ProgressArgs.Percent < 101 Then
  389.                    RaiseEvent Progress(p, ProgressArgs)
  390.                End If
  391.  
  392.            Catch
  393.            End Try
  394.  
  395.        Loop
  396.  
  397.        ProgressArgs.Percent = 100
  398.        RaiseEvent Progress(p, ProgressArgs)
  399.  
  400.        SetMessages(p.StandardOutput.ReadToEnd())
  401.  
  402.        RaiseEvent_Exited(p,
  403.                          MP3_File,
  404.                          operation,
  405.                          InfoMessage,
  406.                          ErrorMessage,
  407.                          db)
  408.  
  409.        ' p.Close()
  410.  
  411.    End Sub
  412.  
  413. #End Region
  414.  
  415. #Region " Miscellaneous Procedures "
  416.  
  417.    ''' <summary>
  418.    ''' Checks if a file exists.
  419.    ''' </summary>
  420.    Private Sub FileExist(ByVal File As String)
  421.  
  422.        If Not IO.File.Exists(File) Then
  423.            Throw New Exception(String.Format("File doesn't exist: ""{0}""", File))
  424.            ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Error)
  425.        End If
  426.  
  427.    End Sub
  428.  
  429.    ''' <summary>
  430.    ''' Raises the Event Started
  431.    ''' </summary>
  432.    Private Sub RaiseEvent_Started(ByVal p As Process,
  433.                                   ByVal file As String,
  434.                                   ByVal operation As Operation)
  435.  
  436.        With StartedArgs
  437.            .File = file
  438.            .Operation = operation
  439.        End With
  440.  
  441.        RaiseEvent Started(p, StartedArgs)
  442.  
  443.    End Sub
  444.  
  445.    ''' <summary>
  446.    ''' Raises the Event Exited
  447.    ''' </summary>
  448.    Private Sub RaiseEvent_Exited(ByVal p As Process,
  449.                                  ByVal file As String,
  450.                                  ByVal operation As Operation,
  451.                                  ByVal InfoMessage As String,
  452.                                  ByVal ErrorMessage As String,
  453.                                  ByVal db As Integer)
  454.  
  455.        With ExitedArgs
  456.            .File = file
  457.            .Operation = operation
  458.            .InfoMessage = InfoMessage
  459.            .ErrorMessage = ErrorMessage
  460.            .db = db
  461.        End With
  462.  
  463.        RaiseEvent Exited(p, ExitedArgs)
  464.  
  465.    End Sub
  466.  
  467.    ''' <summary>
  468.    ''' Sets the InfoMessage, ErrorMessage and db variables.
  469.    ''' </summary>
  470.    Private Sub SetMessages(ByVal StandardOutput As String)
  471.  
  472.        Output = StandardOutput.
  473.                 Split(Environment.NewLine).
  474.                 Select(Function(line) line.Replace(Environment.NewLine, "").Trim).
  475.                 Where(Function(null) Not String.IsNullOrEmpty(null)).ToArray
  476.  
  477.        For Each line In Output
  478.  
  479.            Select Case True
  480.  
  481.                Case line.StartsWith("No changes")
  482.                    InfoMessage = "No volume gain changes are necessary."
  483.  
  484.                Case line.StartsWith("Applying")
  485.                    db = db_RegEx.Match(line).Groups(1).Value
  486.                    If String.IsNullOrEmpty(InfoMessage) Then
  487.                        InfoMessage = line
  488.                    End If
  489.  
  490.                Case line.StartsWith("Can't")
  491.                    ErrorMessage = line
  492.  
  493.            End Select
  494.  
  495.        Next line
  496.  
  497.    End Sub
  498.  
  499. #End Region
  500.  
  501. #Region " IDisposable "
  502.  
  503.      ''' <summary>
  504.      ''' Disposes the objects generated by this instance.
  505.      ''' </summary>
  506.      Public Sub Dispose() Implements IDisposable.Dispose
  507.          Dispose(True)
  508.          GC.SuppressFinalize(Me)
  509.      End Sub
  510.  
  511.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  512.  
  513.          Static IsBusy As Boolean ' To detect redundant calls.
  514.  
  515.          If Not IsBusy AndAlso IsDisposing Then
  516.  
  517.             Process_For_Tag.Dispose()
  518.         Process_For_NonTag.Dispose()
  519.  
  520.          End If
  521.  
  522.          IsBusy = True
  523.  
  524.      End Sub
  525.  
  526.  #End Region
  527.  
  528. End Class
  529.  
  530. #End Region
« Última modificación: 11 Noviembre 2013, 01:39 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 #335 en: 11 Noviembre 2013, 01:36 am »

Una versión mejorada de mi ayudante para la aplicación CoreConverter... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _converter As New CoreConverter _
  4.                With {.CoreConverter_location = "C:\windows\system32\coreconverter.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            ' Checks if CoreConverter executable is avaliable.
  10.            MsgBox(_converter.Is_Avaliable())
  11.  
  12.            ' Convert a file to MP3
  13.            _converter.Convert_To_MP3("C:\Input.wav", "C:\Output.mp3",
  14.                                      CoreConverter.Lame_Bitrate.kbps_320,
  15.                                      CoreConverter.Lame_Bitrate_Mode.cbr,
  16.                                      CoreConverter.Lame_Profile.SLOW,
  17.                                      CoreConverter.Lame_Quality.Q0_Maximum,
  18.                                      CoreConverter.Lame_Khz.Same_As_Source,
  19.                                      CoreConverter.Lame_Channels.auto,
  20.                                      {
  21.                                       CoreConverter.DSP_Effects.Delete_Output_File_on_Error,
  22.                                       CoreConverter.DSP_Effects.Recycle_Source_File_After_Conversion
  23.                                      },
  24.                                      False,
  25.                                      CoreConverter.Priority.normal)
  26.  
  27.            ' Convert a file to WAV
  28.            _converter.Convert_To_WAV_Uncompressed("C:\Input.mp3", "C:\Output.wav", _
  29.                                                   CoreConverter.WAV_Uncompressed_Bitrate.Same_As_Source, _
  30.                                                   CoreConverter.WAV_Uncompressed_Khz.Same_As_Source, _
  31.                                                   CoreConverter.WAV_Uncompressed_Channels.Same_As_Source, , False)
  32.  
  33.            ' Convert a file to WMA
  34.            _converter.Convert_To_WMA("C:\Input.mp3", "C:\Output.wma", _
  35.                                      CoreConverter.WMA_9_2_BitRates.Kbps_128, _
  36.                                      CoreConverter.WMA_9_2_Khz.Khz_44100, _
  37.                                      CoreConverter.WMA_9_2_Channels.stereo, , False)
  38.  
  39.        End Sub
  40.  
  41.        ' CoreConverter [Started]
  42.        Private Sub CoreConverter_Started(ByVal sender As Process, ByVal e As CoreConverter.StartedEventArgs) _
  43.        Handles _converter.Started
  44.  
  45.            ProgressBar1.Value = ProgressBar1.Minimum
  46.  
  47.            Dim sb As New System.Text.StringBuilder
  48.  
  49.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  50.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  51.            sb.AppendLine(String.Format("CoreConverter process PID is: ""{0}""", CStr(sender.Id)))
  52.  
  53.            MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information)
  54.  
  55.        End Sub
  56.  
  57.        ' CoreConverter [Exited]
  58.        Private Sub CoreConverter_Exited(ByVal sender As Process, ByVal e As CoreConverter.ExitedEventArgs) _
  59.        Handles _converter.Exited
  60.  
  61.            Dim sb As New System.Text.StringBuilder
  62.  
  63.            sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  64.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  65.            sb.AppendLine(String.Format("CoreConverter process PID is: {0}", CStr(sender.Id)))
  66.  
  67.            If Not String.IsNullOrEmpty(e.InfoMessage) Then
  68.                sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage))
  69.            End If
  70.  
  71.            If Not String.IsNullOrEmpty(e.ErrorMessage) Then
  72.                sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage))
  73.            End If
  74.  
  75.            If Not String.IsNullOrEmpty(e.ElapsedTime) Then
  76.                sb.AppendLine(String.Format("Total elapsed time: {0}", e.ElapsedTime))
  77.            End If
  78.  
  79.            MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information)
  80.  
  81.        End Sub
  82.  
  83.        ' CoreConverter [Progress]
  84.        Sub CoreConverter_Progress(sender As Process, e As CoreConverter.ProgressEventArgs) _
  85.        Handles _converter.Progress
  86.  
  87.            ProgressBar1.Value = e.Percent
  88.  
  89.        End Sub
  90.  
  91.    End Class


El ayudante:

Código:
' [ CoreConverter Helper ]
'
' // By Elektro H@cker
'
' Instructions:

' 1. Add the "CoreConverter.exe" into the project,
'    together with dbPoweramp Effects and Codec folders.

Código
  1. #Region " CoreConverter Helper "
  2.  
  3. Public Class CoreConverter : Implements IDisposable
  4.  
  5. #Region " Variables, Properties, Enumerations "
  6.  
  7.    ''' <summary>
  8.    ''' Gets or sets CoreConverter.exe executable path.
  9.    ''' </summary>
  10.    Public Property CoreConverter_location As String = ".\CoreConverter.exe"
  11.  
  12.    ''' <summary>
  13.    ''' Indicates if should check that the file exist before realize an operation.
  14.    ''' If True, an exception would be launched if file does not exist.
  15.    ''' </summary>
  16.    Public Property CheckFileExist As Boolean = False
  17.  
  18.    ''' <summary>
  19.    ''' Stores the converter process progress
  20.    ''' </summary>
  21.    Private CurrentProgress As Integer = 0
  22.  
  23.    ''' <summary>
  24.    ''' Stores an information message of the realized operation (if any).
  25.    ''' </summary>
  26.    Private InfoMessage As String = Nothing
  27.  
  28.    ''' <summary>
  29.    ''' Stores an error message of the realized operation (if any).
  30.    ''' </summary>
  31.    Private ErrorMessage As String = Nothing
  32.  
  33.    ''' <summary>
  34.    ''' Stores the next converter process output character.
  35.    ''' </summary>
  36.    Private OutputCharacter As Char = Nothing
  37.  
  38.    ''' <summary>
  39.    ''' Stores the DSP Effects formatted string.
  40.    ''' </summary>
  41.    Private Effects As String = Nothing
  42.  
  43.    ''' <summary>
  44.    ''' Stores the total elapsed time of conversion.
  45.    ''' </summary>
  46.    Private ElapsedTime As String = Nothing
  47.  
  48.    ''' <summary>
  49.    ''' Stores additional information about the conversion.
  50.    ''' </summary>
  51.    Private ExtraInfo() As String = Nothing
  52.  
  53.    ''' <summary>
  54.    ''' Stores the StartedEventArgs Arguments.
  55.    ''' </summary>
  56.    Private StartedArgs As New StartedEventArgs
  57.  
  58.    ''' <summary>
  59.    ''' Stores the ExitedEventArgs Arguments.
  60.    ''' </summary>
  61.    Private ExitedArgs As New ExitedEventArgs
  62.  
  63.    ''' <summary>
  64.    ''' Stores the ProgressEventArgs Arguments.
  65.    ''' </summary>
  66.    Private ProgressArgs As New ProgressEventArgs
  67.  
  68.    ''' <summary>
  69.    ''' CoreConverter Type Of Operation.
  70.    ''' </summary>
  71.    Public Enum Operation
  72.        MP3_Conversion = 0
  73.        WAV_Conversion = 1
  74.        WMA_Conversion = 2
  75.    End Enum
  76.  
  77.    ''' <summary>
  78.    ''' Priority level of CoreConverter process.
  79.    ''' </summary>
  80.    Public Enum Priority
  81.        idle
  82.        low
  83.        normal
  84.        high
  85.    End Enum
  86.  
  87.    ''' <summary>
  88.    ''' DSP Effects.
  89.    ''' </summary>
  90.    Public Enum DSP_Effects
  91.        Delete_Output_File_on_Error ' Delete failed conversion (not deletes source file).
  92.        Delete_Source_File_After_Conversion ' Delete source file after conversion.
  93.        Recycle_Source_File_After_Conversion ' Send source file to recycle bin after conversion.
  94.        Karaoke_Remove_Voice ' Remove voice from file.
  95.        Karaoke_Remove_Instrument ' Remove instruments from file.
  96.        Reverse ' Reverse complete audio file.
  97.        Write_Silence ' Write silence at start of file.
  98.    End Enum
  99.  
  100.    ''' <summary>
  101.    ''' CoreConverter Process.
  102.    ''' </summary>
  103.    Private p As Process =
  104.        New Process With {.StartInfo =
  105.            New ProcessStartInfo With {
  106.                .CreateNoWindow = True, _
  107.                .UseShellExecute = False, _
  108.                .RedirectStandardError = True, _
  109.                .RedirectStandardOutput = True, _
  110.                .StandardErrorEncoding = System.Text.Encoding.Unicode, _
  111.                .StandardOutputEncoding = System.Text.Encoding.Unicode
  112.           }
  113.        }
  114.  
  115. #End Region
  116.  
  117. #Region " Events "
  118.  
  119.    ''' <summary>
  120.    ''' Event raised when CoreConverter operation progress changes.
  121.    ''' </summary>
  122.    Public Event Progress As EventHandler(Of ProgressEventArgs)
  123.    Public Class ProgressEventArgs : Inherits EventArgs
  124.        ''' <summary>
  125.        ''' Gets the CoreConverter operation percent done.
  126.        ''' </summary>
  127.        Public Property Percent As Integer
  128.    End Class
  129.  
  130.    ''' <summary>
  131.    ''' Event raised when CoreConverter process has started.
  132.    ''' </summary>
  133.    Public Event Started As EventHandler(Of StartedEventArgs)
  134.    Public Class StartedEventArgs : Inherits EventArgs
  135.        ''' <summary>
  136.        ''' Gets the file that was passed as argument to the process.
  137.        ''' </summary>
  138.        Public Property File As String
  139.        ''' <summary>
  140.        ''' Gets the type of operation to realize.
  141.        ''' </summary>
  142.        Public Property Operation As Operation
  143.    End Class
  144.  
  145.    ''' <summary>
  146.    ''' Event raised when CoreConverter process has exited.
  147.    ''' </summary>
  148.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  149.    Public Class ExitedEventArgs : Inherits EventArgs
  150.        ''' <summary>
  151.        ''' Gets the file that was passed as argument to the process.
  152.        ''' </summary>
  153.        Public Property File As String
  154.        ''' <summary>
  155.        ''' Gets the type of operation to realize.
  156.        ''' </summary>
  157.        Public Property Operation As Operation
  158.        ''' <summary>
  159.        ''' Gets an information message of the realized operation.
  160.        ''' </summary>
  161.        Public Property InfoMessage As String
  162.        ''' <summary>
  163.        ''' Gets an error message of the realized operation (if any).
  164.        ''' </summary>
  165.        Public Property ErrorMessage As String
  166.        ''' <summary>
  167.        ''' Gets the total elapsed time of the operation.
  168.        ''' </summary>
  169.        Public Property ElapsedTime As String
  170.    End Class
  171.  
  172. #End Region
  173.  
  174. #Region " Codec Enumerations "
  175.  
  176. #Region " MP3 Lame "
  177.  
  178.    Public Enum Lame_Bitrate
  179.        kbps_8 = 8
  180.        kbps_16 = 16
  181.        kbps_24 = 24
  182.        kbps_32 = 32
  183.        kbps_40 = 40
  184.        kbps_48 = 48
  185.        kbps_56 = 56
  186.        kbps_64 = 64
  187.        kbps_80 = 80
  188.        kbps_96 = 96
  189.        kbps_112 = 112
  190.        kbps_128 = 128
  191.        kbps_144 = 144
  192.        kbps_160 = 160
  193.        kbps_192 = 192
  194.        kbps_224 = 224
  195.        kbps_256 = 256
  196.        kbps_320 = 320
  197.    End Enum
  198.  
  199.    Public Enum Lame_Bitrate_Mode
  200.        cbr
  201.        abr
  202.    End Enum
  203.  
  204.    Public Enum Lame_Profile
  205.        NORMAL
  206.        FAST
  207.        SLOW
  208.    End Enum
  209.  
  210.    Public Enum Lame_Quality
  211.        Q0_Maximum = 0
  212.        Q1 = 1
  213.        Q2 = 2
  214.        Q3 = 3
  215.        Q4 = 4
  216.        Q5 = 5
  217.        Q6 = 6
  218.        Q7 = 7
  219.        Q8 = 8
  220.        Q9_Minimum = 9
  221.    End Enum
  222.  
  223.    Public Enum Lame_Khz
  224.        Same_As_Source
  225.        khz_8000 = 8000
  226.        khz_11025 = 11025
  227.        khz_12000 = 12000
  228.        khz_16000 = 16000
  229.        khz_22050 = 22050
  230.        khz_24000 = 24000
  231.        khz_32000 = 32000
  232.        khz_44100 = 44100
  233.        khz_48000 = 48000
  234.    End Enum
  235.  
  236.    Public Enum Lame_Channels
  237.        auto
  238.        mono
  239.        stereo
  240.        joint_stereo
  241.        forced_joint_stereo
  242.        forced_stereo
  243.        dual_channels
  244.    End Enum
  245.  
  246. #End Region
  247.  
  248. #Region " WAV Uncompressed "
  249.  
  250.    Public Enum WAV_Uncompressed_Bitrate
  251.        Same_As_Source
  252.        bits_8 = 8
  253.        bits_16 = 16
  254.        bits_24 = 24
  255.        bits_32 = 32
  256.    End Enum
  257.  
  258.    Public Enum WAV_Uncompressed_Khz
  259.        Same_As_Source
  260.        khz_8000 = 8000
  261.        khz_11025 = 11025
  262.        khz_12000 = 12000
  263.        khz_16000 = 16000
  264.        khz_22050 = 22050
  265.        khz_24000 = 24000
  266.        khz_32000 = 32000
  267.        khz_44100 = 44100
  268.        khz_48000 = 48000
  269.        khz_96000 = 96000
  270.        khz_192000 = 192000
  271.    End Enum
  272.  
  273.    Public Enum WAV_Uncompressed_Channels
  274.        Same_As_Source
  275.        Channels_1_Mono = 1
  276.        Channels_2_Stereo = 2
  277.        Channels_3 = 3
  278.        Channels_4_Quadraphonic = 4
  279.        Channels_5_Surround = 5
  280.        Channels_6_Surround_DVD = 6
  281.        Channels_7 = 7
  282.        Channels_8_Theater = 8
  283.    End Enum
  284.  
  285. #End Region
  286.  
  287. #Region " WMA 9.2 "
  288.  
  289.    Public Enum WMA_9_2_BitRates
  290.        Kbps_12 = 12
  291.        Kbps_16 = 16
  292.        Kbps_20 = 20
  293.        Kbps_22 = 22
  294.        Kbps_24 = 24
  295.        Kbps_32 = 32
  296.        Kbps_40 = 40
  297.        Kbps_48 = 48
  298.        Kbps_64 = 64
  299.        Kbps_80 = 80
  300.        Kbps_96 = 96
  301.        Kbps_128 = 128
  302.        Kbps_160 = 160
  303.        Kbps_192 = 192
  304.        Kbps_256 = 256
  305.        Kbps_320 = 320
  306.    End Enum
  307.  
  308.    Enum WMA_9_2_Khz
  309.        Khz_8000 = 8
  310.        Khz_16000 = 16
  311.        Khz_22050 = 22
  312.        Khz_32000 = 32
  313.        Khz_44100 = 44
  314.        Khz_48000 = 48
  315.    End Enum
  316.  
  317.    Enum WMA_9_2_Channels
  318.        mono
  319.        stereo
  320.    End Enum
  321.  
  322. #End Region
  323.  
  324. #End Region
  325.  
  326. #Region " CoreConverter Procedures "
  327.  
  328.    ''' <summary>
  329.    ''' Checks if CoreConverter process is avaliable.
  330.    ''' </summary>
  331.    Public Function Is_Avaliable() As Boolean
  332.        Return IO.File.Exists(Me.CoreConverter_location)
  333.    End Function
  334.  
  335.    ''' <summary>
  336.    ''' Converts a file to MP3 using Lame codec.
  337.    ''' </summary>
  338.    Public Sub Convert_To_MP3(ByVal In_File As String, _
  339.                              ByVal Out_File As String, _
  340.                              ByVal Bitrate As Lame_Bitrate, _
  341.                              ByVal Bitrate_Mode As Lame_Bitrate_Mode, _
  342.                              ByVal Encoding_Profile As Lame_Profile, _
  343.                              ByVal Quality As Lame_Quality, _
  344.                              ByVal Khz As Lame_Khz, _
  345.                              ByVal Channels As Lame_Channels, _
  346.                              Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  347.                              Optional ByVal Update_Tag As Boolean = True, _
  348.                              Optional ByVal Priority As Priority = Priority.normal, _
  349.                              Optional ByVal Processor As Short = 1)
  350.  
  351.        Get_Effects(DSP_Effects)
  352.  
  353.        Set_Main_Arguments("mp3 (Lame)",
  354.                           In_File,
  355.                           Out_File,
  356.                           If(Not Update_Tag, "-noidtag", ""),
  357.                           Effects,
  358.                           Priority.ToString,
  359.                           Processor.ToString)
  360.  
  361.        p.StartInfo.Arguments &= _
  362.        String.Format("-b {0} --{1} -encoding=""{2}"" -freq=""{3}"" -channels=""{4}"" --noreplaygain --extracli=""-q {5}""", _
  363.                      CInt(Bitrate), _
  364.                      Bitrate_Mode.ToString, _
  365.                      Encoding_Profile.ToString, _
  366.                      If(Khz = Lame_Khz.Same_As_Source, "", CInt(Khz)), _
  367.                      If(Channels = Lame_Channels.auto, "", Channels), _
  368.                      CInt(Quality))
  369.  
  370.        Run_CoreConverter(In_File, Operation.MP3_Conversion)
  371.  
  372.    End Sub
  373.  
  374.    ''' <summary>
  375.    ''' Converts a file to Uncompressed WAV.
  376.    ''' </summary>
  377.    Public Sub Convert_To_WAV_Uncompressed(ByVal In_File As String, _
  378.                                           ByVal Out_File As String, _
  379.                                           ByVal Bitrate As WAV_Uncompressed_Bitrate, _
  380.                                           ByVal Khz As WAV_Uncompressed_Khz, _
  381.                                           ByVal Channels As WAV_Uncompressed_Channels, _
  382.                                           Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  383.                                           Optional ByVal Update_Tag As Boolean = True, _
  384.                                           Optional ByVal Priority As Priority = Priority.normal, _
  385.                                           Optional ByVal Processor As Short = 1)
  386.  
  387.        Get_Effects(DSP_Effects)
  388.  
  389.        Set_Main_Arguments("Wave",
  390.                           In_File,
  391.                           Out_File,
  392.                           If(Not Update_Tag, "-noidtag", ""),
  393.                           Effects,
  394.                           Priority.ToString,
  395.                           Processor.ToString)
  396.  
  397.        p.StartInfo.Arguments &= _
  398.        String.Format("-compression=""PCM"" -bits=""{0}"" -freq=""{1}"" -channels=""{2}""", _
  399.                      If(Bitrate = WAV_Uncompressed_Bitrate.Same_As_Source, "", CInt(Bitrate)), _
  400.                      If(Khz = WAV_Uncompressed_Khz.Same_As_Source, "", CInt(Khz)), _
  401.                      If(Channels = WAV_Uncompressed_Channels.Same_As_Source, "", CInt(Channels)))
  402.  
  403.        Run_CoreConverter(In_File, Operation.WAV_Conversion)
  404.  
  405.    End Sub
  406.  
  407.    ''' <summary>
  408.    ''' Converts a file to WMA v9.2
  409.    ''' </summary>
  410.    Public Sub Convert_To_WMA(ByVal In_File As String, _
  411.                              ByVal Out_File As String, _
  412.                              ByVal Bitrate As WMA_9_2_BitRates, _
  413.                              ByVal Khz As WMA_9_2_Khz, _
  414.                              ByVal Channels As WMA_9_2_Channels, _
  415.                              Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  416.                              Optional ByVal Update_Tag As Boolean = True, _
  417.                              Optional ByVal Priority As Priority = Priority.normal, _
  418.                              Optional ByVal Processor As Short = 1)
  419.  
  420.        Get_Effects(DSP_Effects)
  421.  
  422.        Set_Main_Arguments("Windows Media Audio 10",
  423.                           In_File,
  424.                           Out_File,
  425.                           If(Not Update_Tag, "-noidtag", ""),
  426.                           Effects,
  427.                           Priority.ToString,
  428.                           Processor.ToString)
  429.  
  430.        p.StartInfo.Arguments &= _
  431.        String.Format("-codec=""Windows Media Audio 9.2"" -settings=""{0} kbps, {1} kHz, {2} CBR""",
  432.                      CInt(Bitrate), _
  433.                      CInt(Khz), _
  434.                      Channels.ToString)
  435.  
  436.        Run_CoreConverter(In_File, Operation.WMA_Conversion)
  437.  
  438.    End Sub
  439.  
  440. #End Region
  441.  
  442. #Region " Run Procedure "
  443.  
  444.    ''' <summary>
  445.    ''' Runs a specific operation of CoreConverter.
  446.    ''' </summary>
  447.    Private Sub Run_CoreConverter(ByVal file As String,
  448.                                  ByVal operation As Operation)
  449.  
  450.        If Me.CheckFileExist Then
  451.            FileExist(file)
  452.        End If
  453.  
  454.        CurrentProgress = 0
  455.  
  456.        p.StartInfo.FileName = Me.CoreConverter_location
  457.        p.Start()
  458.  
  459.        With StartedArgs
  460.            .File = file
  461.            .Operation = operation
  462.        End With
  463.  
  464.        RaiseEvent Started(p, StartedArgs)
  465.  
  466.        While Not p.HasExited
  467.  
  468.            OutputCharacter = ChrW(p.StandardOutput.Read)
  469.  
  470.            If OutputCharacter = "*" Then
  471.                ProgressArgs.Percent = CInt((Threading.Interlocked.Increment(CurrentProgress) / 59) * 100)
  472.                RaiseEvent Progress(p, ProgressArgs)
  473.            End If
  474.  
  475.            If CurrentProgress = 59 Then
  476.                ' I store the last line(s) because it has interesting information:
  477.                ' Example Output: "Conversion completed in 30 seconds x44 realtime encoding"
  478.                InfoMessage = p.StandardOutput.ReadToEnd.Trim
  479.            End If
  480.  
  481.        End While
  482.  
  483.        ' Stores the Error Message (If any)
  484.        ErrorMessage = p.StandardError.ReadToEnd.Trim
  485.  
  486.        If Not String.IsNullOrEmpty(InfoMessage) Then
  487.  
  488.            ' Stores additional information
  489.            ExtraInfo = InfoMessage.Split(Environment.NewLine)
  490.  
  491.            Select Case ExtraInfo.Length
  492.  
  493.                Case 1
  494.                    ElapsedTime = ExtraInfo.Last.Split()(3) & " " & ExtraInfo.Last.Split()(4) ' Example: "50,2 seconds"
  495.  
  496.                Case 2
  497.                    ElapsedTime = ExtraInfo.Last.Split()(4) & " " & ExtraInfo.Last.Split()(5) ' Example: "50,2 seconds"
  498.  
  499.                Case Is < 1, Is > 2
  500.                    Throw New Exception("Unmanaged Process Output Length")
  501.  
  502.            End Select
  503.  
  504.        End If
  505.  
  506.        With ExitedArgs
  507.            .File = file
  508.            .Operation = operation
  509.            .InfoMessage = InfoMessage
  510.            .ErrorMessage = ErrorMessage
  511.            .ElapsedTime = ElapsedTime
  512.        End With
  513.  
  514.        RaiseEvent Exited(p, ExitedArgs)
  515.  
  516.        ' CoreConverter.Close()
  517.  
  518.    End Sub
  519.  
  520. #End Region
  521.  
  522. #Region " Miscellaneous procedures "
  523.  
  524.    ''' <summary>
  525.    ''' Checks if a file exists.
  526.    ''' </summary>
  527.    Private Sub FileExist(ByVal File As String)
  528.  
  529.        If Not IO.File.Exists(File) Then
  530.            ' Throw New Exception("File doesn't exist: " & File)
  531.            MessageBox.Show("File doesn't exist: " & File, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Error)
  532.        End If
  533.  
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Sets the static arguments of CoreConverter process.
  538.    ''' </summary>
  539.    Private Sub Set_Main_Arguments(ByVal Codec_Name As String, _
  540.                                   ByVal In_File As String, _
  541.                                   ByVal Out_File As String, _
  542.                                   ByVal Update_Tag As String, _
  543.                                   ByVal Effects As String, _
  544.                                   ByVal Priority As String, _
  545.                                   ByVal Processor As String)
  546.  
  547.        p.StartInfo.Arguments = _
  548.        String.Format("-infile=""{0}"" -outfile=""{1}"" -convert_to=""{2}"" {3} {4} -priority=""{5}"" -processor=""{6}"" ",
  549.                      In_File,
  550.                      Out_File,
  551.                      Codec_Name,
  552.                      Update_Tag,
  553.                      Effects,
  554.                      Priority,
  555.                      Processor)
  556.  
  557.    End Sub
  558.  
  559.    ''' <summary>
  560.    ''' Join all DSP Effects and returns a formatted string.
  561.    ''' </summary>
  562.    Private Function Get_Effects(ByVal DSP_Effects() As DSP_Effects) As String
  563.  
  564.        If DSP_Effects Is Nothing Then
  565.  
  566.            Return Nothing
  567.  
  568.        Else
  569.  
  570.            For Effect As Integer = 0 To DSP_Effects.Length - 1
  571.                Effects &= String.Format(" -dspeffect{0}={1}", _
  572.                                         Effect + 1, _
  573.                                         Format_DSP_Effect(DSP_Effects(Effect).ToString))
  574.            Next Effect
  575.  
  576.            Return Effects
  577.  
  578.        End If
  579.  
  580.    End Function
  581.  
  582.    ''' <summary>
  583.    ''' Returns a formatted string of a single DSP Effects.
  584.    ''' </summary>
  585.    Private Shared Function Format_DSP_Effect(ByVal Effect As String)
  586.  
  587.        Select Case Effect
  588.  
  589.            Case "Reverse"
  590.                Return """Reverse"""
  591.  
  592.            Case "Delete_Output_File_on_Error"
  593.                Return """Delete Destination File on Error="""
  594.  
  595.            Case "Recycle_Source_File_After_Conversion"
  596.                Return """Delete Source File=-recycle"""
  597.  
  598.            Case "Delete_Source_File_After_Conversion"
  599.                Return """Delete Source File="""
  600.  
  601.            Case "Karaoke_Remove_Voice"
  602.                Return """Karaoke (Voice_ Instrument Removal)="""
  603.  
  604.            Case "Karaoke_Remove_Instrument"
  605.                Return """Karaoke (Voice_ Instrument Removal)=-i"""
  606.  
  607.            Case "Write_Silence"
  608.                Return """Write Silence=-lengthms={qt}2000{qt}""" ' 2 seconds
  609.  
  610.            Case Else
  611.                Return String.Empty
  612.  
  613.        End Select
  614.  
  615.    End Function
  616.  
  617. #End Region
  618.  
  619. #Region " IDisposable "
  620.  
  621.      ''' <summary>
  622.      ''' Disposes the objects generated by this instance.
  623.      ''' </summary>
  624.      Public Sub Dispose() Implements IDisposable.Dispose
  625.          Dispose(True)
  626.          GC.SuppressFinalize(Me)
  627.      End Sub
  628.  
  629.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  630.  
  631.          Static IsBusy As Boolean ' To detect redundant calls.
  632.  
  633.          If Not IsBusy AndAlso IsDisposing Then
  634.  
  635.              p.Dispose()
  636.  
  637.          End If
  638.  
  639.          IsBusy = True
  640.  
  641.      End Sub
  642.  
  643.  #End Region
  644.  
  645. End Class
  646.  
  647. #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 #336 en: 11 Noviembre 2013, 01:40 am »

Una versión mejorada de mi ayudante para la aplicación mp3val... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _mp3val As New mp3val _
  4.                With {.mp3val_location = "C:\windows\system32\mp3val.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            MsgBox(_mp3val.Is_Avaliable()) ' Checks if mp3gain executable is avaliable.
  10.  
  11.            MsgBox(_mp3val.Get_Tags(New IO.FileInfo("C:\File.mp3"))) ' Return the TagTypes of an MP3 file.
  12.  
  13.            _mp3val.Analyze("C:\File.mp3") ' Analyzes an MP3 file.
  14.  
  15.            _mp3val.Fix("C:\File.mp3") ' Fix an MP3 file.
  16.  
  17.        End Sub
  18.  
  19.        ' mp3val [Started]
  20.        Private Sub mp3val_Started(ByVal sender As Process, ByVal e As mp3val.StartedEventArgs) _
  21.        Handles _mp3val.Started
  22.  
  23.            Dim sb As New System.Text.StringBuilder
  24.  
  25.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  26.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  27.            sb.AppendLine(String.Format("mp3val process PID is: ""{0}""", CStr(sender.Id)))
  28.  
  29.            MessageBox.Show(sb.ToString, "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Information)
  30.  
  31.        End Sub
  32.  
  33.        ' mp3val [Exited]
  34.        Private Sub mp3val_Exited(ByVal sender As Process, ByVal e As mp3val.ExitedEventArgs) _
  35.        Handles _mp3val.Exited
  36.  
  37.            Dim sb As New System.Text.StringBuilder
  38.  
  39.            sb.AppendLine(String.Format("Finished an ""{1}"" operation in file ""{2}""{0}",
  40.                                        Environment.NewLine,
  41.                                        e.Operation.ToString,
  42.                                        e.File))
  43.  
  44.            sb.AppendLine(String.Format("File information:{0}{1}{0}",
  45.                                        Environment.NewLine,
  46.                                        e.Info))
  47.  
  48.            sb.AppendLine("Warnings found:")
  49.            If e.Warnings.Count Then
  50.                For Each wrn As String In e.Warnings
  51.                    sb.AppendLine(wrn)
  52.                Next wrn
  53.            Else
  54.                sb.AppendLine("Any" & Environment.NewLine)
  55.            End If
  56.  
  57.            sb.AppendLine("Errors found:")
  58.            If e.Errors.Count Then
  59.                For Each err As String In e.Errors
  60.                    sb.AppendLine(err)
  61.                Next err
  62.            Else
  63.                sb.AppendLine("Any" & Environment.NewLine)
  64.            End If
  65.  
  66.            If e.Operation = mp3val.Operation.Fix Then
  67.                sb.AppendLine(String.Format("File was fixed?: {0}",
  68.                                            e.FileIsFixed))
  69.            End If
  70.  
  71.            MessageBox.Show(sb.ToString,
  72.                            "mp3val",
  73.                            MessageBoxButtons.OK,
  74.                            MessageBoxIcon.Information)
  75.  
  76.        End Sub
  77.  
  78.    End Class

El ayudante:

Código:
' [ mp3val Helper ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "mp3val.exe" into the directory project.

Código
  1. #Region " mp3val Helper "
  2.  
  3. Public Class mp3val : Implements IDisposable
  4.  
  5. #Region " CommandLine parametter legend "
  6.  
  7.    ' -f  | try to fix errors
  8.    ' -nb | delete .bak file
  9.    ' -t  | keep file timestamp
  10.  
  11. #End Region
  12.  
  13. #Region " Variables, Properties, Enums "
  14.  
  15.    ''' <summary>
  16.    ''' Gets or sets the mp3val executable path.
  17.    ''' </summary>
  18.    Public Property mp3val_location As String = ".\mp3val.exe"
  19.  
  20.    ''' <summary>
  21.    ''' Indicates if should check that the MP3 file exist before realize an operation.
  22.    ''' If True, an exception will be launched if file does not exist.
  23.    ''' </summary>
  24.    Public Property CheckFileExist As Boolean = False
  25.  
  26.    ''' <summary>
  27.    ''' Stores the process StandardOutput.
  28.    ''' </summary>
  29.    Private StandardOutput As String = String.Empty
  30.  
  31.    ''' <summary>
  32.    ''' Stores the process StandardError.
  33.    ''' </summary>
  34.    Private StandardError As String = String.Empty
  35.  
  36.    ''' <summary>
  37.    ''' Stores some information about the file.
  38.    ''' </summary>
  39.    Private Info As String = String.Empty
  40.  
  41.    ''' <summary>
  42.    ''' Stores all the warnings of the file.
  43.    ''' </summary>
  44.    Private Warnings As New List(Of String)
  45.  
  46.    ''' <summary>
  47.    ''' Stores all the errors of the file.
  48.    ''' </summary>
  49.    Private Errors As New List(Of String)
  50.  
  51.    ''' <summary>
  52.    ''' Stores the tags of the file.
  53.    ''' </summary>
  54.    Private Tags As String = String.Empty
  55.  
  56.    ''' <summary>
  57.    ''' Gets some information about the file.
  58.    ''' </summary>
  59.    Private Info_RegEx As New System.Text.RegularExpressions.Regex("INFO:.*:\s(.*)",
  60.                              System.Text.RegularExpressions.RegexOptions.Multiline)
  61.  
  62.    ''' <summary>
  63.    ''' Gets all the warning occurences.
  64.    ''' </summary>
  65.    Private Warning_RegEx As New System.Text.RegularExpressions.Regex("WARNING:.*:\s(.*)",
  66.                                 System.Text.RegularExpressions.RegexOptions.Multiline)
  67.  
  68.    ''' <summary>
  69.    ''' Gets a value indicating if the file was fixed or not.
  70.    ''' </summary>
  71.    Private Fixed_RegEx As New System.Text.RegularExpressions.Regex("^FIXED:",
  72.                               System.Text.RegularExpressions.RegexOptions.Multiline)
  73.  
  74.    ''' <summary>
  75.    ''' mp3val Process
  76.    ''' </summary>
  77.    Private p As Process =
  78.        New Process With {.StartInfo =
  79.            New ProcessStartInfo With {
  80.                  .CreateNoWindow = True,
  81.                  .UseShellExecute = False,
  82.                  .RedirectStandardError = True,
  83.                  .RedirectStandardOutput = True _
  84.           }
  85.        }
  86.  
  87.    ''' <summary>
  88.    ''' Stores the StartedEventArgs Arguments.
  89.    ''' </summary>
  90.    Private StartedArgs As New StartedEventArgs
  91.  
  92.    ''' <summary>
  93.    ''' Stores the ExitedEventArgs Arguments.
  94.    ''' </summary>
  95.    Private ExitedArgs As New ExitedEventArgs
  96.  
  97.    ''' <summary>
  98.    ''' MP3Val Type Of Operation.
  99.    ''' </summary>
  100.    Public Enum Operation As Short
  101.        Analyze = 0
  102.        Fix = 1
  103.        Get_Tags = 2
  104.    End Enum
  105.  
  106. #End Region
  107.  
  108. #Region " Events "
  109.  
  110.    ''' <summary>
  111.    ''' Event raised when the process has started.
  112.    ''' </summary>
  113.    Public Event Started As EventHandler(Of StartedEventArgs)
  114.    Public Class StartedEventArgs : Inherits EventArgs
  115.        ''' <summary>
  116.        ''' Gets the file that was passed as argument to the process.
  117.        ''' </summary>
  118.        Public Property File As String
  119.        ''' <summary>
  120.        ''' Gets the type of operation to realize.
  121.        ''' </summary>
  122.        Public Property Operation As Operation
  123.    End Class
  124.  
  125.    ''' <summary>
  126.    ''' Event raised when the process has exited.
  127.    ''' </summary>
  128.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  129.    Public Class ExitedEventArgs : Inherits EventArgs
  130.        ''' <summary>
  131.        ''' Gets the file that was passed as argument to the process.
  132.        ''' </summary>
  133.        Public Property File As String
  134.        ''' <summary>
  135.        ''' Gets the type of operation to realize.
  136.        ''' </summary>
  137.        Public Property Operation As Operation
  138.        ''' <summary>
  139.        ''' Gets some information about the file.
  140.        ''' </summary>
  141.        Public Property Info As String
  142.        ''' <summary>
  143.        ''' Gets the warnings found.
  144.        ''' </summary>
  145.        Public Property Warnings As New List(Of String)
  146.        ''' <summary>
  147.        ''' Gets the errors found.
  148.        ''' </summary>
  149.        Public Property Errors As New List(Of String)
  150.        ''' <summary>
  151.        ''' Gets a value indicating if file was fixed.
  152.        ''' This is only usefull when doing a Fix operation.
  153.        ''' </summary>
  154.        Public Property FileIsFixed As Boolean
  155.    End Class
  156.  
  157. #End Region
  158.  
  159. #Region " MP3Val Procedures "
  160.  
  161.    ''' <summary>
  162.    ''' Checks if mp3val process is avaliable.
  163.    ''' </summary>
  164.    Public Function Is_Avaliable() As Boolean
  165.        Return IO.File.Exists(Me.mp3val_location)
  166.    End Function
  167.  
  168.    ''' <summary>
  169.    ''' Analyzes a file and returns the problems (if any).
  170.    ''' </summary>
  171.    Public Function Analyze(ByVal MP3_File As String) As List(Of String)
  172.  
  173.        Return Run_MP3VAL(MP3_File,
  174.                          Operation.Analyze,
  175.                          ControlChars.Quote & MP3_File & ControlChars.Quote)
  176.  
  177.    End Function
  178.  
  179.    ''' <summary>
  180.    ''' Analyzes a file and returns the problems (if any).
  181.    ''' </summary>
  182.    Public Function Analyze(ByVal MP3_File As IO.FileInfo) As List(Of String)
  183.  
  184.        Return Run_MP3VAL(MP3_File.FullName,
  185.                          Operation.Analyze,
  186.                          ControlChars.Quote & MP3_File.FullName & ControlChars.Quote)
  187.  
  188.    End Function
  189.  
  190.    ''' <summary>
  191.    ''' Try to Fix/Rebuild problems of a file,
  192.    ''' and returns a value indicating if file was fixed or not.
  193.    ''' </summary>
  194.    Public Function Fix(ByVal MP3_File As String,
  195.                        Optional ByVal Delete_Backup_File As Boolean = False,
  196.                        Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean
  197.  
  198.        Return Run_MP3VAL(MP3_File,
  199.                          Operation.Fix,
  200.                          String.Format("-f {0} {1} ""{2}""",
  201.                                        If(Delete_Backup_File, "-nb", ""),
  202.                                        If(Preserve_Datestamp, "-t", ""),
  203.                                        MP3_File))
  204.  
  205.    End Function
  206.  
  207.    ''' <summary>
  208.    ''' Try to Fix/Rebuild problems of a file,
  209.    ''' and returns a value indicating if file was fixed or not.
  210.    ''' </summary>
  211.    Public Function Fix(ByVal MP3_File As IO.FileInfo,
  212.                        Optional ByVal Delete_Backup_File As Boolean = False,
  213.                        Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean
  214.  
  215.        Return Run_MP3VAL(MP3_File.FullName,
  216.                          Operation.Fix,
  217.                          String.Format("-f {0} {1} ""{2}""",
  218.                                        If(Delete_Backup_File, "-nb", ""),
  219.                                        If(Preserve_Datestamp, "-t", ""),
  220.                                        MP3_File.FullName))
  221.  
  222.    End Function
  223.  
  224.    ''' <summary>
  225.    ''' Return the metadata ID types of a file.
  226.    ''' </summary>
  227.    Public Function Get_Tags(ByVal MP3_File As String) As String
  228.  
  229.        Return Run_MP3VAL(MP3_File,
  230.                          Operation.Get_Tags,
  231.                          ControlChars.Quote & MP3_File & ControlChars.Quote)
  232.  
  233.    End Function
  234.  
  235.    ''' <summary>
  236.    ''' Return the metadata ID types of a file.
  237.    ''' </summary>
  238.    Public Function Get_Tags(ByVal MP3_File As IO.FileInfo) As String
  239.  
  240.        Return Run_MP3VAL(MP3_File.FullName,
  241.                          Operation.Get_Tags,
  242.                          ControlChars.Quote & MP3_File.FullName & ControlChars.Quote)
  243.  
  244.    End Function
  245.  
  246. #End Region
  247.  
  248. #Region " Run Procedure "
  249.  
  250.    ''' <summary>
  251.    ''' Runs mp3val process.
  252.    ''' </summary>
  253.    Private Function Run_MP3VAL(ByVal MP3_File As String,
  254.                                ByVal operation As Operation,
  255.                                ByVal arguments As String) As Object
  256.  
  257.        If Me.CheckFileExist Then
  258.            FileExist(MP3_File)
  259.        End If
  260.  
  261.        With p.StartInfo
  262.            .FileName = Me.mp3val_location
  263.            .Arguments = arguments
  264.        End With
  265.  
  266.        Warnings.Clear() : Errors.Clear()
  267.  
  268.        p.Start()
  269.        RaiseEvent_Started(MP3_File, operation)
  270.        p.WaitForExit()
  271.  
  272.        StandardError = p.StandardError.ReadToEnd
  273.        StandardOutput = p.StandardOutput.ReadToEnd
  274.  
  275.        Info = Info_RegEx.Match(StandardOutput).Groups(1).Value.Trim
  276.  
  277.        For Each m As System.Text.RegularExpressions.Match In Warning_RegEx.Matches(StandardOutput)
  278.            Warnings.Add(m.Groups(1).Value)
  279.        Next m
  280.  
  281.        For Each e As String In StandardError.Split(Environment.NewLine)
  282.            If Not String.IsNullOrEmpty(e.Trim) Then
  283.                Errors.Add(e)
  284.            End If
  285.        Next e
  286.  
  287.        Select Case operation
  288.  
  289.            Case mp3val.Operation.Analyze
  290.                RaiseEvent_Exited(MP3_File,
  291.                                  operation.Analyze,
  292.                                  Info,
  293.                                  Warnings.Distinct.ToList,
  294.                                  Errors,
  295.                                  False)
  296.  
  297.                Return Warnings.Concat(Errors).Distinct.ToList
  298.  
  299.            Case mp3val.Operation.Fix
  300.                RaiseEvent_Exited(MP3_File,
  301.                                  operation.Fix,
  302.                                  Info,
  303.                                  Warnings.Distinct.ToList,
  304.                                  Errors,
  305.                                  Fixed_RegEx.IsMatch(StandardOutput))
  306.  
  307.                Return Fixed_RegEx.IsMatch(StandardOutput)
  308.  
  309.            Case mp3val.Operation.Get_Tags
  310.                RaiseEvent_Exited(MP3_File,
  311.                                  operation.Get_Tags,
  312.                                  Info,
  313.                                  Warnings.Distinct.ToList,
  314.                                  Errors,
  315.                                  False)
  316.  
  317.                If Not String.IsNullOrEmpty(Info) Then
  318.  
  319.                    Tags = Info.Split(",")(1).Trim
  320.  
  321.                    If Tags = "no tags" Then
  322.                        Return "No tags"
  323.                    Else
  324.                        Return Tags.Substring(1).Replace("+", ", ")
  325.                    End If
  326.  
  327.                Else
  328.  
  329.                    Return "Can't examine tag type."
  330.  
  331.                End If
  332.  
  333.            Case Else
  334.                Return Nothing
  335.  
  336.        End Select
  337.  
  338.    End Function
  339.  
  340. #End Region
  341.  
  342. #Region " Miscellaneous preocedures "
  343.  
  344.    ''' <summary>
  345.    ''' Checks if a file exists.
  346.    ''' </summary>
  347.    Private Sub FileExist(ByVal File As String)
  348.  
  349.        If Not IO.File.Exists(File) Then
  350.            Throw New Exception(String.Format("File doesn't exist: ""{0}""", File))
  351.            ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Error)
  352.        End If
  353.  
  354.    End Sub
  355.  
  356.    ''' <summary>
  357.    ''' Raises the Event Started
  358.    ''' </summary>
  359.    Private Sub RaiseEvent_Started(ByVal File As String,
  360.                                   ByVal Operation As Operation)
  361.  
  362.        With StartedArgs
  363.            .File = File
  364.            .Operation = Operation
  365.        End With
  366.  
  367.        RaiseEvent Started(p, StartedArgs)
  368.  
  369.    End Sub
  370.  
  371.    ''' <summary>
  372.    ''' Raises the Event Exited
  373.    ''' </summary>
  374.    Private Sub RaiseEvent_Exited(ByVal File As String,
  375.                                  ByVal Operation As Operation,
  376.                                  ByVal Info As String,
  377.                                  ByVal Warnings As List(Of String),
  378.                                  ByVal Errors As List(Of String),
  379.                                  ByVal IsFixed As Boolean)
  380.  
  381.        With ExitedArgs
  382.            .File = File
  383.            .Operation = Operation
  384.            .Info = Info
  385.            .Warnings = Warnings
  386.            .Errors = Errors
  387.            .FileIsFixed = IsFixed
  388.        End With
  389.  
  390.        RaiseEvent Exited(p, ExitedArgs)
  391.  
  392.    End Sub
  393.  
  394. #End Region
  395.  
  396. #Region " IDisposable "
  397.  
  398.      ''' <summary>
  399.      ''' Disposes the objects generated by this instance.
  400.      ''' </summary>
  401.      Public Sub Dispose() Implements IDisposable.Dispose
  402.          Dispose(True)
  403.          GC.SuppressFinalize(Me)
  404.      End Sub
  405.  
  406.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  407.  
  408.          Static IsBusy As Boolean ' To detect redundant calls.
  409.  
  410.          If Not IsBusy AndAlso IsDisposing Then
  411.  
  412.              p.Dispose()
  413.  
  414.          End If
  415.  
  416.          IsBusy = True
  417.  
  418.      End Sub
  419.  
  420.  #End Region
  421.  
  422. End Class
  423.  
  424. #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 #337 en: 11 Noviembre 2013, 01:44 am »

Un pequeño hook para capturar los mensajes del menú de edición del menú contextual (por defecto) de un Textbox (las opciones de copiar, pegar, cortar, y eliminar).

En un post anterior posteé la forma de capturarl dichos mensajes heredando el Textbox, pero este código es diferente, no depende de ningun control, se puede usar como otra Class cualquiera para capturar los mensajes en cualquier textbox (menos los textbox de Krypton y otros...) sin necesidad de heredar el control.

PD: El código no es del todo de mi propiedad, me han ayudado un poquito.

Código
  1. #Region " Capture Windows ContextMenu Edit Options "
  2.  
  3. ' [ Capture Windows ContextMenu Edit Options ]
  4. '
  5. ' Examples :
  6. '
  7. ' Public Class Form1
  8. '
  9. '     Private WithEvents EditMenu As New EditMenuHook
  10. '
  11. '     Protected Overrides Sub OnLoad(e As EventArgs)
  12. '         MyBase.OnLoad(e)
  13. '         ' Capture the EditMenu Messages for TextBox1 and TextBox2
  14. '         EditMenuHook.Controls = {TextBox1, TextBox2}
  15. '         ' Enable the Hook
  16. '         EditMenuHook.Enable(True)
  17. '     End Sub
  18. '
  19. '     Protected Overrides Sub OnClosed(e As EventArgs)
  20. '         ' Disable the Hook
  21. '         EditMenuHook.Enable(False)
  22. '         MyBase.OnClosed(e)
  23. '     End Sub
  24. '
  25. '     Private Sub TextBox_OnTextCommand(sender As Object, e As EditMenuHook.TextCommandEventArgs) _
  26. '     Handles EditMenu.OnCopy, EditMenu.OnCut, EditMenu.OnPaste, EditMenu.OnDelete
  27. '
  28. '         MessageBox.Show(String.Format("Control:{0}  Message:{1}", sender.name, e.Command.ToString))
  29. '
  30. '     End Sub
  31. '
  32. ' End Class
  33.  
  34. Imports System.Runtime.InteropServices
  35.  
  36. Friend Class EditMenuHook
  37.  
  38.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  39.    Public Overloads Shared Function SetWindowsHookEx _
  40.          (ByVal idHook As Integer, ByVal HookProc As CallBack, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
  41.    End Function
  42.  
  43.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  44.    Public Overloads Shared Function CallNextHookEx _
  45.          (ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  46.    End Function
  47.  
  48.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  49.    Public Overloads Shared Function UnhookWindowsHookEx _
  50.              (ByVal idHook As Integer) As Boolean
  51.    End Function
  52.  
  53.    Public Enum TextCommandMessage
  54.        WM_CUT = &H300
  55.        WM_COPY = &H301
  56.        WM_PASTE = &H302
  57.        WM_DELETE = &H303
  58.    End Enum
  59.  
  60.    Public Structure CWPSTRUCT
  61.        Public lParam As IntPtr
  62.        Public wParam As IntPtr
  63.        Public message As UInt32
  64.        Public hWnd As IntPtr
  65.    End Structure
  66.  
  67.    Public Delegate Function CallBack( _
  68.        ByVal nCode As Integer, _
  69.        ByVal wParam As IntPtr, _
  70.        ByVal lParam As IntPtr) As Integer
  71.  
  72.    Private Shared WithEvents CopyOrCut_Timer As New Timer _
  73.                   With {.Interval = 50, .Enabled = False}
  74.  
  75.    ' The Control to monitor and report the TextCommand Messages.
  76.    Public Shared Controls As Control() = Nothing
  77.  
  78.    Public Shared MessagesEnabled As Boolean = True
  79.  
  80.    Private Shared CopyMessageEnabled As Boolean = True
  81.  
  82.    Shared hHook As Integer = 0
  83.  
  84.    Private Shared cwp As CWPSTRUCT
  85.  
  86.    Private Const WH_CALLWNDPROC = 4
  87.  
  88.    'Keep the reference so that the delegate is not garbage collected.
  89.    Private Shared hookproc As CallBack
  90.  
  91.    Public Class TextCommandEventArgs
  92.        Inherits EventArgs
  93.        Public Property Command As TextCommandMessage
  94.    End Class
  95.  
  96.    Shared Event OnCut(sender As Object, e As TextCommandEventArgs)
  97.    Shared Event OnCopy(sender As Object, e As TextCommandEventArgs)
  98.    Shared Event OnPaste(sender As Object, e As TextCommandEventArgs)
  99.    Shared Event OnDelete(sender As Object, e As TextCommandEventArgs)
  100.  
  101.    Friend Shared Sub Enable(enable As Boolean)
  102.  
  103.        If hHook = 0 AndAlso enable = True Then
  104.  
  105.            hookproc = AddressOf EditCommandHook
  106.            hHook = SetWindowsHookEx(WH_CALLWNDPROC, _
  107.                                     hookproc, _
  108.                                     IntPtr.Zero, _
  109.                                     AppDomain.GetCurrentThreadId())
  110.  
  111.            If hHook.Equals(0) Then
  112.                MsgBox("SetWindowsHookEx Failed")
  113.                Return
  114.            End If
  115.  
  116.        ElseIf hHook <> 0 AndAlso enable = False Then
  117.  
  118.            Dim ret As Boolean = UnhookWindowsHookEx(hHook)
  119.  
  120.            If ret.Equals(False) Then
  121.                MsgBox("UnhookWindowsHookEx Failed")
  122.                Return
  123.            Else
  124.                hHook = 0
  125.            End If
  126.  
  127.        End If
  128.  
  129.    End Sub
  130.  
  131.    Private Shared Function EditCommandHook(ByVal nCode As Integer, _
  132.                                            ByVal wParam As IntPtr, _
  133.                                            ByVal lParam As IntPtr) As Integer
  134.  
  135.        If nCode < 0 Then
  136.            Return CallNextHookEx(hHook, nCode, wParam, lParam)
  137.        End If
  138.  
  139.        cwp = DirectCast(Marshal.PtrToStructure(lParam, GetType(CWPSTRUCT)), CWPSTRUCT)
  140.  
  141.        For Each ctrl As Control In Controls
  142.  
  143.            If cwp.hWnd = ctrl.Handle Then
  144.  
  145.                Select Case cwp.message
  146.  
  147.                    Case TextCommandMessage.WM_CUT
  148.                        CopyMessageEnabled = False
  149.                        RaiseEvent OnCut(ctrl, New TextCommandEventArgs() _
  150.                                               With {.Command = TextCommandMessage.WM_CUT})
  151.  
  152.                    Case TextCommandMessage.WM_COPY
  153.                        If CopyMessageEnabled Then
  154.                            RaiseEvent OnCopy(ctrl, New TextCommandEventArgs() _
  155.                                                    With {.Command = TextCommandMessage.WM_COPY})
  156.                        Else
  157.                            CopyMessageEnabled = True
  158.                        End If
  159.  
  160.                    Case TextCommandMessage.WM_PASTE
  161.                        RaiseEvent OnPaste(ctrl, New TextCommandEventArgs() _
  162.                                                 With {.Command = TextCommandMessage.WM_PASTE})
  163.  
  164.                    Case TextCommandMessage.WM_DELETE
  165.                        RaiseEvent OnDelete(ctrl, New TextCommandEventArgs() _
  166.                                                  With {.Command = TextCommandMessage.WM_DELETE})
  167.  
  168.                End Select
  169.  
  170.            End If
  171.        Next
  172.  
  173.        Return CallNextHookEx(hHook, nCode, wParam, lParam)
  174.  
  175.    End Function
  176.  
  177. End Class
  178.  
  179. #End Region
« Última modificación: 11 Noviembre 2013, 01:45 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 #338 en: 12 Noviembre 2013, 18:22 pm »

Devuelve un Array con las ocurrencias que se encuentren de una Value en un Diccionario

Código
  1. #Region " Match Dictionary Values "
  2.  
  3.    ' [ Match Dictionary Values ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Match_Dictionary_Values(New Dictionary(Of Integer, String) From {{1, "Hello World!"}},
  10.    '                                "hello", False, StringComparison.CurrentCultureIgnoreCase).First.Value)
  11.  
  12.    Private Function Match_Dictionary_Values(Of K)(
  13.                     ByVal Dictionary As Dictionary(Of K, String),
  14.                     ByVal Value As String,
  15.                     ByVal MatchWholeWord As Boolean,
  16.                     ByVal IgnoreCase As StringComparison) As KeyValuePair(Of K, String)()
  17.  
  18.        If MatchWholeWord Then
  19.  
  20.            Return (From kp As KeyValuePair(Of K, String) In Dictionary
  21.                    Where String.Compare(kp.Value, Value, IgnoreCase) = 0).ToArray
  22.        Else
  23.  
  24.            Return (From kp As KeyValuePair(Of K, String) In Dictionary
  25.                    Where kp.Value.IndexOf(Value, 0, IgnoreCase) > -1).ToArray
  26.  
  27.        End If
  28.  
  29.    End Function
  30.  
  31. #End Region





Devuelve un Array con las ocurrencias que se encuentren de una Key en un Diccionario

Código
  1. #Region " Match Dictionary Keys "
  2.  
  3.    ' [ Match Dictionary Keys ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Match_Dictionary_Keys(New Dictionary(Of String, Integer) From {{"Hello World!", 1}},
  10.    '                              "hello", False, StringComparison.CurrentCultureIgnoreCase).First.Key)
  11.  
  12.    Private Function Match_Dictionary_Keys(Of V)(
  13.                     ByVal Dictionary As Dictionary(Of String, V),
  14.                     ByVal Key As String,
  15.                     ByVal MatchWholeWord As Boolean,
  16.                     ByVal IgnoreCase As StringComparison) As KeyValuePair(Of String, V)()
  17.  
  18.        If MatchWholeWord Then
  19.  
  20.            Return (From kp As KeyValuePair(Of String, V) In Dictionary
  21.                    Where String.Compare(kp.Key, Key, IgnoreCase) = 0).ToArray
  22.        Else
  23.  
  24.            Return (From kp As KeyValuePair(Of String, V) In Dictionary
  25.                    Where kp.Key.IndexOf(Key, 0, IgnoreCase) > -1).ToArray
  26.  
  27.        End If
  28.  
  29.    End Function
  30.  
  31. #End Region





Devuelve True si se encuentra alguna ocurrencia de un Value en un Diccionario.

Código
  1. #Region " Find Dictionary Value "
  2.  
  3.    ' [ Find Dictionary Value ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    '  MsgBox(Find_Dictionary_Value(
  10.    '         New Dictionary(Of Integer, String) From {{1, "ABC"}},
  11.    '         "abc", True, StringComparison.CurrentCultureIgnoreCase))
  12.  
  13.    Private Function Find_Dictionary_Value(Of K)(
  14.                     ByVal Dictionary As Dictionary(Of K, String),
  15.                     ByVal Value As String,
  16.                     ByVal MatchWholeWord As Boolean,
  17.                     ByVal IgnoreCase As StringComparison) As Boolean
  18.  
  19.        If MatchWholeWord Then
  20.  
  21.            Return (From kp As KeyValuePair(Of K, String) In Dictionary
  22.                    Where String.Compare(kp.Value, Value, IgnoreCase) = 0).Any
  23.        Else
  24.  
  25.            Return (From kp As KeyValuePair(Of K, String) In Dictionary
  26.                    Where kp.Value.IndexOf(Value, 0, IgnoreCase) > -1).Any
  27.  
  28.        End If
  29.  
  30.    End Function
  31.  
  32. #End Region




Devuelve True si se encuentra alguna ocurrencia de una Key en un Diccionario.

Código
  1. #Region " Find Dictionary Key "
  2.  
  3.    ' [ Find Dictionary Key ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Find_Dictionary_Key(
  10.    '        New Dictionary(Of String, Integer) From {{"ABC", 1}},
  11.    '        "abc", True, StringComparison.CurrentCultureIgnoreCase))
  12.  
  13.    Private Function Find_Dictionary_Key(Of V)(
  14.                     ByVal Dictionary As Dictionary(Of String, V),
  15.                     ByVal Key As String,
  16.                     ByVal MatchWholeWord As Boolean,
  17.                     ByVal IgnoreCase As StringComparison) As Boolean
  18.  
  19.        If MatchWholeWord Then
  20.  
  21.            Return (From kp As KeyValuePair(Of String, V) In Dictionary
  22.                    Where String.Compare(kp.Key, Key, IgnoreCase) = 0).Any
  23.        Else
  24.  
  25.            Return (From kp As KeyValuePair(Of String, V) In Dictionary
  26.                    Where kp.Key.IndexOf(Key, 0, IgnoreCase) > -1).Any
  27.  
  28.        End If
  29.  
  30.    End Function
  31.  
  32. #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 #339 en: 13 Noviembre 2013, 06:23 am »

Quiero compartir con ustedes este SystemMenu Manager, como su nombre indica, es un ayudante para manejar el SystemMenu, le añadi infinidad de métodos y el uso de eventos para manejar de forma sencilla los items que agreguemos... además lo he documentado todo muy bien, aunque me he dejado bastantes comentarios XML (es bastante tedioso), a pesar de las 1.600 lineas de código, aun le faltaría añadir bastantes métodos más, pero bueno, por el momento así está muy bien, espero que lo disfruten.


Unas imágenes:

   

   




Un ejemplo de uso:

( Nótese que todos los métodos tienen su overload para utilizar una posición de item en lugar de un item predefinido. )

Código
  1. Public Class Form1
  2.  
  3.     Private WithEvents SystemMenu As New SystemMenuManager(Me)
  4.  
  5.     Private Shadows Sub Shown() Handles MyBase.Shown
  6.  
  7.        ' Gets the total amount of menu items.
  8.        ' MsgBox(SystemMenu.GetItemCount())
  9.  
  10.        ' Sets the menu background color.
  11.         SystemMenu.SetMenuBackColor(Color.Teal)
  12.  
  13.        ' Sets the menu style.
  14.        ' SystemMenu.SetMenuStyle(SystemMenuManager.MenuStyle.AUTODISMIS)
  15.  
  16.        ' Sets the state of the Close button and menu item.
  17.        ' SystemMenu.SetItemState(SystemMenuManager.Item.Close, SystemMenuManager.ItemState.Disabled)
  18.  
  19.        ' Sets the Bitmap image of the Move menu item.
  20.        ' SystemMenu.SetItemBitmap(SystemMenuManager.Item.Move, New Bitmap("C:\File.png"))
  21.  
  22.        ' Gets the Bitmap image of the Move menu item.
  23.        ' Dim bmp As Bitmap = SystemMenu.GetItemBitmap(SystemMenuManager.Item.Move)
  24.  
  25.        ' Removes the Bitmap image of the Move menu item.
  26.        ' SystemMenu.RemoveItemBitmap(SystemMenuManager.Item.Move)
  27.  
  28.        ' Adds a separator at the bottom.
  29.         SystemMenu.AddSeparator(SystemMenuManager.DefaultPositions.Last)
  30.  
  31.        ' Adds an item at the bottom.
  32.         SystemMenu.AddItem("Hello World!", 666, SystemMenuManager.DefaultPositions.Last)
  33.  
  34.        ' Gets the ID of an item.
  35.        ' MsgBox(SystemMenu.GetItemState(SystemMenuManager.Item.Move).ToString)
  36.  
  37.        ' Gets the text of an item.
  38.        ' MsgBox(SystemMenu.GetItemText(SystemMenuManager.Item.Move))
  39.  
  40.        ' Gets the state of an item.
  41.        ' MsgBox(SystemMenu.GetItemState(SystemMenuManager.Item.Move).ToString)
  42.  
  43.        ' Sets the text of an item.
  44.        ' SystemMenu.SetItemText(SystemMenuManager.Item.Move, "Muéveme")
  45.  
  46.        ' Checks if a handle is a menu handle.
  47.        ' MsgBox(SystemMenu.IsMenuHandle(IntPtr.Zero))
  48.  
  49.        ' Disable all the menu items.
  50.        ' SystemMenu.DisableAllItems()
  51.  
  52.        ' Re-enable all the menu items.
  53.        ' SystemMenu.EnableAllItems()
  54.  
  55.        ' Remove all the menu items.
  56.        ' SystemMenu.RemoveAllItems()
  57.  
  58.        ' Restore the menu to defaults.
  59.        '  SystemMenu.Restore_Menu()
  60.  
  61.        ' Dispose the SystemMenuManager Object.
  62.        ' SystemMenu.Dispose()
  63.  
  64. End Sub
  65.  
  66.         ' SystemMenu [MenuItemClicked]
  67.        Private Sub SystemMenu_MenuItemClicked(
  68.                ByVal MenuHandle As IntPtr,
  69.                ByVal e As SystemMenuManager.ItemClickedEventArgs
  70.        ) Handles SystemMenu.ItemClicked
  71.  
  72.            Dim sr As New System.Text.StringBuilder
  73.  
  74.            sr.AppendLine(String.Format("Item ID   : {0}", CStr(e.ID)))
  75.            sr.AppendLine(String.Format("Item Text : {0}", e.Text))
  76.            sr.AppendLine(String.Format("Item Type : {0}", e.Type.ToString))
  77.            sr.AppendLine(String.Format("Item State: {0}", e.State.ToString))
  78.  
  79.            MessageBox.Show(sr.ToString, "SystemMenuManager", MessageBoxButtons.OK, MessageBoxIcon.Information)
  80.  
  81.     End Sub
  82.  
  83. End Class


La Class la pueden ver en ESTE enlace de pastebin (no cabe en este post).
« Última modificación: 13 Noviembre 2013, 06:27 am por EleKtro H@cker » En línea

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

Ir a:  

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