Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 526,946 veces)
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
· Usar un proxy en el WebBrowser: #Region " Use Proxy " ' [ Use Proxy ] ' ' Examples : ' Use_Proxy("213.181.73.145:80") ' WebBrowser1.Navigate("http://www.ipchicken.com/") <Runtime.InteropServices.DllImport("wininet.dll", SetLastError:=True)> _ Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean End Function Public Structure Struct_INTERNET_PROXY_INFO Public dwAccessType As Integer Public proxy As IntPtr Public proxyBypass As IntPtr End Structure Private Sub Use_Proxy(ByVal strProxy As String) Const INTERNET_OPTION_PROXY As Integer = 38 Const INTERNET_OPEN_TYPE_PROXY As Integer = 3 Dim struct_IPI As Struct_INTERNET_PROXY_INFO struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy) struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local") Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)) Marshal.StructureToPtr(struct_IPI, intptrStruct, True) Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI)) End Sub #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
[ListView] Restrict column resizing Restringe cambiar de tamaño una columna. ' [ListView] Restrict column resizing Private Sub ListView1_ColumnWidthChanging(sender As Object, e As ColumnWidthChangingEventArgs) Handles ListView1.ColumnWidthChanging e.Cancel = True e.NewWidth = sender.Columns(e.ColumnIndex).Width End Sub
Get Non-Client Area Width Devuelve el tamaño del borde del área NO cliente de la aplicación. #Region " Get Non-Client Area Width " ' [ Get Non-Client Area Width Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_NonClientArea_Width(Form1)) ' Me.Location = New Point((Form1.Location.X + (Form1.Width + Get_NonClientArea_Width(Form1))), Form1.Location.Y) Private Function Get_NonClientArea_Width(ByVal Form As Form) As Int32 Return (Form.Width - Form.ClientSize.Width) End Function #End Region
Extend Non Client Area Extiende el área NO cliente al área cliente de la aplicación #Region " Extend Non Client Area " ' [ Extend Non Client Area Function ] ' ' // By Elektro H@cker ' ' Examples : ' Extend_Non_Client_Area(Me.Handle, 50, 50, -0, 20) ' MsgBox(Extend_Non_Client_Area(12345, -1, -1, -1, -1)) <System.Runtime.InteropServices.DllImport("dwmapi.dll")> _ Private Shared Function DwmExtendFrameIntoClientArea(ByVal handle As IntPtr, ByRef Margins As MARGINS) As Integer End Function <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)> _ Public Structure MARGINS Public Left As Integer Public Right As Integer Public Up As Integer Public Down As Integer End Structure Private Function Extend_Non_Client_Area(ByVal Window_Handle As IntPtr, _ ByVal Left As Int32, _ ByVal Right As Int32, _ ByVal Up As Int32, _ ByVal Down As Int32) As Boolean Try Dim Margins As New MARGINS() Margins.Left = Left Margins.Right = Right Margins.Up = Up Margins.Down = Down DwmExtendFrameIntoClientArea(Window_Handle, Margins) Return True Catch ex As Exception 'Return false Throw New Exception(ex.Message) End Try End Function #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
If Debug conditional #Else #End If
If Debugger IsAttached conditional Ejemplo de una condicional de ejecución en Debug If Debugger.IsAttached Then Else End If
String Format Ejemplo de un String Format 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? #Region " Get NT Version " ' [ Get NT Version Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_NT_Version()) ' If Get_NT_Version() < 6.0 Then MsgBox("This application only works with an Aero compatible windows version") Private Function Get_NT_Version() As Double Dim NT As Double = CDbl(Val(System.Environment.OSVersion.Version.ToString.Substring(0, 3))) ' INFO: ' ----- ' 3.1 = Windows NT 3.1 ' 3.5 = Windows NT 3.5 ' 4.0 = Windows NT 4.0 ' 5.0 = Windows 2000 ' 5.1 = Windows XP / Windows Fundamentals for Legacy PCs ' 5.2 = Windows XP 64 Bit / Windows server 2003 / Windows server 2003 R2 / Windows home Server ' 6.0 = Windows VISTA / Windows server 2008 ' 6.1 = Windows 7 / Windows server 2008 R2 ' 6.2 = Windows 8 / Windows 8 Phone / Windows Server 2012 Return NT End Function
#End Region
Extract Icon Devuelve el icono de un archivo #Region " Extract Icon " ' [ Extract Icon Function ] ' ' // By Elektro H@cker ' ' Me.Icon = Extract_Icon("c:\windows\explorer.exe") ' Dim MyIcon as System.Drawing.Icon = Extract_Icon("c:\Test.txt") Private Function Extract_Icon (ByVal File As String) As System. Drawing. Icon Try : Return System. Drawing. Icon. ExtractAssociatedIcon(File) Catch ex As Exception 'MsgBox(ex.message) Return Nothing End Try Else : Return Nothing End If End Function #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 MsgBox(OSVersionInfo.Name) MsgBox(OSVersionInfo.Edition) MsgBox(OSVersionInfo.ServicePack) MsgBox(OSVersionInfo.VersionString) MsgBox(OSVersionInfo.BuildVersion) MsgBox(OSVersionInfo.OSBits.ToString) MsgBox(OSVersionInfo.ProcessorBits.ToString) 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
Mensajes: 9.866
|
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). #Region " Set Aero Theme " ' [ Set Aero Theme Function ] ' ' // By Elektro H@cker ' ' Instructions : ' Add a reference for "System.ServiceProcess" ' ' Set_Aero_Theme("C:\Windows\Resources\Themes\aero\aero.msstyles") ' Set_Aero_Theme("C:\Windows\Resources\Themes\Concave 7\Concave 7.msstyles") ' Set_Aero_Theme("C:\Windows\Resources\Themes\Aero\Luna.msstyles", "Metallic", "NormalSize") Private Function Set_Aero_Theme(ByVal ThemeFile As String, _ Optional ByVal ColorName As String = "NormalColor", _ Optional ByVal SizeName As String = "NormalSize" _ ) As Boolean Try Using ThemeService As New ServiceProcess.ServiceController("Themes") ThemeService.Stop() ThemeService.WaitForStatus(1) ' Wait for Stopped My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "LoadedBefore", "0", Microsoft.Win32.RegistryValueKind.String) My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "DllName", ThemeFile, Microsoft.Win32.RegistryValueKind.String) My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "ColorName", ColorName, Microsoft.Win32.RegistryValueKind.String) My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "SizeName", SizeName, Microsoft.Win32.RegistryValueKind.String) ThemeService.Start() ThemeService.WaitForStatus(4) ' Wait for Running End Using Catch ex As Exception 'MsgBox(ex.message) Return False End Try Return True End Function #End Region
Devuelve información del theme actual PD: Yo solo he creado la función. #Region " Get Current Aero Theme " ' [ Get Current Aero Theme Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Get_Current_Aero_Theme(Theme_Info.Name)) ' MsgBox(Get_Current_Aero_Theme(Theme_Info.FullPath)) Public Structure ThemeInfo Private Declare Unicode Function GetCurrentThemeName _ Lib "uxtheme.dll" _ ( _ ByVal pszThemeFileName As String, _ ByVal dwMaxNameChars As Int32, _ ByVal pszColorBuff As String, _ ByVal cchMaxColorChars As Int32, _ ByVal pszSizeBuff As String, _ ByVal cchMaxSizeChars As Int32 _ ) As Int32 Private Const S_OK As Int32 = &H0 Private m_FileName As String Private m_ColorSchemeName As String Private m_SizeName As String Public Property FileName() As String Get Return m_FileName End Get Set(ByVal Value As String) m_FileName = Value End Set End Property Public Property ColorSchemeName() As String Get Return m_ColorSchemeName End Get Set(ByVal Value As String) m_ColorSchemeName = Value End Set End Property Public Property SizeName() As String Get Return m_SizeName End Get Set(ByVal Value As String) m_SizeName = Value End Set End Property Public Overrides Function ToString() As String Return _ "FileName={" & Me.FileName & _ "} ColorSchemeName={" & Me.ColorSchemeName & _ "} SizeName={" & Me.SizeName & "}" End Function Public Shared ReadOnly Property CurrentTheme() As ThemeInfo Get Dim ti As New ThemeInfo() Const BufferLength As Int32 = 256 ti.FileName = Strings.Space(BufferLength) ti.ColorSchemeName = ti.FileName ti.SizeName = ti.FileName If _ GetCurrentThemeName( _ ti.FileName, _ BufferLength, _ ti.ColorSchemeName, _ BufferLength, _ ti.SizeName, _ BufferLength _ ) = S_OK _ Then ti.FileName = NullTrim(ti.FileName) ti.ColorSchemeName = NullTrim(ti.ColorSchemeName) ti.SizeName = NullTrim(ti.SizeName) Return ti Else Const Message As String = _ "An error occured when attempting to get theme info." Throw New Exception(Message) End If End Get End Property Private Shared Function NullTrim(ByVal Text As String) As String Return _ Strings.Left( _ Text, _ Strings.InStr(Text, ControlChars.NullChar) - 1 _ ) End Function End Structure Public Enum Theme_Info Name FileName FullPath ColorScheme Size End Enum Private Function Get_Current_Aero_Theme(ByVal Info As Theme_Info) As String Select Case Info Case Theme_Info.Name : Return ThemeInfo.CurrentTheme.FileName.Split("\").Last.Split(".").First Case Theme_Info.FileName : Return ThemeInfo.CurrentTheme.FileName.Split("\").Last Case Theme_Info.FullPath : Return ThemeInfo.CurrentTheme.FileName Case Theme_Info.ColorScheme : Return ThemeInfo.CurrentTheme.ColorSchemeName Case Theme_Info.Size : Return ThemeInfo.CurrentTheme.SizeName Case Else : Return Nothing End Select End Function #End Region
Escribe texto a la CMD desde un proyecto Windowsforms Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean Declare Function FreeConsole Lib "kernel32.dll" () As Boolean AttachConsole(-1) ' Attach the console System.Console.Writeline("I am writing from a WinForm to the console!") FreeConsole() ' Desattach the console
Adjunta una nueva instancia de la CMD a la aplicación. Public Declare Function AllocConsole Lib "kernel32.dll" () As Boolean AllocConsole() 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. #Region " App Is Launched From CMD? " ' [ App Is Launched From CMD? Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(App_Is_Launched_From_CMD) ' If App_Is_Launched_From_CMD() Then Console.WriteLine("Help for this application: ...") Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean Declare Function FreeConsole Lib "kernel32.dll" () As Boolean Private Function App_Is_Launched_From_CMD() As Boolean If AttachConsole(-1) Then FreeConsole() Return True Else Return False End If End Function #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. #Region " Split File " ' [ Split File Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Split_File("C:\Test.txt", 10000, , True)) ' MsgBox(Split_File("C:\Test.txt", 10000, "Splitted")) Public Function Split_File (ByVal File As String, _ ByVal ChunkSize As Long, _ Optional ByVal OutputName As String = Nothing, _ Optional ByVal Preserve_FileExtension As Boolean = True _ ) As Boolean Dim Index As Long Dim OutputFile As String Dim BaseName As String Dim StartPosition As Long Dim Buffer As Byte() = New Byte() {} Dim InputFileStram As System.IO.FileStream Dim OutputFileStram As System.IO.FileStream Dim BinaryWriter As IO.BinaryWriter Dim BinaryReader As IO.BinaryReader Dim Fragments As Long Dim RemainingBytes As Long Dim Progress As Double Dim Zeroes As String = "" Try Dim FileInfo As New IO. FileInfo(File) Dim Filename As String = FileInfo.FullName Dim FileExtension As String = FileInfo.Extension Dim outputpath As String = FileInfo.DirectoryName Dim FileSize As Long = FileInfo.Length If OutputName IsNot Nothing Then : BaseName = OutputName Else : BaseName = FileInfo.Name.Replace(FileInfo.Extension, "") : End If If Not IO. File. Exists(Filename ) Then MsgBox("File " & Filename & " doesn't exist") Return False End If If FileSize <= ChunkSize Then MsgBox(Filename & " size(" & FileSize & ") is less than the ChunkSize(" & ChunkSize & ")") Return False End If InputFileStram = New IO.FileStream(Filename, IO.FileMode.Open) BinaryReader = New IO.BinaryReader(InputFileStram) Fragments = Math.Floor(FileSize / ChunkSize) For n As Integer = 1 To Fragments.ToString.Length : Zeroes += "0" : Next Progress = 100 / Fragments RemainingBytes = FileSize - (Fragments * ChunkSize) If outputpath = "" Then outputpath = IO.Directory.GetParent(Filename).ToString If Not IO.Directory.Exists(outputpath) Then IO.Directory.CreateDirectory(outputpath) BinaryReader.BaseStream.Seek(0, IO.SeekOrigin.Begin) For Index = 1 To Fragments If Preserve_FileExtension Then : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) & FileExtension Else : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) End If ReDim Buffer(ChunkSize - 1) BinaryReader.Read(Buffer, 0, ChunkSize) StartPosition = BinaryReader.BaseStream.Seek(0, IO.SeekOrigin.Current) If IO. File. Exists(OutputFile ) Then IO. File. Delete(OutputFile ) OutputFileStram = New System.IO.FileStream(OutputFile, IO.FileMode.Create) BinaryWriter = New IO.BinaryWriter(OutputFileStram) BinaryWriter.Write(Buffer) OutputFileStram.Flush() BinaryWriter.Close() OutputFileStram.Close() Next If RemainingBytes > 0 Then If Preserve_FileExtension Then : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) & FileExtension Else : OutputFile = outputpath & "\" & BaseName & "." & Format(Index, Zeroes) End If ReDim Buffer(RemainingBytes - 1) BinaryReader.Read(Buffer, 0, RemainingBytes) If IO. File. Exists(OutputFile ) Then IO. File. Delete(OutputFile ) OutputFileStram = New System.IO.FileStream(OutputFile, IO.FileMode.Create) BinaryWriter = New IO.BinaryWriter(OutputFileStram) BinaryWriter.Write(Buffer) OutputFileStram.Flush() BinaryWriter.Close() OutputFileStram.Close() End If InputFileStram.Close() BinaryReader.Close() Return True Catch ex As Exception MsgBox(ex.Message) Return False Finally BinaryWriter = Nothing OutputFileStram = Nothing BinaryReader = Nothing InputFileStram = Nothing End Try End Function #End Region
Parte un archivo de texto en trozos especificando el número de líneas por archivo. #Region " Split TextFile By Number Of Lines " ' [ Split TextFile By Number Of Lines Function ] ' ' // By Elektro H@cker ' ' Examples : ' Split_TextFile_By_Number_Of_Lines("C:\Test.txt", 10000) ' MsgBox(Split_TextFile_By_Number_Of_Lines("C:\Test.txt", 10)) Private Function Split_TextFile_By_Number_Of_Lines(ByVal TextFile As String, ByVal NumberOfLines As Long) As Boolean Try Dim FileInfo As New IO.FileInfo(TextFile) If NumberOfLines > IO. File. ReadAllLines(TextFile ). Length Then ' MsgBox("Number of lines is greater than total file lines") Return False End If Using sr As New System.IO.StreamReader(TextFile) Dim fileNumber As Integer = 0 While Not sr.EndOfStream Dim count As Integer = 0 Using sw As New System.IO.StreamWriter(FileInfo.DirectoryName & "\" & FileInfo.Name.Replace(FileInfo.Extension, " " & System.Threading.Interlocked.Increment(fileNumber) & FileInfo.Extension)) sw.AutoFlush = True While Not sr.EndOfStream AndAlso Not System.Threading.Interlocked.Increment(count) > NumberOfLines Application.DoEvents() sw.WriteLine(sr.ReadLine()) End While End Using End While End Using Return True Catch ex As Exception Throw New Exception(ex.Message) End Try End Function #End Region
|
|
« Última modificación: 30 Abril 2013, 17:26 pm por EleKtro H@cker »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
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#Region " Is First Run? " ' [ Is First Run? Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Is_First_Run) ' If Is_First_Run() Then... Private Function Is_First_Run() As Boolean Dim RegRoot As Microsoft.Win32.RegistryKey = Registry.CurrentUser Dim RegKey As String = "Software\MyApplicationName" Dim RegValue As String = "First Run" Dim FirstRun As Boolean RegRoot.CreateSubKey(RegKey) RegRoot.Close() Try : FirstRun = Convert.ToBoolean(My.Computer.Registry.GetValue(RegRoot.ToString & "\" & RegKey, RegValue, Microsoft.Win32.RegistryValueKind.String)) Catch : FirstRun = True End Try If FirstRun Then My.Computer.Registry.SetValue(RegRoot.ToString & "\" & RegKey, RegValue, "False", Microsoft.Win32.RegistryValueKind.String) Return True Else Return False End If End Function #End region
|
|
« Última modificación: 1 Mayo 2013, 12:03 pm por EleKtro H@cker »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Elimina el contenido del portapapeles Private Sub Delete_Clipboard() Clipboard.SetText(vbCr) 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. #Region " Set Control Hint " ' //By Elektro H@cker Dim TextBox_Hint As String = "Type your RegEx here..." ' TextBox1 [Enter/Leave] Private Sub TextBox1_Hint(sender As Object, e As EventArgs) Handles _ TextBox1.Enter, _ TextBox1.Leave If sender.Text = TextBox_Hint Then : sender.text = "" ElseIf sender.Text = "" Then : sender.text = TextBox_Hint End If End Sub #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Elimina el contenido del portapapeles: Private Sub Delete_Clipboard() Clipboard.SetText(vbCr) 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. #Region " Get Pixel Color " ' [ Get Pixel Color Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Dim RGB As Color = Get_Pixel_Color(MousePosition.X, MousePosition.Y, ColorType.RGB) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.RGB).ToString) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HEX)) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HTML)) <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function GetDC(hwnd As IntPtr) As IntPtr End Function <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function ReleaseDC(hwnd As IntPtr, hdc As IntPtr) As Int32 End Function <System.Runtime.InteropServices.DllImport("gdi32.dll")> Shared Function GetPixel(hdc As IntPtr, nXPos As Integer, nYPos As Integer) As UInteger End Function Public Enum ColorType RGB HEX HTML End Enum Public Function Get_Pixel_Color(ByVal x As Int32, ByVal y As Int32, ByVal ColorType As ColorType) Dim hdc As IntPtr = GetDC(IntPtr.Zero) Dim pixel As UInteger = GetPixel(hdc, x, y) ReleaseDC(IntPtr.Zero, hdc) Dim RGB As Color = Color.FromArgb(CType((pixel And &HFF), Integer), CType((pixel And &HFF00), Integer) >> 8, CType((pixel And &HFF0000), Integer) >> 16) Dim R As Int16 = RGB.R, G As Int16 = RGB.G, B As Int16 = RGB.B Dim HEX_R As String, HEX_G As String, HEX_B As String Select Case ColorType Case ColorType.RGB : Return RGB Case ColorType.HEX If Hex(R) = Hex(0) Then HEX_R = "00" Else HEX_R = Hex(R) If Hex(G) = Hex(0) Then HEX_G = "00" Else HEX_G = Hex(G) If Hex(B) = Hex(0) Then HEX_B = "00" Else HEX_B = Hex(B) Return (HEX_R & HEX_G & HEX_B) Case ColorType.HTML : Return ColorTranslator.ToHtml(RGB) Case Else : Return Nothing End Select End Function #End Region
Crear un archivo comprimido autoextraible (SFX) con la librería SevenZipSharp: #Region " SevenZipSharp Compress SFX " ' [ SevenZipSharp Compress SFX Function ] ' ' // By Elektro H@cker ' ' Instructions : ' 1. Add a reference to "SevenZipSharp.dll". ' 2. Add the "7z.dll" or "7z64.dll" files to the project. ' 3. Add the "7z.sfx" and "7zCon.sfx" files to the project. ' 4. Use the code below. ' ' Examples : ' SevenZipSharp_Compress_SFX("C:\File.txt") ' File will be compressed in the same dir. ' SevenZipSharp_Compress_SFX("C:\File.txt", "C:\Compressed\File.exe") ' File will be compressed in "C:\Compressed\". ' SevenZipSharp_Compress_SFX("C:\Folder\", , , , , , , "Password") ' Folder will be compressed with the given password. ' SevenZipSharp_Compress_SFX("C:\File.txt", , SevenZipSharp_SFX_Module.Console, CompressionLevel.Fast) ' Imports SevenZip ' Dim dll As String = "7z.dll" Public Enum SevenZipSharp_SFX_Module Normal Console End Enum Private Function SevenZipSharp_Compress_SFX(ByVal Input_DirOrFile As String, _ Optional ByVal OutputFileName As String = Nothing, _ Optional ByVal SFX_Module As SevenZipSharp_SFX_Module = SevenZipSharp_SFX_Module.Normal, _ Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _ Optional ByVal Password As String = Nothing) As Boolean ' Create the .7z file Try ' Set library path SevenZipCompressor.SetLibraryPath(dll) ' Create compressor Dim Compressor As SevenZipCompressor = New SevenZipCompressor() ' Set compression parameters Compressor.CompressionLevel = CompressionLevel ' Archiving compression level. Compressor.CompressionMethod = CompressionMethod.Lzma ' Compression Method Compressor.ArchiveFormat = OutArchiveFormat.SevenZip ' Compression file format Compressor.CompressionMode = CompressionMode.Create ' Append files to compressed file or overwrite the compressed file. Compressor.DirectoryStructure = True ' Preserve the directory structure. Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives. Compressor.ScanOnlyWritable = False ' Compress files only open for writing. Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path Compressor.FastCompression = False ' Compress as fast as possible, without calling events. Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory. Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives. Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance ' Add Progress Handler ' AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress ' Removes the end slash ("\") if 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) & ".tmp").Replace("\\", "\") Else OutputFileName = OutputFileName & ".tmp" End If ' Check if given argument is Dir or File ...then start the compression If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir If Not Password Is Nothing Then Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password) Else Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True) End If ElseIf IO. File. Exists(Input_DirOrFile ) Then ' Is a File If Not Password Is Nothing Then Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile) Else Compressor.CompressFiles(OutputFileName, Input_DirOrFile) End If End If ' Create the SFX file ' Create the SFX compressor Dim compressorSFX As SevenZipSfx = New SevenZipSfx(SfxModule.Default) ' Set SFX Module path If SFX_Module = SevenZipSharp_SFX_Module.Normal Then compressorSFX.ModuleFileName = ".\7z.sfx" ElseIf SFX_Module = SevenZipSharp_SFX_Module.Console Then compressorSFX.ModuleFileName = ".\7zCon.sfx" End If ' Start the compression ' Generate the OutputFileName if any is given. Dim SFXOutputFileName As String If OutputFileName.ToLower.EndsWith(".exe.tmp") Then SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) Else SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) & ".exe" End If compressorSFX.MakeSfx(OutputFileName, SFXOutputFileName) ' Delete the 7z tmp file Try : IO. File. Delete(OutputFileName ) : Catch : End Try Catch ex As Exception 'Return False ' File not compressed Throw New Exception(ex.Message) End Try Return True ' File compressed End Function ' Public Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) ' MsgBox("Percent compressed: " & e.PercentDone) ' End Sub #End Region
|
|
« Última modificación: 4 Mayo 2013, 17:02 pm por EleKtro H@cker »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Un snippet para medir el tiempo transcurrido para un procedimiento o una función o cualquier cosa: MEJORADO: #Region " Code Execution Time " ' [ Code Execution Time ] ' ' // By Elektro H@cker ' ' Examples : ' Execution_Start() : Threading.Thread.Sleep(500) : Execution_End() Dim Execution_Watcher As New Stopwatch Private Sub Execution_Start() If Execution_Watcher.IsRunning Then Execution_Watcher.Restart() Execution_Watcher.Start() End Sub Private Sub Execution_End() If Execution_Watcher.IsRunning Then MessageBox.Show("Execution watcher finished:" & vbNewLine & vbNewLine & _ "[H:M:S:MS]" & vbNewLine & _ Execution_Watcher.Elapsed.Hours & _ ":" & Execution_Watcher.Elapsed.Minutes & _ ":" & Execution_Watcher.Elapsed.Seconds & _ ":" & Execution_Watcher.Elapsed.Milliseconds & _ vbNewLine & _ vbNewLine & _ "Total H: " & Execution_Watcher.Elapsed.TotalHours & vbNewLine & vbNewLine & _ "Total M: " & Execution_Watcher.Elapsed.TotalMinutes & vbNewLine & vbNewLine & _ "Total S: " & Execution_Watcher.Elapsed.TotalSeconds & vbNewLine & vbNewLine & _ "Total MS: " & Execution_Watcher.ElapsedMilliseconds & vbNewLine, _ "Code execution time", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information, _ MessageBoxDefaultButton.Button1) Execution_Watcher.Reset() Else MessageBox.Show("Execution watcher never started.", _ "Code execution time", _ MessageBoxButtons.OK, _ MessageBoxIcon.Error, _ MessageBoxDefaultButton.Button1) End If End Sub #End Region
|
|
« Última modificación: 4 Mayo 2013, 18:59 pm por EleKtro H@cker »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Para bloquear procesos. ' [ Block Process Functions ] ' ' // By Elektro H@cker ' ' Examples : ' BlockProcess.Block("cmd") ' Blocks a process ' BlockProcess.Block("firefox.exe") ' Blocks a process ' BlockProcess.Unblock("cmd") ' Unblocks a process ' BlockProcess.Unblock("firefox.exe") ' Unblocks a process ' ' BlockProcess.Unblock_All() ' Reset all values and stop timer ' BlockProcess.Monitor_Interval = 5 * 1000 ' BlockProcess.Show_Message_On_Error = True ' BlockProcess.Show_Message_On_blocking = True ' BlockProcess.Message_Text = "I blocked your process: " ' BlockProcess.Message_Title = "Block Process .:: By Elektro H@cker ::." #Region " Block Process Class " Public Class BlockProcess Shared Blocked_APPS As New List(Of String) ' List of process names Shared WithEvents ProcessMon_Timer As New Timer ' App Monitor timer ''' <summary> ''' Shows a MessageBox if error occurs when blocking the app [Default: False]. ''' </summary> Public Shared Show_Message_On_Error As Boolean = False ''' <summary> ''' Shows a MessageBox when app is being blocked [Default: False]. ''' </summary> Public Shared Show_Message_On_blocking As Boolean = False ''' <summary> ''' Set the MessageBox On blocking Text. ''' </summary> Public Shared Message_Text As String = "Process blocked: " ''' <summary> ''' Set the MessageBox On blocking Title. ''' </summary> Public Shared Message_Title As String = "Process Blocked" ''' <summary> ''' Set the App Monitor interval in milliseconds [Default: 200]. ''' </summary> Public Shared Monitor_Interval As Int64 = 200 ''' <summary> ''' Add a process name to the process list. ''' </summary> Public Shared Sub Block(ByVal ProcessName As String) If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Blocked_APPS.Add(ProcessName) If Not ProcessMon_Timer.Enabled Then ProcessMon_Timer.Enabled = True End Sub ''' <summary> ''' Delete a process name from the process list. ''' </summary> Public Shared Sub Unblock(ByVal ProcessName As String) If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Blocked_APPS.Remove(ProcessName) End Sub ''' <summary> ''' Clear the process list and disables the App Monitor. ''' </summary> Public Shared Sub Unblock_All() ProcessMon_Timer.Enabled = False Blocked_APPS.Clear() End Sub ' Timer Tick Event Shared Sub ProcessMon_Timer_Tick(sender As Object, e As EventArgs) Handles ProcessMon_Timer.Tick For Each ProcessName In Blocked_APPS Dim proc() As Process = Process.GetProcessesByName(ProcessName) Try For proc_num As Integer = 0 To proc.Length - 1 proc(proc_num).Kill() If Show_Message_On_blocking Then MessageBox.Show(Message_Text & ProcessName & ".exe", Message_Title, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) End If Next Catch ex As Exception If Show_Message_On_Error Then MsgBox(ex.Message) ' One of the processes can't be killed End If End Try Next ' Set the Timer interval if is different If Not sender.Interval = Monitor_Interval Then sender.Interval = Monitor_Interval End Sub End Class #End Region
|
|
« Última modificación: 5 Mayo 2013, 09:43 am por EleKtro H@cker »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
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: ResHacker.All_Resources_Extract("C:\File.exe", ResHacker.ResourceType.ICON) ResHacker.All_Resources_Extract("C:\File.dll", ResHacker.ResourceType.BITMAP, "C:\Temp\") ResHacker.MainIcon_Delete("C:\Old.exe", "C:\New.exe") ResHacker.MainIcon_Extract("C:\Program.exe", "C:\Icon.ico") ResHacker.MainIcon_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico") ResHacker.Resource_Add("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "Test", 1033) ResHacker.Resource_Delete("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Resource_Extract("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Resource_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Run_Script("C:\Reshacker.txt") ResHacker.Check_Last_Error()
#Region " ResHacker class " Public Class ResHacker ''' <summary> ''' Set the location of ResHacker executable [Default: ".\Reshacker.exe"]. ''' </summary> Public Shared ResHacker_Location As String = ".\ResHacker.exe" ''' <summary> ''' Set the location of ResHacker log file [Default: ".\Reshacker.log"]. ''' </summary> Public Shared ResHacker_Log_Location As String = ResHacker_Location.Substring(0, ResHacker_Location.Length - 4) & ".log" ' Most Known ResourceTypes ''' <summary> ''' The most known ResourceTypes. ''' </summary> Enum ResourceType ASFW AVI BINARY BINDATA BITMAP CURSOR DIALOG DXNAVBARSKINS FONT FTR GIF HTML IBC ICON IMAGE JAVACLASS JPGTYPE LIBRARY MASK MENU MUI ORDERSTREAM PNG RCDATA REGINST REGISTRY STRINGTABLE RT_RCDATA SHADER STYLE_XML TYPELIB UIFILE VCLSTYLE WAVE WEVT_TEMPLATE XML XMLWRITE End Enum ' ------------------ ' MainIcon functions ' ------------------ ''' <summary> ''' Extract the main icon from file. ''' </summary> Public Shared Function MainIcon_Extract(ByVal InputFile As String, _ ByVal OutputIcon As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputIcon & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Delete the main icon of file. ''' </summary> Public Shared Function MainIcon_Delete(ByVal InputFile As String, _ ByVal OutputFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Replace the main icon of file. ''' </summary> Public Shared Function MainIcon_Replace(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal IconFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & IconFile & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ---------------------- ' ResourceType functions ' ---------------------- ''' <summary> ''' Add a resource to file. ''' </summary> Public Shared Function Resource_Add(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-add " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Delete a resource from file. ''' </summary> Public Shared Function Resource_Delete(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Extract a resource from file. ''' </summary> Public Shared Function Resource_Extract(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Replace a resource from file. ''' </summary> Public Shared Function Resource_Replace(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ---------------------- ' All resources function ' ---------------------- ''' <summary> ''' Extract all kind of resource from file. ''' </summary> Public Shared Function All_Resources_Extract(ByVal InputFile As String, _ ByVal ResourceType As ResourceType, _ Optional ByVal OutputDir As String = Nothing) As Boolean If OutputDir Is Nothing Then OutputDir = InputFile.Substring(0, InputFile.LastIndexOf("\")) _ & "\" _ & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) _ & ".rc" Else If OutputDir.EndsWith("\") Then OutputDir = OutputDir.Substring(0, OutputDir.Length - 1) OutputDir += "\" & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) & ".rc" End If Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputDir & """" & ", " & ResourceType.ToString & ",," ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' --------------- ' Script function ' --------------- ''' <summary> ''' Run a ResHacker script file. ''' </summary> Public Shared Function Run_Script(ByVal ScriptFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-script " & """" & ScriptFile & """" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ------------------------- ' Check Last Error function ' ------------------------- ''' <summary> ''' Return the last operation error if any [False = ERROR, True = Ok]. ''' </summary> Shared Function Check_Last_Error() Dim Line As String = Nothing Dim Text As IO. StreamReader = IO. File. OpenText(ResHacker_Log_Location ) Do Until Text.EndOfStream Line = Text.ReadLine() If Line.ToString.StartsWith("Error: ") Then MsgBox(Line) Return False End If Loop Text.Close() Text.Dispose() Return True End Function End Class #End Region
|
|
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
25,810
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,068
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
21,046
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,065
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
6,507
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|