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

 

 


Tema destacado: Introducción a Git (Primera Parte)


+  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 4 Visitantes 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 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 526,946 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #90 en: 20 Abril 2013, 06:02 am »

· Usar un proxy en el WebBrowser:

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


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

[ListView] Restrict column resizing

Restringe cambiar de tamaño una columna.


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



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

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


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

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



En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

If Debug conditional

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



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



String Format
Ejemplo de un String Format

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



Get NT Version

Devuelve la versión NT de Windows

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

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



Extract Icon
Devuelve el icono de un archivo

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

[OSVersionInfo] - Examples

Ejemplos de uso de OSVersionInfo

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

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

« Última modificación: 30 Abril 2013, 13:28 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #93 en: 30 Abril 2013, 13:26 pm »

Cambia el theme actual de Windows

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

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



Devuelve información del theme actual

PD: Yo solo he creado la función.

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



Escribe texto a la CMD desde un proyecto Windowsforms

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




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

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





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

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

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



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

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



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

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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #94 en: 30 Abril 2013, 21:55 pm »

Comprueba si es la primera ejecuciónd e la aplicación.

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

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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #95 en: 2 Mayo 2013, 10:23 am »

Elimina el contenido del portapapeles

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



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

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

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

En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #96 en: 4 Mayo 2013, 16:44 pm »

Elimina el contenido del portapapeles:

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




Devuelve el color de un pixel en varios formatos:

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

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




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

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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #97 en: 4 Mayo 2013, 18:26 pm »

Un snippet para medir el tiempo transcurrido para un procedimiento o una función o cualquier cosa:

MEJORADO:




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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #98 en: 5 Mayo 2013, 08:59 am »

Para bloquear procesos.

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



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #99 en: 7 Mayo 2013, 11:53 am »

Me he currado esta class para manejar la aplicación ResHacker, para añadir/eliminar/reemplazar/Extraer iconos u otros tipos de recursos de un archivo:

Ejemplos de uso:

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

Ir a:  

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