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

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 55 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 341,444 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #100 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):






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


En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #101 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


En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #102 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
« Última modificación: 7 Mayo 2013, 15:22 pm por EleKtro H@cker » En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #103 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
En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #104 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
« Última modificación: 7 Mayo 2013, 15:25 pm por EleKtro H@cker » En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #105 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
« Última modificación: 17 Abril 2014, 22:30 pm por Eleкtro » En línea


ABDERRAMAH


Desconectado Desconectado

Mensajes: 431


en ocasiones uso goto ¬¬


Ver Perfil WWW
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #106 en: 7 Mayo 2013, 16:46 pm »

Mother of god, que bueno ese último. Seguro que se me ocurre alguna aplicación...
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #107 en: 7 Mayo 2013, 19:17 pm »



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.  







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
« Última modificación: 7 Mayo 2013, 19:19 pm por EleKtro H@cker » En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #108 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
En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.701



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #109 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
En línea


Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 55 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Desproteger algunas funciones
Ingeniería Inversa
Giusseppe1342 1 1,645 Último mensaje 15 Abril 2009, 01:52 am
por tena
Funciones utiles [batch]
Scripting
<< Lucas, ¿quién más? >> 4 3,876 Último mensaje 21 Febrero 2010, 22:05 pm
por xassiz_
Funciones útiles con gráficos (GDI+)
.NET (C#, VB.NET, ASP)
ABDERRAMAH 0 1,188 Último mensaje 4 Septiembre 2012, 16:09 pm
por ABDERRAMAH
Conoce otras útiles funciones adicionales de Google además de «buscar»
Noticias
wolfbcn 0 985 Último mensaje 8 Octubre 2016, 14:33 pm
por wolfbcn
Probamos Android P, la gran apuesta de Google:estas son sus funciones más útiles
Noticias
wolfbcn 0 606 Último mensaje 12 Mayo 2018, 01:33 am
por wolfbcn
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines