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

 

 


Tema destacado: Curso de javascript por TickTack


  Mostrar Mensajes
Páginas: 1 ... 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 [924] 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 ... 1236
9231  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 15 Abril 2013, 18:12 pm
· Convierte un string a LowerCase/Titlecase/UpperCase/WordCase

Código
  1. #Region " String to Case "
  2.  
  3.    ' [ String to Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase))
  9.    ' Var = String_To_WordCase(Var, StringCase.LowerCase)
  10.  
  11.    Public Enum StringCase
  12.        LowerCase
  13.        Titlecase
  14.        UpperCase
  15.        WordCase
  16.    End Enum
  17.  
  18.    Private Function String_To_Case(ByVal str As String, ByVal StringCase As StringCase) As String
  19.        Select Case StringCase
  20.            Case Form1.StringCase.LowerCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(str)
  21.            Case Form1.StringCase.Titlecase : Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase)
  22.            Case Form1.StringCase.UpperCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(str)
  23.            Case Form1.StringCase.WordCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str)
  24.            Case Else : Return Nothing
  25.        End Select
  26.    End Function
  27.  
  28. #End Region
9232  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) 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...

Código
  1. #Region " Remove Last Char "
  2.  
  3.    ' [ Remove Last Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Remove_Last_Char("C:\Folder\"))
  9.    ' Var = Remove_Last_Char(Var)
  10.  
  11.    Private Function Remove_Last_Char(ByVal str As String) As String
  12.        Return str.Substring(0, str.Length - 1)
  13.    End Function
  14.  
  15. #End Region
9233  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 15 Abril 2013, 16:43 pm
· Devuelve información sobre archivos comprimidos (tamaño, nombre de los archivos internos, total de archivos internos..)

Código
  1. #Region " SevenZipSharp FileInfo "
  2.  
  3.    ' [ SevenZipSharp FileInfo Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(SevenZipSharp_FileInfo("C:\Test.7z", SevenZip_Info.Format))
  14.    ' For Each FileName In SevenZipSharp_FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next
  15.  
  16.    Imports SevenZip
  17.    Dim dll As String = "7z.dll"
  18.  
  19.    Public Enum SevenZip_Info
  20.        FileName
  21.        Format
  22.        Size_In_Bytes
  23.        Internal_Files_FileNames
  24.        Total_Internal_Files
  25.    End Enum
  26.  
  27.    Private Function SevenZipSharp_FileInfo(ByVal InputFile As String, ByVal Info As SevenZip_Info)
  28.  
  29.        Try
  30.            ' Set library path
  31.            SevenZip.SevenZipExtractor.SetLibraryPath(dll)
  32.  
  33.            ' Create extractor and specify the file to extract
  34.            Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile)
  35.  
  36.            ' Return info
  37.            Select Case Info
  38.  
  39.                Case SevenZip_Info.FileName
  40.                    Return Extractor.FileName
  41.  
  42.                Case SevenZip_Info.Format
  43.                    Return Extractor.Format
  44.  
  45.                Case SevenZip_Info.Size_In_Bytes
  46.                    Return Extractor.PackedSize
  47.  
  48.                Case SevenZip_Info.Total_Internal_Files
  49.                    Return Extractor.FilesCount
  50.  
  51.                Case SevenZip_Info.Internal_Files_FileNames
  52.                    Dim FileList As New List(Of String)
  53.                    For Each Internal_File In Extractor.ArchiveFileData
  54.                        FileList.Add(Internal_File.FileName)
  55.                    Next
  56.                    Return FileList
  57.  
  58.                Case Else
  59.                    Return Nothing
  60.  
  61.            End Select
  62.  
  63.            Extractor.Dispose()
  64.  
  65.        Catch ex As Exception
  66.            ' Return nothing
  67.            Throw New Exception(ex.Message)
  68.        End Try
  69.  
  70.    End Function
  71.  
  72. #End Region
9234  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 15 Abril 2013, 16:11 pm
· Descomprimir con la librería SevenzipSharp:

EDITO: Mejorado (Extracción con password)

Código
  1. #Region " SevenZipSharp Extract "
  2.  
  3.    ' [ SevenZipSharp Extract Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Extract("C:\File.7zip")                  ' Will be extracted in the same dir.
  14.    ' SevenZipSharp_Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\".
  15.    ' SevenZipSharp_Extract("C:\File.7zip", , "Password")    ' Will be extracted with the given password.
  16.  
  17.    Imports SevenZip
  18.    Dim dll As String = "7z.dll"
  19.  
  20.    Private Function SevenZipSharp_Extract(ByVal InputFile As String, _
  21.                                           Optional ByVal OutputDir As String = Nothing, _
  22.                                           Optional ByVal Password As String = "Nothing") As Boolean
  23.  
  24.        Try
  25.            ' Set library path
  26.            SevenZipExtractor.SetLibraryPath(dll)
  27.  
  28.            ' Create extractor and specify the file to extract
  29.            Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password)
  30.  
  31.            ' Specify the output path where the files will be extracted
  32.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  33.  
  34.            ' Add Progress Handler
  35.            ' AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress
  36.  
  37.            ' Check for password matches
  38.            If Extractor.Check() Then
  39.                ' Start the extraction
  40.                Extractor.BeginExtractArchive(OutputDir)
  41.            Else
  42.                Return False ' Bad password
  43.            End If
  44.  
  45.            Return True ' File extracted
  46.  
  47.            Extractor.Dispose()
  48.  
  49.        Catch ex As Exception
  50.            'Return False ' File not extracted
  51.            Throw New Exception(ex.Message)
  52.        End Try
  53.  
  54.    End Function
  55.  
  56.    ' Public Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  57.    '     MsgBox("Percent extracted: " & e.PercentDone)
  58.    ' End Sub
  59.  
  60. #End Region





· Comprimir con la librería SevenzipSharp:

EDITO: Mejorado (Compresión con password)

Código
  1. #Region " SevenZipSharp Compress "
  2.  
  3.    ' [ SevenZipSharp Compress Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Compress("C:\File.txt")                          ' File will be compressed in the same dir.
  14.    ' SevenZipSharp_Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Extracted\".
  15.    ' SevenZipSharp_Compress("C:\Folder\", , , , , , "Password")     ' File will be compressed with the given password.
  16.    ' SevenZipSharp_Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra)
  17.  
  18.    Imports SevenZip
  19.    Dim dll As String = "7z.dll"
  20.  
  21.    Private Function SevenZipSharp_Compress(ByVal Input_DirOrFile As String, _
  22.                                       Optional ByVal OutputFileName As String = Nothing, _
  23.                                       Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
  24.                                       Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
  25.                                       Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
  26.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  27.                                       Optional ByVal Password As String = Nothing) As Boolean
  28.        Try
  29.            ' Set library path
  30.            SevenZipExtractor.SetLibraryPath(dll)
  31.  
  32.            ' Create compressor and specify the file or folder to compress
  33.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  34.  
  35.            ' Set compression parameters
  36.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  37.            Compressor.CompressionMethod = CompressionMethod ' Append files to compressed file or overwrite the compressed file.
  38.            Compressor.ArchiveFormat = Format ' Compression file format
  39.            Compressor.CompressionMode = CompressionMode ' Compression mode
  40.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  41.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  42.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  43.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  44.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  45.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  46.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  47.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  48.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  49.  
  50.            ' Get File extension
  51.            Dim CompressedFileExtension As String = Nothing
  52.            Select Case Compressor.ArchiveFormat
  53.                Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
  54.                Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
  55.                Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
  56.                Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
  57.                Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
  58.                Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
  59.            End Select
  60.  
  61.            ' Add Progress Handler
  62.            'AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  63.  
  64.            ' Removes the end slash ("\") if given for a directory
  65.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  66.  
  67.            ' Generate the OutputFileName if any is given.
  68.            If OutputFileName Is Nothing Then _
  69.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")
  70.  
  71.            ' Check if given argument is Dir or File ...then start the compression
  72.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  73.                If Not Password Is Nothing Then
  74.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  75.                Else
  76.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  77.                End If
  78.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  79.                If Not Password Is Nothing Then
  80.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  81.                Else
  82.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  83.                End If
  84.            End If
  85.  
  86.        Catch ex As Exception
  87.            'Return False ' File not compressed
  88.            Throw New Exception(ex.Message)
  89.        End Try
  90.  
  91.        Return True ' File compressed
  92.  
  93.    End Function
  94.  
  95.    ' Public Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  96.    '     MsgBox("Percent compressed: " & e.PercentDone)
  97.    ' End Sub
  98.  
  99. #End Region
9235  Programación / Scripting / Re: Código para apretar una tecla elegida y que se cierre la aplicación en batch. en: 15 Abril 2013, 12:34 pm
De la misma forma que se puede apagar una aplicación pasando un tiempo, no veo imposible el crear un código para que al pulsar la tecla que elijamos, el batch mande la orden de cerrar la aplicación...

Si, claro... eso es algo muy posible en cualquier lenguaje, pero en Batch lamentáblemente NO, lo que quieres es capturar los eventos del teclado, y no puedes hacerlo de ninguna manera, es imposible.

Batch es procesamiento por lotes, como te han comentado no se pueden hacer 2 cosas al mismo tiempo... Primero se procesa "X", y luego "Y", no puedes procesar "Y" a la espera de "X".

A lo que daniel.r.23 se refiere es al archivo keyboard.dat de la aplicación Keyboard.exe, que es un comando de Windows XP y anteriores, dicho comando fue excluido en win 7/8 (dudo que lo puedas usar en ese SO), pero para nada sirve para tu propósito, el comando keyboard.exe es un prompt (Como set /P) es  decir, es un comando que pausa la ejecución del script (como ya dijimos no se pueden procesar 2 cosas a la vez en Batch) pero con la diferencia de que sólo permite pulsar una tecla, y al pulsarla devuelve el código de la letra, nada más.

La única solución es recurrir a otro lenguaje como VBScript, o alguna aplicación CommandLine externa, por ejemplo para configurar un Hotkey del escritorio (O un hotkey global), y al teclear el hotkey, mandar la orden de cerrar el proceso de la CMD.

EDITO: ...O generar un exe en otro lenguaje que cumpla lo que pides, capturar la tecla "X" del keyboard y si se pulsa cerrar la instancia de tu CMD, yo la haría para que pudiera pasarle dos argumentos, un argumento para la tecla a capturar, y un segundo argumento para el título del script (el título de la ventana del CMD que se qquiere cerrar), para no cerrar todos los procesos "CMD.exe" de golpe. Es algo fácil hacerlo, de verdad.

Saludos!


9236  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 13 Abril 2013, 18:23 pm
· Enviar evento click del ratón.

Código
  1. #Region " Mouse Click "
  2.  
  3.    ' [ Mouse Click ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Click(MouseButton.Left)      ' Press the left click button
  9.    ' Mouse_Click(MouseButton.Left_Down) ' Hold the left click button
  10.    ' Mouse_Click(MouseButton.Left_Up)   ' Release the left click button
  11.  
  12.    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)
  13.  
  14.    Public Enum MouseButton As Int32
  15.  
  16.        Left_Down = &H2    ' Left button (hold)
  17.        Left_Up = &H4      ' Left button (release)
  18.  
  19.        Right_Down = &H8   ' Right button (hold)
  20.        Right_Up = &H10    ' Right button (release)
  21.  
  22.        Middle_Down = &H20 ' Middle button (hold)
  23.        Middle_Up = &H40   ' Middle button (release)
  24.  
  25.        Left               ' Left   button (press)
  26.        Right              ' Right  button (press)
  27.        Middle             ' Middle button (press)
  28.  
  29.    End Enum
  30.  
  31.    Private Sub Mouse_Click(ByVal MouseButton As MouseButton)
  32.        Select Case MouseButton
  33.            Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
  34.            Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
  35.            Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
  36.            Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
  37.        End Select
  38.    End Sub
  39.  
  40. #End Region





· Setear la posición del mouse sin APIs y con posibilidad de restingir el movimiento a la pantalla primária.

Código
  1. #Region " Set Cursor Pos "
  2.  
  3.    ' [ Set Cursor Pos Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Cursor_Pos(500, 500)
  9.    ' Set_Cursor_Pos(2500, 0, False)
  10.  
  11.    Private Sub Set_Cursor_Pos(ByVal X As Int32, ByVal Y As Int32, _
  12.                                    Optional ByVal Enable_Extended_Screen As Boolean = True)
  13.  
  14.        If Not Enable_Extended_Screen Then
  15.            Dim Screen_X = My.Computer.Screen.Bounds.Width
  16.            Dim Screen_Y = My.Computer.Screen.Bounds.Height
  17.            If X > Screen_X Then X = Screen_X
  18.            If Y > Screen_Y Then Y = Screen_Y
  19.        End If
  20.  
  21.        Cursor.Position = New System.Drawing.Point(X, Y)
  22.  
  23.    End Sub
  24.  
  25. #End Region





· Devuelve la posición del mouse en formato seleccionable

Código
  1. #Region " Get Cursor Pos "
  2.  
  3.    Public Enum Cursor_Data
  4.        AsText
  5.        AsPoint
  6.    End Enum
  7.  
  8.    ' [ Get Cursor Pos Function ]
  9.    '
  10.    ' // By Elektro H@cker
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsText))
  14.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsPoint).ToString)
  15.  
  16.    Private Function Get_Cursor_Pos(ByVal Cursor_Data As Cursor_Data)
  17.        Select Case Cursor_Data
  18.            Case Cursor_Data.AsText : Return Cursor.Position.X & ", " & Cursor.Position.Y
  19.            Case Cursor_Data.AsPoint : Return Cursor.Position
  20.            Case Else : Return Nothing
  21.        End Select
  22.    End Function
  23.  
  24. #End Region



· Mueve el cursor

Código
  1. #Region " Mouse Move "
  2.  
  3.    ' [ Mouse Move ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Move(-50, 0) ' Move the cursor 50 pixels to left
  9.    ' Mouse_Move(+50, 0) ' Move the cursor 50 pixels to right
  10.    ' Mouse_Move(0, +50) ' Move the cursor 50 pixels to down
  11.    ' Mouse_Move(0, -50) ' Move the cursor 50 pixels to up
  12.  
  13.    Public Enum MouseMove_Event As Int32
  14.        Move = &H1
  15.    End Enum
  16.  
  17.    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)
  18.  
  19.    Private Sub Mouse_Move(ByVal X As Int32, ByVal Y As Int32)
  20.        Mouse_Event(&H1, X, Y, 0, 0)
  21.    End Sub
  22.  
  23. #End Region
9237  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 13 Abril 2013, 17:29 pm
· Devuelve la resolución de la pantalla primária o de la pantalla extendida

Código
  1. #Region " Get Screen Resolution "
  2.  
  3.    ' [ Get Screen Resolution Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Screen_Resolution(False).ToString)
  9.    ' MsgBox(Get_Screen_Resolution(True).ToString)
  10.    ' Me.Size = Get_Screen_Resolution()
  11.  
  12.    Private Function Get_Screen_Resolution(ByVal Get_Extended_Screen_Resolution As Boolean) As Point
  13.  
  14.        If Not Get_Extended_Screen_Resolution Then
  15.            Return New Point(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
  16.        Else
  17.            Dim X As Integer, Y As Integer
  18.  
  19.            For Each screen As Screen In screen.AllScreens
  20.                X += screen.Bounds.Width
  21.                Y += screen.Bounds.Height
  22.            Next
  23.  
  24.            Return New Point(X, Y)
  25.        End If
  26.  
  27.    End Function
  28.  
  29. #End Region
9238  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 13 Abril 2013, 15:50 pm
· Convierte entero a caracter

Código
  1. #Region " Byte To Char "
  2.  
  3.    ' [ Byte To Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Byte_To_Char(97)) ' Result: a
  9.  
  10.    Private Function Byte_To_Char(ByVal int As Int32) As String
  11.        Return Convert.ToChar(int)
  12.    End Function
  13.  
  14. #End Region



· Convierte caracter a entero

Código
  1. #Region " Char To Byte "
  2.  
  3.    ' [ Char To Byte Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Char_To_Byte("a")) ' Result: 97
  9.    ' Dim MyChar As String = "a" : MsgBox(Chr(Char_To_Byte(MyChar))) ' Result: a    ( ...xD )
  10.  
  11.    Private Function Char_To_Byte(ByVal str As String) As Int32
  12.        Dim character As Char = str & "c"
  13.        Return Convert.ToByte(character)
  14.    End Function
  15.  
  16. #End Region



· Obtiene el SHA1 de un string

Código
  1. #Region " Get SHA1 Of String "
  2.  
  3.    ' [ Get SHA1 Of String Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_String("Hello")) ' Result: D2EFCBBA102ED3339947E85F4141EB08926E40E9
  7.  
  8.    Private Function Get_SHA1_Of_String(ByVal str As String) As String
  9.        'create our SHA1 provider
  10.        Dim sha As System.Security.Cryptography.SHA1 = New System.Security.Cryptography.SHA1CryptoServiceProvider()
  11.        Dim hashedValue As String = String.Empty
  12.        'hash the data
  13.        Dim hashedData As Byte() = sha.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str))
  14.  
  15.        'loop through each byte in the byte array
  16.        For Each b As Byte In hashedData
  17.            'convert each byte and append
  18.            hashedValue += String.Format("{0,2:X2}", b)
  19.        Next
  20.  
  21.        'return the hashed value
  22.        Return hashedValue
  23.    End Function
  24.  
  25. #End Region



· Obtiene el SHA1 de un archivo

Código
  1. #Region " Get SHA1 Of File "
  2.  
  3.    ' [ Get SHA1 Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_File("C:\File.txt"))
  7.  
  8.    Private Function Get_SHA1_Of_File(ByVal File As String) As String
  9.        Dim File_Stream As New System.IO.FileStream(File, IO.FileMode.Open)
  10.        Dim sha As New System.Security.Cryptography.SHA1CryptoServiceProvider
  11.        Dim hash As Array
  12.        Dim shaHash As String
  13.        Dim sb As New System.Text.StringBuilder
  14.  
  15.        sha.ComputeHash(File_Stream)
  16.        hash = sha.Hash
  17.        For Each hashByte As Byte In hash : sb.Append(String.Format("{0:X1}", hashByte)) : Next
  18.        shaHash = sb.ToString
  19.        File_Stream.Close()
  20.  
  21.        Return shaHash
  22.    End Function
  23.  
  24. #End Region



· cifra un string en AES

Código
  1. #Region " AES Encrypt "
  2.  
  3.    ' [ AES Encrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Encrypt("Test_Text", "Test_Password")) ' Result: cv/vYwpl51/dxbxSMNSPSg==
  7.  
  8.    Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim encrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
  20.            Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
  21.            encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return encrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· descifra un string AES

Código
  1. #Region " AES Decrypt "
  2.  
  3.    ' [ AES Decrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Decrypt("cv/vYwpl51/dxbxSMNSPSg==", "Test_Password")) ' Result: Test_Text
  7.  
  8.    Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim decrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
  20.            Dim Buffer As Byte() = Convert.FromBase64String(input)
  21.            decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return decrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· Devuelve el código fuente de una URL

Código
  1. #Region " Get URL SourceCode "
  2.  
  3.    ' [ Get URL SourceCode Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_URL_SourceCode("http://www.el-hacker.com"))
  7.  
  8.    Function Get_URL_SourceCode(ByVal url As String) As String
  9.  
  10.        Dim sourcecode As String = String.Empty
  11.  
  12.        Try
  13.            Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(url)
  14.            Dim response As System.Net.HttpWebResponse = request.GetResponse()
  15.            Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
  16.            sourcecode = sr.ReadToEnd()
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.        End Try
  20.  
  21.        Return sourcecode
  22.  
  23.    End Function
  24.  
  25. #End Region



· Intercambia entre el modo pantalla completa o modo normal.

Código
  1. #Region " Toogle FullScreen "
  2.  
  3.    ' [ Toogle FullScreen ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Toogle_FullScreen()
  9.  
  10.    Dim MyFormBorderStyle = Me.FormBorderStyle
  11.    Dim MyWindowState = Me.WindowState
  12.    Dim MyTopMost = Me.TopMost
  13.    Dim IsFullscreened As Boolean
  14.  
  15.    Public Sub Toogle_FullScreen()
  16.        If Not IsFullscreened Then
  17.            IsFullscreened = True
  18.            Me.FormBorderStyle = FormBorderStyle.None
  19.            Me.WindowState = FormWindowState.Maximized
  20.            Me.TopMost = True
  21.        ElseIf IsFullscreened Then
  22.            IsFullscreened = False
  23.            Me.FormBorderStyle = MyFormBorderStyle
  24.            Me.WindowState = MyWindowState
  25.            Me.TopMost = MyTopMost
  26.        End If
  27.    End Sub
  28.  
  29. #End Region



· Devuelve la versión del Framework con el que se ha desarrollado una applicación (o DLL).

Código
  1. #Region " Get FrameWork Of File "
  2.  
  3.    ' [ Get FrameWork Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_FrameWork_Of_File("C:\My .Net Application.exe"))
  7.  
  8.    Private Function Get_FrameWork_Of_File(ByVal File As String) As String
  9.        Try
  10.            Dim FW As System.Reflection.Assembly = Reflection.Assembly.ReflectionOnlyLoadFrom(File)
  11.            Return FW.ImageRuntimeVersion
  12.        Catch ex As Exception
  13.            Return Nothing ' Is not managed code
  14.        End Try
  15.    End Function
  16.  
  17. #End Region



· Devuelve positivo si el número es primo

Código
  1. #Region " Number Is Prime? "
  2.  
  3.    ' [ Number Is Prime? Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Number_Is_Prime(4)) ' Result: False
  7.  
  8.    Private Function Number_Is_Prime(ByVal Number As Long, Optional ByVal f As Integer = 2) As Boolean
  9.        If Number = f Then Return True
  10.        If Number Mod f = 0 Or Number = 1 Then Return False _
  11.        Else Return Number_Is_Prime(Number, f + 1)
  12.    End Function
  13.  
  14. #End Region



· Valida si un string se puede usar como nombre de archivo en Windows

Código
  1. #Region " Validate Windows FileName "
  2.  
  3.    ' [ Validate Windows FileName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Validate_Windows_FileName("C:\Test.txt")) ' Result: True
  7.    ' MsgBox(Validate_Windows_FileName("C:\Te&st.txt")) ' Result: False
  8.  
  9.    Private Function Validate_Windows_FileName(ByRef FileName As String) As Boolean
  10.        Dim Windows_Reserved_Chars As String = "\/:*?""<>|"
  11.  
  12.        For i As Integer = 0 To FileName.Length - 1
  13.            If Windows_Reserved_Chars.Contains(FileName(i)) Then
  14.                Return False ' FileName is not valid
  15.            End If
  16.        Next
  17.  
  18.        Return True ' FileName is valid
  19.    End Function
  20.  
  21. #End Region



· cifra un string a Base64

Código
  1. #Region " String To Base64 "
  2.  
  3.    ' [ String To Base64 Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Base64("Test")) ' Result: VGVzdA==
  9.  
  10.    Private Function String_To_Base64(ByVal str As String) As String
  11.        Return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str))
  12.    End Function
  13.  
  14. #End Region



· descifra un string Base64 a string

Código
  1. #Region " Base64 To String "
  2.  
  3.    ' [ Base64 To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Base64_To_String("VGVzdA==")) ' Result: Test
  9.  
  10.    Private Function Base64_To_String(ByVal str As String) As String
  11.        Return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(str))
  12.    End Function
  13.  
  14. #End Region
9239  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 13 Abril 2013, 12:58 pm
· Enviar texto a una ventana PERO sin activar el foco de esa ventana :)

Ejemplo de uso:
Código
  1.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        ' Abrimos una instancia minimizada del bloc de notas
  3.        Process.Start("CMD", "/C Start /MIN Notepad.exe")
  4.        ' Y enviamos el texto a la instancia minimizada del bloc de notas!
  5.        ' Nota: El while es para esperar a que el notepad termine de cargar, no es algo imprescindible.
  6.        While Not SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D") : Application.DoEvents() : End While
  7.    End Sub

Función:
Código
  1. #Region " SendKeys To App "
  2.  
  3.    ' [ SendKeys To App Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D")
  9.  
  10.    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
  11.    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
  12.    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
  13.    Private Const EM_REPLACESEL = &HC2
  14.  
  15.    Private Function SendKeys_To_App(ByVal App_Name As String, ByVal str As String) As Boolean
  16.        Dim nPadHwnd As Long, ret As Long, EditHwnd As Long
  17.        Dim APP_WindowTitle As String
  18.  
  19.        If App_Name.ToLower.EndsWith(".exe") Then App_Name = App_Name.Substring(0, App_Name.Length - 4) ' Rename APP Name
  20.  
  21.        Dim ProcessArray = Process.GetProcessesByName(App_Name)
  22.        If ProcessArray.Length = 0 Then
  23.            Return False ' App not found
  24.        Else
  25.            APP_WindowTitle = ProcessArray(0).MainWindowTitle ' Set window title of the APP
  26.        End If
  27.  
  28.        nPadHwnd = FindWindow(App_Name, APP_WindowTitle)
  29.  
  30.        If nPadHwnd > 0 Then
  31.            EditHwnd = FindWindowEx(nPadHwnd, 0&, "Edit", vbNullString) ' Find edit window
  32.            If EditHwnd > 0 Then ret = SendMessage(EditHwnd, EM_REPLACESEL, 0&, str) ' Send text to edit window
  33.            Return True  ' Text sended
  34.        Else
  35.            Return False ' Name/Title not found
  36.        End If
  37.  
  38.    End Function
  39.  
  40. #End Region
9240  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) 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.
Páginas: 1 ... 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 [924] 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines