Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 1 Visitante están viendo este tema.

TrashAmbishion

Ja no tienes nada que hacer verdad !! GRacias por los aportes  ;-) ;-) ;-) ;-) ;-)

::) ;D

Dale suave !!

Eleкtro

· Comprimir con DotNetZip


Código (vbnet) [Seleccionar]
#Region " DotNetZip Compress "

    ' [ DotNetZip Compress Function ]
    '
    ' // By Elektro H@cker
    '
    ' Instructions :
    ' 1. Add a reference to "Ionic.Zip.dll".
    ' 2. Use the code below.
    '
    ' Examples:
    ' DotNetZip_Compress("C:\File.txt")
    ' DotNetZip_Compress("C:\Folder")
    ' DotNetZip_Compress("C:\Folder", "C:\Folder\Test.zip", , CompressionLevel.BestCompression, "Password", EncryptionAlgorithm.WinZipAes256)

    Imports Ionic.Zip
    Imports Ionic.Zlib

    Private Function DotNetZip_Compress(ByVal Input_DirOrFile As String, _
                                      Optional ByVal OutputFileName As String = Nothing, _
                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
                                      Optional ByVal Password As String = Nothing, _
                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None _
                                    ) As Boolean
        Try
            ' Create compressor
            Dim Compressor As ZipFile = New ZipFile

            ' Set compression parameters
            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
            Compressor.CompressionMethod = CompressionMethod ' Compression method
            Compressor.Password = Password ' Zip Password
            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations

            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then _
                 Compressor.Encryption = EncryptionAlgorithm.None _
            Else Compressor.Encryption = Encrypt_Password ' Encryption for Zip password.

            ' Add Progress Handler
            ' AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_Progress

            ' Removes the end slash ("\") if is given for a directory.
            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)

            ' Generate the OutputFileName if any is given.
            If OutputFileName Is Nothing Then _
                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".zip").Replace("\\", "\")

            ' Check if given argument is Dir or File ...then start the compression
            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
                Compressor.AddDirectory(Input_DirOrFile)
            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
                Compressor.AddFile(Input_DirOrFile)
            End If

            Compressor.Save(OutputFileName)
            Compressor.Dispose()

        Catch ex As Exception
            'Return False ' File not compressed
            Throw New Exception(ex.Message)
        End Try

        Return True ' File compressed

    End Function

    'Public Sub DotNetZip_Compress_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
    '
    '    If e.EventType = ZipProgressEventType.Saving_Started Then
    '        MsgBox("Begin Saving: " & _
    '               e.ArchiveName) ' Destination ZIP filename
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
    '        MsgBox("Writing: " & e.CurrentEntry.FileName & _
    '               " (" & (e.EntriesSaved + 1) & "/" & e.EntriesTotal & ")") ' Input filename to be compressed
    '
    '        ' ProgressBar2.Maximum = e.EntriesTotal   ' Count of total files to compress
    '        ' ProgressBar2.Value = e.EntriesSaved + 1 ' Count of compressed files
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_EntryBytesRead Then
    '        ' ProgressBar1.Value = CType((e.BytesTransferred * 100) / e.TotalBytesToTransfer, Integer) ' Total Progress
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
    '        MessageBox.Show("Compression Done: " & vbNewLine & _
    '                        e.ArchiveName) ' Compression finished
    '    End If
    '
    'End Sub

#End Region







· Crear un SFX con DotNetZip

Código (vbnet) [Seleccionar]
#Region " DotNetZip Compress SFX "


    ' [ DotNetZip Compress SFX Function ]
    '
    ' // By Elektro H@cker
    '
    ' Instructions :
    ' 1. Add a reference to "Ionic.Zip.dll".
    ' 2. Use the code below.
    '
    ' Examples:
    ' DotNetZip_Compress_SFX("C:\File.txt")
    ' DotNetZip_Compress_SFX("C:\Folder")
    '
    ' DotNetZip_Compress_SFX( _
    '    "C:\File.txt", "C:\Test.exe", , CompressionLevel.BestCompression, _
    '    "MyPassword", EncryptionAlgorithm.WinZipAes256, , , _
    '    ExtractExistingFileAction.OverwriteSilently, , , , _
    '    System.IO.Path.GetFileName("notepad.exe") _
    ' )


    Imports Ionic.Zip
    Imports Ionic.Zlib

    Private Function DotNetZip_Compress_SFX(ByVal Input_DirOrFile As String, _
                                      Optional ByVal OutputFileName As String = Nothing, _
                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
                                      Optional ByVal Password As String = Nothing, _
                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None, _
                                      Optional ByVal Extraction_Directory As String = ".\", _
                                      Optional ByVal Silent_Extraction As Boolean = False, _
                                      Optional ByVal Overwrite_Files As ExtractExistingFileAction = ExtractExistingFileAction.InvokeExtractProgressEvent, _
                                      Optional ByVal Delete_Extracted_Files_After_Extraction As Boolean = False, _
                                      Optional ByVal Icon As String = Nothing, _
                                      Optional ByVal Window_Title As String = Nothing, _
                                      Optional ByVal Window_Style As SelfExtractorFlavor = SelfExtractorFlavor.WinFormsApplication, _
                                      Optional ByVal Command_Line_Argument As String = Nothing _
                                    ) As Boolean
        Try
            ' Create compressor
            Dim Compressor As ZipFile = New ZipFile

            ' Set compression parameters
            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
            ' Compression method
            Compressor.Password = Password ' Zip Password
            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations

            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then
                Compressor.Encryption = EncryptionAlgorithm.None ' No encryption because no password.
                Compressor.CompressionMethod = CompressionMethod ' Set any compression method.
            Else
                Compressor.Encryption = Encrypt_Password ' Set Encryption for Zip password.
                Compressor.CompressionMethod = CompressionMethod.Deflate ' Set deflate method to don't destroy the SFX if AES encryption.
            End If

            Dim SFX_Options As New SelfExtractorSaveOptions()
            SFX_Options.DefaultExtractDirectory = Extraction_Directory
            SFX_Options.Quiet = Silent_Extraction
            SFX_Options.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently
            SFX_Options.RemoveUnpackedFilesAfterExecute = Delete_Extracted_Files_After_Extraction
            SFX_Options.Flavor = Window_Style
            SFX_Options.PostExtractCommandLine = Command_Line_Argument
            If Not Icon Is Nothing Then SFX_Options.IconFile = Icon
            If Not Window_Title Is Nothing Then SFX_Options.SfxExeWindowTitle = Window_Title

            ' Add Progress Handler
            ' AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_SFX_Progress

            ' Removes the end slash ("\") if is given for a directory.
            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)

            ' Generate the OutputFileName if any is given.
            If OutputFileName Is Nothing Then _
                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".exe").Replace("\\", "\")

            ' Check if given argument is Dir or File ...then start the compression
            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
                Compressor.AddDirectory(Input_DirOrFile)
            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
                Compressor.AddFile(Input_DirOrFile)
            End If

            Compressor.SaveSelfExtractor(OutputFileName, SFX_Options)
            Compressor.Dispose()

        Catch ex As Exception
            'Return False ' File not compressed
            Throw New Exception(ex.Message)
        End Try

        Return True ' File compressed

    End Function

    ' Public Sub DotNetZip_Compress_SFX_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
    '
    '    If e.EventType = ZipProgressEventType.Saving_Started Then
    '        MsgBox("Begin Saving: " & _
    '               e.ArchiveName) ' Destination ZIP filename
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
    '        MsgBox("Writing: " & e.CurrentEntry.FileName & _
    '               " (" & (e.EntriesSaved + 1) & "/" & e.EntriesTotal & ")") ' Input filename to be compressed
    '
    '        ' ProgressBar2.Maximum = e.EntriesTotal   ' Count of total files to compress
    '        ' ProgressBar2.Value = e.EntriesSaved + 1 ' Count of compressed files
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_EntryBytesRead Then
    '        ' ProgressBar1.Value = CType((e.BytesTransferred * 100) / e.TotalBytesToTransfer, Integer) ' Total Progress
    '
    '    ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
    '        MessageBox.Show("Compression Done: " & vbNewLine & _
    '                        e.ArchiveName) ' Compression finished
    '    End If
    '
    ' End Sub

#End Region







· Descomprimir con DotNetZip


Código (vbnet) [Seleccionar]
#Region " DotNetZip Extract "

    ' [ DotNetZip Extract Function ]
    '
    ' // By Elektro H@cker
    '
    ' Instructions :
    ' 1. Add a reference to "Ionic.Zip.dll".
    ' 2. Use the code below.
    '
    ' Examples:
    ' DotNetZip_Extract("C:\File.zip")
    ' DotNetZip_Extract("C:\File.zip", "C:\Folder\Test\", , "MyPassword")

    Imports Ionic.Zip
    Imports Ionic.Zlib

    Dim ZipFileCount As Long = 0
    Dim ExtractedFileCount As Long = 0

    Private Function DotNetZip_Extract(ByVal InputFile As String, _
                                       Optional ByVal OutputDir As String = Nothing, _
                                       Optional ByVal Overwrite As ExtractExistingFileAction = ExtractExistingFileAction.DoNotOverwrite, _
                                       Optional ByVal Password As String = "Nothing" _
                                     ) As Boolean
        Try
            ' Create Extractor
            Dim Extractor As ZipFile = ZipFile.Read(InputFile)

            ' Set Extractor parameters
            Extractor.Password = Password ' Zip Password
            Extractor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
            Extractor.ZipErrorAction = ZipErrorAction.Throw

            ' Specify the output path where the files will be extracted
            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName

            ' Add Progress
            'AddHandler Extractor.ExtractProgress, AddressOf DotNetZip_Extract_Progress ' Progress Handler
            'For Each Entry As ZipEntry In Extractor.Entries : ZipFileCount += 1 : Next ' Total bytes size of Zip
            'ZipFileCount = Extractor.Entries.Count ' Total files inside Zip

            ' Start the extraction
            For Each Entry As ZipEntry In Extractor.Entries : Entry.Extract(OutputDir, Overwrite) : Next

            ZipFileCount = 0 : ExtractedFileCount = 0 ' Reset vars
            Extractor.Dispose()
            Return True ' File Extracted

        Catch ex As Exception
            ' Return False ' File not extracted
            Throw New Exception(ex.Message)
        End Try

    End Function

    ' Public Sub DotNetZip_Extract_Progress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
    '
    '     If e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry Then
    '         If ExtractedFileCount = 0 Then
    '             MsgBox("Begin Extracting: " & _
    '                     e.ArchiveName) ' Input ZIP filename
    '         End If
    '
    '         ExtractedFileCount += 1
    '         MsgBox("Writing: " & e.CurrentEntry.FileName & _
    '                " (" & (ExtractedFileCount) & "/" & ZipFileCount & ")") ' Output filename uncompressing
    '
    '         ProgressBar1.Maximum = ZipFileCount     ' Count of total files to uncompress
    '         ProgressBar1.Value = ExtractedFileCount ' Count of uncompressed files
    '
    '     ElseIf e.EventType = ZipProgressEventType.Extracting_AfterExtractEntry Then
    '         If ExtractedFileCount = ZipFileCount Then
    '             MessageBox.Show("Extraction Done: " & vbNewLine & _
    '                             e.ArchiveName) ' Uncompression finished
    '         End If
    '     End If
    '
    ' End Sub

#End Region








Eleкtro

#82
· Modificar la prioridad de un proceso, por el nombre.

Código (vbnet) [Seleccionar]
#Region " Set Process Priority By Name "

   ' [ Set Process Priority By Name Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' Set_Process_Priority_By_Name("notepad.exe", ProcessPriorityClass.RealTime)
   ' Set_Process_Priority_By_Name("notepad", ProcessPriorityClass.Idle, False)

   Private Function Set_Process_Priority_By_Name(ByVal ProcessName As String, _
                                     ByVal Priority As ProcessPriorityClass, _
                                     Optional ByVal OnlyFirstFound As Boolean = True
                                   ) As Boolean
       Try
           If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)

           For Each Proc As Process In System.Diagnostics.Process.GetProcessesByName(ProcessName)
               Proc.PriorityClass = Priority
               If OnlyFirstFound Then Exit For
           Next

           Return True

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

   End Function

#End Region







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

Código (vbnet) [Seleccionar]
#Region " Set Process Priority By Handle "

   ' [ Set Process Priority By Handle Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' Set_Process_Priority_By_Handle(Process.GetCurrentProcess().Handle, Process_Priority.RealTime)
   ' Set_Process_Priority_By_Handle(33033, Process_Priority.Idle)

   Private Declare Function GetPriorityClass Lib "kernel32" (ByVal hProcess As Long) As Long
   Private Declare Function SetPriorityClass Lib "kernel32" (ByVal hProcess As Long, ByVal dwPriorityClass As Long) As Long

   Public Enum Process_Priority As Int32
       RealTime = 256
       High = 128
       Above_Normal = 32768
       Normal = 32
       Below_Normal = 16384
       Low = 64
   End Enum

   Private Function Set_Process_Priority_By_Handle(ByVal Process_Handle As IntPtr, _
                                                   ByVal Process_Priority As Process_Priority) As Boolean

       SetPriorityClass(Process_Handle, Process_Priority)
       If GetPriorityClass(Process_Handle) = Process_Priority Then _
            Return True _
       Else Return False ' Return false if priority can't be changed 'cause user permissions.

   End Function

#End Region







· modificar la prioridad del Thread actual:

Código (vbnet) [Seleccionar]
#Region " Set Current Thread Priority "

   ' [ Set Current Thread Priority Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' Set_Current_Thread_Priority(Threading.ThreadPriority.AboveNormal)
   ' MsgBox(Set_Current_Thread_Priority(Threading.ThreadPriority.Highest))

   Public Shared Function Set_Current_Thread_Priority(ByVal Thread_Priority As Threading.ThreadPriority) As Boolean
       Try
           Threading.Thread.CurrentThread.Priority = Thread_Priority
           Return True
       Catch ex As Exception
           ' Return False
           Throw New Exception(ex.Message)
       End Try

   End Function

#End Region












Eleкtro

· Detectar la ejecución de la aplicación en una máquina virtual.


Código (vbnet) [Seleccionar]
#Region " Detect Virtual Machine "

    ' [ Detect Virtual Machine Function ]
    '
    ' // By Elektro H@cker
    '
    ' Instructions :
    ' 1. Add a reference for "System.Management"
    '
    ' Examples :
    ' MsgBox(Detect_Virtual_Machine)
    ' If Detect_Virtual_Machine() Then MsgBox("This program cannot run on a virtual machine")

    Imports System.Management

    Private Function Detect_Virtual_Machine() As Boolean

        Dim ModelName As String = Nothing
        Dim SearchQuery = New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE BytesPerSector > 0")

        For Each ManagementSystem In SearchQuery.Get

            ModelName = ManagementSystem("Model").ToString.Split(" ").First.ToLower

            If ModelName = "virtual" Or _
               ModelName = "vmware" Or _
               ModelName = "vbox" Or _
               ModelName = "qemu" _
            Then
                Return True ' Virtual machine HDD Model Name found
            End If

        Next

        Return False ' Virtual machine HDD Model Name not found

    End Function

#End Region








Eleкtro

A ver si alguien se anima y hace un snippet Anti-Sandbox, que según he leido es bien fácil: http://www.aspfree.com/c/a/braindump/virtualization-and-sandbox-detection/ pero por desgracia hay demasiados software virtualizadores para ponerse a probar uno por uno para hacer una función genérica...

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

Saludos!








Eleкtro

#85
· Animar la ventana con efectos

Código (vbnet) [Seleccionar]
#Region " Animate Window "

   ' [ Animate Window ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' AnimateWindow(Me.Handle, 1500, Animation.Show_Fade)
   ' AnimateWindow(Me.Handle, 1500, Animation.Hide_Center)

   Public Declare Function AnimateWindow Lib "user32" (ByVal hwnd As IntPtr, ByVal dwtime As Int64, ByVal dwflags As Animation) As Boolean

   Public Enum Animation As Int32

       Show_Left_To_Right = 1
       Show_Right_To_left = 2
       Show_Top_To_Bottom = 4
       Show_Bottom_to_top = 8
       Show_Corner_Left_UP = 5
       Show_Corner_Left_Down = 9
       Show_Corner_Right_UP = 6
       Show_Corner_Right_Down = 10
       Show_Center = 16
       Show_Fade = 524288

        Hide_Left_To_Right = 1 Or 65536
        Hide_Right_To_left = 2 Or 65536
        Hide_Top_To_Bottom = 4 Or 65536
        Hide_Bottom_to_top = 8 Or 65536
        Hide_Corner_Left_UP = 5 Or 65536
        Hide_Corner_Left_Down = 9 Or 65536
        Hide_Corner_Right_UP = 6 Or 65536
        Hide_Corner_Right_Down = 10 Or 65536
        Hide_Center = 16 Or 65536
        Hide_Fade = 524288 Or 65536

   End Enum

#End Region








Eleкtro

· Ejemplo de un String multi-línea para aplicaciones de consola:

Código (vbnet) [Seleccionar]
       Dim Logo As String = <a><![CDATA[
 ___              _ _           _   _               _____ _ _   _      
/ _ \            | (_)         | | (_)             |_   _(_) | | |    
/ /_\ \_ __  _ __ | |_  ___ __ _| |_ _  ___  _ __     | |  _| |_| | ___
|  _  | '_ \| '_ \| | |/ __/ _` | __| |/ _ \| '_ \    | | | | __| |/ _ \
| | | | |_) | |_) | | | (_| (_| | |_| | (_) | | | |   | | | | |_| |  __/
\_| |_/ .__/| .__/|_|_|\___\__,_|\__|_|\___/|_| |_|   \_/ |_|\__|_|\___|
     | |   | |                                                        
     |_|   |_|                                                        

]]></a>.Value

Console.WriteLine(Logo)










Eleкtro

#87
· Setear los argumentos commandline por defecto del modo debug de la aplicación.

Código (vbnet) [Seleccionar]
#Region " Set CommandLine Arguments "

    ' [ Set CommandLine Arguments Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples:
    ' For Each Arg In Arguments : MsgBox(Arg) : Next

    Dim Arguments As List(Of String) = Set_CommandLine_Arguments()

    Public Function Set_CommandLine_Arguments() As List(Of String)
#If DEBUG Then
        ' Debug Commandline arguments for this application:
        Dim DebugArguments = "Notepad.exe -Sleep 5 -Interval 50 -Key CTRL+C"
        Return DebugArguments.Split(" ").ToList
#Else
        ' Nomal Commandline arguments
        Return My.Application.CommandLineArgs.ToList
#End If
    End Function

#End Region











Eleкtro

#88
· Un Sub especial para el control de terceros "CButton", para modificar los colores (Y actualizar el estado de los colores).

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

Código (vbnet) [Seleccionar]
#Region " Change Cbutton Color "

   ' [ Change Cbutton Color ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   ' Change_Cbutton_Color(CButton1, Color.Black, Color.DarkRed, Color.Red)


   Private Sub Change_Cbutton_Color(ByVal Button_Name As CButtonLib.CButton, _
                                     ByVal Color1 As Color, _
                                     ByVal Color2 As Color, _
                                     ByVal Color3 As Color)

       Button_Name.ColorFillBlend.iColor(0) = Color1
       Button_Name.ColorFillBlend.iColor(1) = Color2
       Button_Name.ColorFillBlend.iColor(2) = Color3
       Button_Name.UpdateDimBlends()

   End Sub

#End Region








Eleкtro

· comprueba si Aero está activado:

Código (vbnet) [Seleccionar]
#Region " Is Aero Enabled? "

    ' [ Is Aero Enabled? Function ]
    '
    ' Examples:
    ' MsgBox(Is_Aero_Enabled)

    <System.Runtime.InteropServices.DllImport("dwmapi.dll")> _
    Private Shared Function DwmIsCompositionEnabled(ByRef enabled As Boolean) As Integer
    End Function

    Public Function Is_Aero_Enabled() As Boolean
        If Environment.OSVersion.Version.Major < 6 Then
            Return False ' Windows version is under Windows Vista so not Aero.
        Else
            DwmIsCompositionEnabled(Is_Aero_Enabled)
        End If
    End Function

#End Region