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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 2 3 4 [5] 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,151 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #40 en: 9 Febrero 2013, 02:10 am »

Unos snippets para monitorizar unidades...

Recopilar información de las unidades conectadas en ese momento:

Código
  1. #Region " Get Drives Info Function "
  2.  
  3.    ' [ Get Drives Info Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Dim CDROMS = Get_Drives_Info(DriveType.CDRom, True)
  10.    ' For Each Drive_Info In Get_Drives_Info(DriveType.ALL, True, True, True, True, True, True) : MsgBox(Drive_Info) : Next
  11.  
  12.    Private Enum DriveType
  13.        ALL
  14.        CDRom = IO.DriveType.CDRom
  15.        Fixed = IO.DriveType.Fixed
  16.        Network = IO.DriveType.Network
  17.        Ram = IO.DriveType.Ram
  18.        Removable = IO.DriveType.Removable
  19.        Unknown = IO.DriveType.Unknown
  20.    End Enum
  21.  
  22.    Private Function Get_Drives_Info( _
  23.       ByVal DriveType As DriveType, _
  24.       ByVal Name As Boolean, _
  25.       Optional ByVal Label As Boolean = False, _
  26.       Optional ByVal Type As Boolean = False, _
  27.       Optional ByVal Format As Boolean = False, _
  28.       Optional ByVal Size As Boolean = False, _
  29.       Optional ByVal FreeSpace As Boolean = False) As List(Of String)
  30.  
  31.        Dim Drive_Info_List As New List(Of String)
  32.        Dim Drive_Info As String = Nothing
  33.  
  34.        For Each Drive In Microsoft.VisualBasic.FileIO.FileSystem.Drives
  35.            If (DriveType = DriveType.ALL Or Drive.DriveType = DriveType) And (Drive.IsReady) Then
  36.                If Drive.IsReady = True Then
  37.                    If Name Then Drive_Info += Drive.Name & ";"
  38.                    If Label Then Drive_Info += Drive.VolumeLabel & ";"
  39.                    If Type Then Drive_Info += Drive.DriveType.ToString & ";"
  40.                    If Format Then Drive_Info += Drive.DriveFormat & ";"
  41.                    If Size Then Drive_Info += Drive.TotalSize.ToString & ";"
  42.                    If FreeSpace Then Drive_Info += Drive.TotalFreeSpace & ";"
  43.                End If
  44.            End If
  45.            If Drive_Info IsNot Nothing Then Drive_Info_List.Add(Drive_Info) : Drive_Info = Nothing
  46.        Next
  47.  
  48.        Return Drive_Info_List
  49.  
  50.    End Function
  51.  
  52. #End Region






Monitorizar la inserción/extracción de dispositivos (y obtener información adicional)

by Keyen Night

Código
  1. #Region " Monitorize Drives "
  2.  
  3.    ' Diccionario para guardar información (letra, información)
  4.    Public CurrentDrives As New Dictionary(Of Char, DriveInfoGhost)
  5.  
  6.    Public Event DriveConnected(ByVal e As IO.DriveInfo)
  7.    Public Event DriveDisconnected(ByVal e As DriveInfoGhost)
  8.  
  9.    ' Estructura que replica el contenido de DriveInfo
  10.    Public Structure DriveInfoGhost
  11.  
  12.        Public Name As String
  13.        Public AvailableFreeSpace As Long
  14.        Public DriveFormat As String
  15.        Public DriveType As IO.DriveType
  16.        Public RootDirectory As String
  17.        Public TotalFreeSpace As Long
  18.        Public TotalSize As Long
  19.        Public VolumeLabel As String
  20.  
  21.        Public Sub New(ByVal e As IO.DriveInfo)
  22.            Name = e.Name
  23.            AvailableFreeSpace = e.AvailableFreeSpace
  24.            DriveFormat = e.DriveFormat
  25.            DriveType = e.DriveType
  26.            RootDirectory = e.RootDirectory.FullName
  27.            TotalFreeSpace = e.TotalFreeSpace
  28.            TotalSize = e.TotalSize
  29.            VolumeLabel = e.VolumeLabel
  30.        End Sub
  31.  
  32.    End Structure
  33.  
  34.    ' Estructura nativa de Windows para almacenar información de dispositivos
  35.    Public Structure WindowsDrive
  36.        Public Size As Integer
  37.        Public Type As Integer
  38.        Public Reserved As Integer
  39.        Public Mask As Integer
  40.    End Structure
  41.  
  42.    ' Constantes que necesitamos
  43.    Public Enum ConstWindowsDrivers As Integer
  44.        Change = &H219
  45.        Arrival = &H8000
  46.        QueryRemove = &H8001
  47.        QueryRemoveFailed = &H8002
  48.        RemovePending = &H8003
  49.        RemoveComplete = &H8004
  50.        TypeVolume = &H2
  51.    End Enum
  52.  
  53.    Protected Overrides Sub WndProc(ByRef [Message] As Message)
  54.  
  55.        Select Case [Message].Msg ' Filtramos los mensajes
  56.            Case ConstWindowsDrivers.Change ' Si el Hardware cambió
  57.                ' Transformamos el puntero del primer parametro en una estructura de datos
  58.                Dim CurrentWDrive As WindowsDrive = CType(System.Runtime.InteropServices.Marshal.PtrToStructure([Message].LParam, GetType(WindowsDrive)), WindowsDrive)
  59.                ' Transformamos la estructura en información de la unidad
  60.                Dim CurrentDrive As IO.DriveInfo = New IO.DriveInfo(GetDriveLetter(CurrentWDrive.Mask))
  61.                ' El segundo parametros nos indica si se esta desconectando o conectando
  62.                Select Case [Message].WParam.ToInt32
  63.                    ' Se esta conectando...
  64.                    Case ConstWindowsDrivers.Arrival
  65.                        ' Si es un dispositivo de almacenamiento
  66.                        If System.Runtime.InteropServices.Marshal.ReadInt32([Message].LParam, 4) = ConstWindowsDrivers.TypeVolume Then
  67.                            ' Llamamos un evento que controla la conexión
  68.                            RaiseEvent DriveConnected(CurrentDrive)
  69.                            ' Guardamos la información del dispositivo en un diccionario fantasma (letra, información),
  70.                            ' ya que cuando se desconecte habremos perdido toda la información,
  71.                            ' sólamente nos quedara la letra de la unidad, con ella podremos volver a obtener la información a traves del diccionario'
  72.                            CurrentDrives.Add(GetDriveLetter(CurrentWDrive.Mask), New DriveInfoGhost(CurrentDrive))
  73.                        End If
  74.                        ' Si es desconectado...
  75.                    Case ConstWindowsDrivers.RemoveComplete
  76.                        ' Llamamos al evento de desconexión con la información en el diccionario fantasma,
  77.                        ' ya que no tenemos acceso a la información, porque el hardware ha sido desconectado
  78.                        RaiseEvent DriveDisconnected(CurrentDrives(GetDriveLetter(CurrentWDrive.Mask)))
  79.                        ' Removemos el hardware del diccionario
  80.                        CurrentDrives.Remove(GetDriveLetter(CurrentWDrive.Mask))
  81.                End Select
  82.        End Select
  83.  
  84.        MyBase.WndProc([Message])
  85.  
  86.    End Sub
  87.  
  88.    ' Nos traduce el código de los parametros a letras
  89.    Private Function GetDriveLetter(ByVal Mask As Integer) As Char
  90.  
  91.        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"}
  92.        Dim Devices As New BitArray(System.BitConverter.GetBytes(Mask))
  93.  
  94.        For x As Integer = 0 To Devices.Length
  95.            If Devices(x) Then
  96.                Return Names(x)
  97.            End If
  98.        Next
  99.  
  100.    End Function
  101.  
  102.    ' Eventos
  103.  
  104.    Private Sub Main_DriveConnected(ByVal e As System.IO.DriveInfo) Handles Me.DriveConnected
  105.        MessageBox.Show(String.Format("Se ha conectado la unidad {0}", e.Name))
  106.    End Sub
  107.  
  108.    Private Sub Main_DriveDisconnected(ByVal e As DriveInfoGhost) Handles Me.DriveDisconnected
  109.        MessageBox.Show(String.Format("Se ha desconectado la unidad {0}", e.Name))
  110.    End Sub
  111.  
  112. #End Region





Monitorizar la inserción/extracción de dispositivos (y obtener información adicional)

by Kub0x

PD: Añadir un listbox al Form para ver/entender como actua el code.

Código
  1. Imports System.IO
  2. Imports System.Threading
  3.  
  4. Public Class Inicio
  5.  
  6.    Private Drives() As DriveInfo
  7.    Private Delegate Sub ListenToUSB()
  8.    Private Delegate Sub UpdateListBoxText(ByVal Text As String)
  9.    Private Delegate Sub MonitorizeUSB(ByVal Drive As DriveInfo)
  10.  
  11.    Private Sub ListenToRemovableDrives()
  12.        'Mejor crear 1 sola variable que ochocientas mil e ir actualizándola periodicamente
  13.        Dim connectedDrives As DriveInfo() = Nothing
  14.        While True
  15.            connectedDrives = DriveInfo.GetDrives()
  16.            For Each drive As DriveInfo In connectedDrives
  17.                IsRemovableDrive(drive)
  18.            Next
  19.            'Aquí indica el tiempo que quieres que espere el proceso de escucha para después volver a comenzar
  20.            Thread.Sleep(2500)
  21.        End While
  22.    End Sub
  23.    Private Sub IsRemovableDrive(ByVal Drive As DriveInfo)
  24.        If Drive.IsReady And Drive.DriveType = DriveType.Removable Then
  25.            IsDriveMonitorized(Drive)
  26.        End If
  27.    End Sub
  28.    Private Function GetDrivePosInArray(ByVal Drive As DriveInfo) As Int32
  29.        Dim isInList As Boolean = False
  30.        Dim i As Int32 = 0
  31.        Do
  32.            If Not IsNothing(CType(Drives(i), Object)) Then
  33.                If Drives(i).Name = Drive.Name Then
  34.                    isInList = True
  35.                End If
  36.            End If
  37.            i += 1
  38.        Loop Until isInList Or i >= Drives.Length - 1
  39.        Return i - 1
  40.    End Function
  41.    Private Function IsDriveInList(ByVal Drive As DriveInfo) As Boolean
  42.        Dim isInList As Boolean = False
  43.        Dim i As Int32 = 0
  44.        Do
  45.            If Not IsNothing(CType(Drives(i), Object)) Then
  46.                If Drives(i).Name = Drive.Name Then
  47.                    isInList = True
  48.                End If
  49.            End If
  50.            i += 1
  51.        Loop Until isInList Or i >= Drives.Length - 1
  52.        Return isInList
  53.    End Function
  54.    Private Sub IsDriveMonitorized(ByVal Drive As DriveInfo)
  55.        If Not IsDriveInList(Drive) Then
  56.            'Como la unidad USB no está siendo monitorizada por otro subproceso
  57.            'Añadimos sus características al ListBox
  58.            ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _
  59.                                 New Object() {"Se ha conectado una nueva Memoria USB en " & Drive.Name})
  60.            Drives(Drives.Length - 1) = Drive
  61.            Array.Resize(Drives, Drives.Length + 1)
  62.            'Monitorizamos la unidad USB
  63.            Dim delegado As New MonitorizeUSB(AddressOf MonitorizeDrive)
  64.            delegado.BeginInvoke(Drive, Nothing, Nothing)
  65.        End If
  66.    End Sub
  67.    Private Sub MonitorizeDrive(ByVal Drive As DriveInfo)
  68.        Dim Removed As Boolean = False
  69.        While Not Removed
  70.            If Not Drive.IsReady Then
  71.                Removed = True
  72.                Dim pos As Int32 = GetDrivePosInArray(Drive)
  73.                ReOrganizeArray(pos)
  74.                ListBox1.BeginInvoke(New UpdateListBoxText(AddressOf UpdateLstBoxText), _
  75.                     New Object() {"La unidad USB " & Drive.Name & " fue extraída."})
  76.            End If
  77.        End While
  78.    End Sub
  79.    Private Sub ReOrganizeArray(ByVal pos As Int32)
  80.        'Eliminamos el elemento rotando el Array hacia la izquierda
  81.        Drives(pos) = Nothing
  82.        Array.Resize(Drives, Drives.Length - 1)
  83.    End Sub
  84.    Private Sub UpdateLstBoxText(ByVal Text As String)
  85.        ListBox1.Items.Add(Text)
  86.    End Sub
  87.  
  88.    Private Sub Inicio_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  89.        Drives = New DriveInfo(0) {}
  90.        Dim delegado As New ListenToUSB(AddressOf ListenToRemovableDrives)
  91.        delegado.BeginInvoke(Nothing, Nothing)
  92.    End Sub
  93.  
  94. End Class


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #41 en: 9 Febrero 2013, 05:01 am »

Calcula el CRC32 checksum de un archivo

Código
  1. #Region " Get CRC32 Function "
  2.  
  3.    ' [ Get CRC32 Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Get_CRC32("C:\File.txt"))
  8.  
  9.    Public Function Get_CRC32(ByVal sFileName As String) As String
  10.  
  11.        Try
  12.            Dim FS As IO.FileStream = New IO.FileStream(sFileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read, 8192)
  13.            Dim CRC32Result As Integer = &HFFFFFFFF
  14.            Dim Buffer(4096) As Byte
  15.            Dim ReadSize As Integer = 4096
  16.            Dim Count As Integer = FS.Read(Buffer, 0, ReadSize)
  17.            Dim CRC32Table(256) As Integer
  18.            Dim DWPolynomial As Integer = &HEDB88320
  19.            Dim DWCRC As Integer
  20.            Dim i As Integer, j As Integer, n As Integer
  21.  
  22.            ' Create CRC32 Table
  23.            For i = 0 To 255
  24.                DWCRC = i
  25.                For j = 8 To 1 Step -1
  26.                    If (DWCRC And 1) Then
  27.                        DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  28.                        DWCRC = DWCRC Xor DWPolynomial
  29.                    Else
  30.                        DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  31.                    End If
  32.                Next j
  33.                CRC32Table(i) = DWCRC
  34.            Next i
  35.  
  36.            ' Calculate CRC32 Hash
  37.            Do While (Count > 0)
  38.                For i = 0 To Count - 1
  39.                    n = (CRC32Result And &HFF) Xor Buffer(i)
  40.                    CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
  41.                    CRC32Result = CRC32Result Xor CRC32Table(n)
  42.                Next i
  43.                Count = FS.Read(Buffer, 0, ReadSize)
  44.            Loop
  45.            Return Hex(Not (CRC32Result))
  46.        Catch ex As Exception
  47.            Return Nothing
  48.        End Try
  49.  
  50.    End Function
  51.  
  52. #End Region



En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #42 en: 3 Marzo 2013, 18:29 pm »

Hexadecimal a Array de Bytes:

Código
  1. #Region " Hex to Byte-Array Function "
  2.  
  3.    ' [ Hex to Byte-Array Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Byte_Array = Hex_to_Byte_Array("000a42494c4c2047415445535ad50adc4f5ca6f9efc1252aadf9847f")
  7.    ' My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\KEYNAME", "VALUENAME", Byte_Array, Microsoft.Win32.RegistryValueKind.Binary)
  8.  
  9.    Private Function Hex_to_Byte_Array(ByVal HEX_String As String) As Byte()
  10.        Dim Bytes_Array((HEX_String.Length \ 2) - 1) As Byte
  11.        For i As Integer = 0 To HEX_String.Length - 1 Step 2
  12.            Dim HEX_Byte As String = HEX_String.Substring(i, 2)
  13.            Dim Byte_Value As Byte = Byte.Parse(HEX_Byte, Globalization.NumberStyles.AllowHexSpecifier)
  14.            Bytes_Array(i \ 2) = Byte_Value
  15.        Next
  16.        Return Bytes_Array
  17.    End Function
  18.  
  19. #End Region





Windows API Code Pack:
Código
  1. #Region " Set TaskBar Status Function "
  2.  
  3.    ' [ Set TaskBar Status Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_TaskBar_Status(TaskBar_Status.Paused)
  9.  
  10.    Public Enum TaskBar_Status
  11.        Normal = 2     ' Blue
  12.        Stopped = 4    ' Red
  13.        Paused = 8     ' Yellow
  14.        Disabled = 0   ' No colour
  15.        Undefinied = 1 ' Marquee
  16.    End Enum
  17.  
  18.    Private Function Set_TaskBar_Status(ByVal TaskBar_Status As TaskBar_Status) As Boolean
  19.        Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(TaskBar_Status)
  20.            Return True
  21.        Catch ex As Exception : Throw New Exception(ex.Message)
  22.        End Try
  23.    End Function
  24.  
  25. #End Region

Windows API Code Pack:
Código
  1. #Region " Set TaskBar Value Function "
  2.  
  3.    ' [ Set TaskBar Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_TaskBar_Value(50, 100)
  9.  
  10.    Private Function Set_TaskBar_Value(ByVal Current_Value As Integer, ByVal MAX_Value As Integer) As Boolean
  11.        Try : Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Current_Value, MAX_Value)
  12.            Return True
  13.        Catch ex As Exception : Throw New Exception(ex.Message)
  14.        End Try
  15.    End Function
  16.  
  17. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #43 en: 4 Marzo 2013, 16:11 pm »

Modificar permisos de carpetas:

Código
  1. #Region " Folder Access Function "
  2.  
  3.    ' [ Folder Access Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Folder_Access("C:\Folder", Folder_Access.Create + Folder_Access.Write, Action.Allow)
  9.    ' Set_Folder_Access("C:\Folder", Folder_Access.Delete, Action.Deny)
  10.  
  11.    Public Enum Folder_Access
  12.        Create = System.Security.AccessControl.FileSystemRights.CreateDirectories + System.Security.AccessControl.FileSystemRights.CreateFiles
  13.        Delete = System.Security.AccessControl.FileSystemRights.Delete + System.Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
  14.        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
  15.    End Enum
  16.  
  17.    Public Enum Action
  18.        Allow = 0
  19.        Deny = 1
  20.    End Enum
  21.  
  22.    Private Function Set_Folder_Access(ByVal Path As String, ByVal Folder_Access As Folder_Access, ByVal Action As Action) As Boolean
  23.        Try
  24.            Dim Folder_Info As IO.DirectoryInfo = New IO.DirectoryInfo(Path)
  25.            Dim Folder_ACL As New System.Security.AccessControl.DirectorySecurity
  26.            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))
  27.            Folder_Info.SetAccessControl(Folder_ACL)
  28.            Return True
  29.        Catch ex As Exception
  30.            Throw New Exception(ex.Message)
  31.            ' Return False
  32.        End Try
  33.  
  34. #End Region
« Última modificación: 4 Marzo 2013, 16:16 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #44 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:

Código
  1. #Region " Get Master Volume Function "
  2.  
  3.    ' [ Get Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim Volume As Integer = Get_Master_Volume(Volume_Measure.As_Integer)
  9.    ' Dim Volume As String = Get_Master_Volume(Volume_Measure.As_Percent)
  10.  
  11.    Public Enum Volume_Measure
  12.        As_Integer
  13.        As_Decimal
  14.        As_Single
  15.        As_Percent
  16.    End Enum
  17.  
  18.    Private Function Get_Master_Volume(ByVal Volume_Measure As Volume_Measure)
  19.       Select Case Volume_Measure
  20.            Case Form1.Volume_Measure.As_Integer : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100)
  21.            Case Form1.Volume_Measure.As_Decimal : Return (String.Format("{0:n2}", Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar))
  22.            Case Form1.Volume_Measure.As_Single : Return CSng(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar)
  23.            Case Form1.Volume_Measure.As_Percent : Return CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100) & "%"
  24.            Case Else : Return Nothing
  25.        End Select
  26.    End Function
  27.  
  28. #End Region

· Setear el volumen maestro:

Código
  1. #Region " Set Master Volume Function "
  2.  
  3.    ' [ Set Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Master_Volume(50)
  9.  
  10.    Private Function Set_Master_Volume(ByVal Value As Integer) As Boolean
  11.        Try : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Value / 100)
  12.            Return True
  13.        Catch ex As Exception : Throw New Exception(ex.Message)
  14.        End Try
  15.    End Function
  16.  
  17. #End Region

· Mutear el volumen maestro:
Código
  1. #Region " Mute Master Volume Function "
  2.  
  3.    ' [ Mute Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Mute_Master_Volume(False)
  9.    ' Mute_Master_Volume(True)
  10.  
  11.    Private Function Set_Master_Volume(ByVal Mute As Boolean) As Boolean
  12.        Try : Audio_Device.AudioEndpointVolume.Mute = Mute
  13.            Return True
  14.        Catch ex As Exception : Throw New Exception(ex.Message)
  15.        End Try
  16.    End Function
  17.  
  18. #End Region

· Deslizar el volumen maestro (Desvanecer o aumentar):
(Corregido)

Instrucciones:
Código:
Fade_Master_Volume(Desde el volumen, Hasta el volumen, En "X" Milisegundos, Forzar/NoForzar el devanecimiento)

Código
  1. #Region " Fade Master Volume Function "
  2.  
  3.    ' [ Fade Master Volume Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Fade_Master_Volume(0, 100, 5000, Fading_Mode.FadeIN, True)
  9.    ' Fade_Master_Volume(80, 20, 5000, Fading_Mode.FadeOUT, False)
  10.    ' Fade_Master_Volume(10, 50, 5000, Fading_Mode.None, True)
  11.  
  12.    Dim Fade_Value_MIN As Integer
  13.    Dim Fade_Value_MAX As Integer
  14.    Dim Fade_TimeOut As Long
  15.    Dim Fade_Mode As Fading_Mode
  16.    Dim Force_Fading As Boolean
  17.    Dim Fader_Timer As New Timer
  18.  
  19.    Public Enum Fading_Mode
  20.        FadeIN = 0
  21.        FadeOUT = 1
  22.        None = 2
  23.    End Enum
  24.  
  25.    ' Fade Master Volume Function
  26.    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
  27.  
  28.        If MIN <= 100 And MIN >= 0 And MAX <= 100 And MAX >= 0 Then
  29.  
  30.            Try
  31.  
  32.                Fade_Value_MIN = MIN
  33.                Fade_Value_MAX = MAX
  34.                Fade_TimeOut = Milliseconds
  35.                Fade_Mode = Mode
  36.                Force_Fading = Force
  37.  
  38.                Fader_Timer = New Timer
  39.                AddHandler Fader_Timer.Tick, AddressOf Fade_Master_Volume_Timer_Tick
  40.  
  41.                Select Case Mode
  42.                    Case Fading_Mode.FadeIN : Fader_Timer.Interval = Milliseconds / (MAX - MIN)
  43.                    Case Fading_Mode.FadeOUT : Fader_Timer.Interval = Milliseconds / (MIN - MAX)
  44.                    Case Fading_Mode.None : Fader_Timer.Interval = Milliseconds
  45.                End Select
  46.  
  47.                Fader_Timer.Enabled = True
  48.                Return True
  49.  
  50.            Catch ex As Exception : Throw New Exception(ex.Message)
  51.            End Try
  52.  
  53.        Else
  54.            Throw New Exception("Number is not in range from 0 to 100")
  55.        End If
  56.  
  57.    End Function
  58.  
  59.    ' Fade Master Volume Timer Tick Event
  60.    Private Sub Fade_Master_Volume_Timer_Tick(sender As Object, e As EventArgs)
  61.  
  62.        Dim Current_Vol As Integer = CInt(Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100)
  63.  
  64.        Select Case Fade_Mode
  65.  
  66.            Case Fading_Mode.FadeOUT
  67.                If Not Force_Fading Then
  68.                    If Not Current_Vol <= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar -= 0.01
  69.                    ElseIf Current_Vol >= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  70.                    End If
  71.                ElseIf Force_Fading Then
  72.                    If Not Fade_Value_MIN < Fade_Value_MAX Then
  73.                        Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100)
  74.                        Fade_Value_MIN -= 1
  75.                    Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  76.                    End If
  77.                End If
  78.  
  79.            Case Fading_Mode.FadeIN
  80.                If Not Force_Fading Then
  81.                    If Not Current_Vol >= Fade_Value_MAX Then : Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar += 0.01
  82.                    ElseIf Current_Vol <= Fade_Value_MAX Then : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  83.                    End If
  84.                ElseIf Force_Fading Then
  85.                    If Not Fade_Value_MIN > Fade_Value_MAX Then
  86.                        Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = (Fade_Value_MIN / 100)
  87.                        Fade_Value_MIN += 1
  88.                    Else : Fader_Timer.Stop() : Fader_Timer.Enabled = False
  89.                    End If
  90.                End If
  91.  
  92.            Case Fading_Mode.None
  93.                Audio_Device.AudioEndpointVolume.MasterVolumeLevelScalar = Fade_Value_MAX
  94.                Fader_Timer.Stop() : Fader_Timer.Enabled = False
  95.  
  96.        End Select
  97.  
  98.    End Sub
  99.  
  100. #End Region
« Última modificación: 17 Marzo 2013, 11:41 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #45 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

Código
  1. #Region " Number Is In Range Function "
  2.  
  3.    ' [ Number Is In Range Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(NumberIsInRange(50, 0, 100))
  9.    ' If NumberIsInRange(5, 1, 10) then...
  10.  
  11.    Private Function NumberIsInRange(ByVal Number As Integer, ByVal MIN As Integer, ByVal MAX As Integer) As Boolean
  12.        Select Case Number
  13.            Case MIN To MAX : Return True
  14.            Case Else : Return False
  15.        End Select
  16.    End Function
  17.  
  18. #End Region





Modificar permisos de archivos:

Código
  1. #Region " Set File Access Function "
  2.  
  3.    ' [ Set File Access Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_File_Access("C:\File.txt", File_Access.Read + File_Access.Write, Action.Allow)
  9.    ' Set_File_Access("C:\File.txt", File_Access.Full, Action.Deny)
  10.  
  11.    Public Enum File_Access
  12.        Delete = System.Security.AccessControl.FileSystemRights.Delete + Security.AccessControl.FileSystemRights.DeleteSubdirectoriesAndFiles
  13.        Read = System.Security.AccessControl.FileSystemRights.ExecuteFile + System.Security.AccessControl.FileSystemRights.Read
  14.        Write = System.Security.AccessControl.FileSystemRights.Write + Security.AccessControl.FileSystemRights.WriteAttributes + Security.AccessControl.FileSystemRights.WriteExtendedAttributes
  15.        Full = Security.AccessControl.FileSystemRights.FullControl
  16.    End Enum
  17.  
  18.    Public Enum Action
  19.        Allow = 0
  20.        Deny = 1
  21.    End Enum
  22.  
  23.    Private Function Set_File_Access(ByVal File As String, ByVal File_Access As File_Access, ByVal Action As Action) As Boolean
  24.        Try
  25.            Dim File_Info As IO.FileInfo = New IO.FileInfo(File)
  26.            Dim File_ACL As New System.Security.AccessControl.FileSecurity
  27.            File_ACL.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule(My.User.Name, File_Access, Action))
  28.            File_Info.SetAccessControl(File_ACL)
  29.            Return True
  30.        Catch ex As Exception
  31.            Throw New Exception(ex.Message)
  32.            ' Return False
  33.        End Try
  34.    End Function
  35.  
  36. #End Region


« Última modificación: 17 Marzo 2013, 11:24 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #46 en: 17 Marzo 2013, 13:13 pm »

Obtener la edición de Windows (Sólo para windows VISTA o superior)

Código
  1. #Region " Get OS Edition Function "
  2.  
  3.    ' [ Get OS Edition Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Edition As String = Get_OS_Edition()
  7.    ' MsgBox("You are running Windows " & Get_OS_Edition() & " Edition")
  8.  
  9.    Private Const STARTER As Integer = &HB
  10.    Private Const HOME_BASIC As Integer = &H2
  11.    Private Const HOME_BASIC_N As Integer = &H5
  12.    Private Const HOME_PREMIUM As Integer = &H3
  13.    Private Const HOME_PREMIUM_N As Integer = &H1A
  14.    Private Const BUSINESS As Integer = &H6
  15.    Private Const BUSINESS_N As Integer = &H10
  16.    Private Const ENTERPRISE As Integer = &H4
  17.    Private Const ENTERPRISE_N As Integer = &H1B
  18.    Private Const ULTIMATE As Integer = &H1
  19.    Private Const ULTIMATE_N As Integer = &H1C
  20.  
  21.    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
  22.  
  23.    Public Function Get_OS_Edition() As String
  24.        Dim Edition_Type As Integer
  25.        If GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, Edition_Type) Then
  26.            Select Case Edition_Type
  27.                Case STARTER : Return "Starter"
  28.                Case HOME_BASIC : Return "Home Basic"
  29.                Case HOME_BASIC_N : Return "Home Basic N"
  30.                Case HOME_PREMIUM : Return "Home Premium"
  31.                Case HOME_PREMIUM_N : Return "Home Premium N"
  32.                Case BUSINESS : Return "Business"
  33.                Case BUSINESS_N : Return "Business N"
  34.                Case ENTERPRISE : Return "Enterprise"
  35.                Case ENTERPRISE_N : Return "Enterprise N"
  36.                Case ULTIMATE : Return "Ultimate"
  37.                Case ULTIMATE_N : Return "Ultimate N"
  38.                Case Else : Return "Unknown"
  39.            End Select
  40.        End If
  41.        Return Nothing ' Windows is not VISTA or Higher
  42.    End Function
  43.  
  44. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #47 en: 17 Marzo 2013, 15:19 pm »

· Función para modificar el color del borde de un control.



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 Region


Mejorado:

Código
  1. #Region " Set Control Border Color Function "
  2.  
  3.    ' [ Set Control Border Color Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Control_Border_Color(Button1, Pens.Crimson, Pens.Red, Pens.DarkRed)
  9.    ' Set_Control_Border_Color(Checkbox1, Pens.Transparent, Pens.Transparent, Pens.Transparent)
  10.  
  11.    Dim Border_Color_Light As Pen
  12.    Dim Border_Color_Middle As Pen
  13.    Dim Border_Color_Dark As Pen
  14.    Dim Last_Handled_control As Control
  15.  
  16.    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
  17.        Try
  18.            Border_Color_Light = Color_Light
  19.            Border_Color_Middle = Color_Middle
  20.            Border_Color_Dark = Color_Dark
  21.            AddHandler Control.Paint, AddressOf Control_Paint
  22.            Last_Handled_control = Control
  23.            Return True
  24.        Catch ex As Exception : Throw New Exception(ex.Message)
  25.        End Try
  26.    End Function
  27.  
  28.    Private Sub Control_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs)
  29.        If sender.name = Last_Handled_control.Name Then
  30.            Dim offset As Integer = 0
  31.            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))))
  32.            offset += 1
  33.            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))))
  34.            offset += 1
  35.            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))))
  36.        End If
  37.    End Sub
  38.  
  39. #End Region
« Última modificación: 17 Marzo 2013, 15:39 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #48 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:

Código
  1. Private Function CheckDate(ByVal dateToCheck As Date) As Boolean
  2.        'In reality, CheckDate would get the date (current date) itself and not have it passed in
  3.        Dim retValue As Boolean = False 'Fail safe, default to false
  4.        Dim usageDatesLeft As Int16 = 3 ' set it to 4 just for testing
  5.        'Dim usageDatesLeft As Int16 = 30 ' set this to the number of days of application access
  6.  
  7.        'Hash the date
  8.        Dim hashedDate As String = HashDate(dateToCheck)
  9.        'Check to see if the hash value exists in the UsageDates
  10.  
  11.        'Initialize the container if necessary
  12.        If My.Settings.UsageDates Is Nothing Then
  13.            My.Settings.UsageDates = New System.Collections.Specialized.StringCollection
  14.        End If
  15.  
  16.        If My.Settings.UsageDates.Contains(hashedDate) Then
  17.            'then we are ok...  it's already been checked
  18.            retValue = True
  19.            usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count)
  20.  
  21.            'sanity check... if the system date is backed up to a previous date in the list, but not the last date
  22.            If usageDatesLeft <= 0 AndAlso My.Settings.UsageDates.IndexOf(hashedDate) <> My.Settings.UsageDates.Count - 1 Then
  23.                retValue = False
  24.            End If
  25.        Else
  26.            If My.Settings.UsageDates.Count < usageDatesLeft Then
  27.                My.Settings.UsageDates.Add(hashedDate)
  28.            End If
  29.            usageDatesLeft = CShort(usageDatesLeft - My.Settings.UsageDates.Count)
  30.  
  31.  
  32.            'If not, and the remining count has "slots" open, add it
  33.            If usageDatesLeft > 0 Then
  34.                retValue = True
  35.            Else
  36.                'If not and tree are no more slots, tell user, exit app
  37.                retValue = False
  38.            End If
  39.  
  40.        End If
  41.        'Display to the user how many days are remianing:
  42.        MessageBox.Show(String.Format("You have {0} day(s) remaining.", usageDatesLeft))
  43.  
  44.        Return retValue
  45.    End Function
  46.  
  47.    Private Function HashDate(ByVal dateToHash As Date) As String
  48.        'Get a hash object
  49.        Dim hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
  50.        'Take date, make it a Long date and hash it
  51.        Dim data As Byte() = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(dateToHash.ToLongDateString()))
  52.        ' Create a new Stringbuilder to collect the bytes
  53.        ' and create a string.
  54.        Dim sBuilder As New System.Text.StringBuilder()
  55.  
  56.        ' Loop through each byte of the hashed data
  57.        ' and format each one as a hexadecimal string.
  58.        Dim idx As Integer
  59.        For idx = 0 To data.Length - 1
  60.            sBuilder.Append(data(idx).ToString("x2"))
  61.        Next idx
  62.  
  63.        Return sBuilder.ToString
  64.  
  65.    End Function

3. Usar la función por ejemplo en el Form_Load:

Código
  1.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.        Dim aCount As Integer = 0
  3.        Dim loopIt As Boolean = True
  4.        'My.Settings.Reset() 'This is here for design time support... otherwise you won't get your app to run agin
  5.  
  6.        Do While loopIt
  7.            MessageBox.Show(String.Format("Checking Date: {0}.", Date.Now.AddDays(aCount)))
  8.            loopIt = CheckDate(Date.Now.AddDays(aCount))
  9.            If Not loopIt Then
  10.                MessageBox.Show("Trial Period Ended! Application closing!")
  11.                Me.Close()
  12.            Else
  13.                MessageBox.Show("You can keep using the app")
  14.            End If
  15.            aCount += 1
  16.        Loop
  17.    End Sub




· Trial period (Modificado un poco por mí)

Código
  1. #Region " Trial Period Function "
  2.  
  3.    ' [ Trial Period Function ]
  4.    '
  5.    ' Examples :
  6.    ' Trial_Get(Trial_value.As_Boolean)
  7.    ' MsgBox(String.Format("You have {0} day(s) remaining.", Trial_Get(Trial_value.As_LeftDays)))
  8.  
  9.    Public Enum Trial_value
  10.        As_Boolean
  11.        As_LeftDays
  12.        As_CountDays
  13.    End Enum
  14.  
  15.    ' Trial Period [Get]
  16.    Public Function Trial_Get(ByVal Trial_value As Trial_value)
  17.        'My.Settings.Reset() 'If you want to reset the trial period
  18.        Dim TrialCount As Integer = 0
  19.        TrialCount += 1
  20.        Return Trial_CheckDate(Date.Now.AddDays(TrialCount), Trial_value)
  21.    End Function
  22.  
  23.    ' Trial Period [CheckDate]
  24.    Public Function Trial_CheckDate(ByVal Trial_DateToCheck As Date, ByVal Trial_value As Trial_value)
  25.  
  26.        Dim Trial_retValue As Boolean = False ' Fail safe, default to false
  27.        Dim Trial_usageDatesLeft As Int16 = 7 ' Set here the number of days of Trial period
  28.        Dim Trial_hashedDate As String = Trial_HashDate(Trial_DateToCheck)
  29.  
  30.        If My.Settings.Trial_Period Is Nothing Then My.Settings.Trial_Period = New System.Collections.Specialized.StringCollection
  31.  
  32.        If My.Settings.Trial_Period.Contains(Trial_hashedDate) Then
  33.            Trial_retValue = True
  34.            Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count)
  35.            If Trial_usageDatesLeft <= 0 AndAlso My.Settings.Trial_Period.IndexOf(Trial_hashedDate) <> My.Settings.Trial_Period.Count - 1 Then Trial_retValue = False
  36.        Else
  37.            If My.Settings.Trial_Period.Count < Trial_usageDatesLeft Then My.Settings.Trial_Period.Add(Trial_hashedDate)
  38.            Trial_usageDatesLeft = CShort(Trial_usageDatesLeft - My.Settings.Trial_Period.Count)
  39.            If Trial_usageDatesLeft > 0 Then Trial_retValue = True Else Trial_retValue = False
  40.        End If
  41.  
  42.        Select Case Trial_value
  43.            Case Trial_value.As_Boolean : Return Trial_retValue ' If False then Trial Period is expired
  44.            Case Trial_value.As_LeftDays : Return Trial_usageDatesLeft ' Days left
  45.            Case Trial_value.As_CountDays : Return My.Settings.Trial_Period.Count ' Count days
  46.            Case Else : Return Nothing
  47.        End Select
  48.  
  49.    End Function
  50.  
  51.    ' Trial Period [HashDate]
  52.    Public Function Trial_HashDate(ByVal Trial_DateToHash As Date) As String
  53.        Dim Trial_Hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
  54.        Dim Trial_Data As Byte() = Trial_Hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(Trial_DateToHash.ToLongDateString()))
  55.        Dim Trial_StringBuilder As New System.Text.StringBuilder()
  56.        Dim Trial_IDX As Integer
  57.        For Trial_IDX = 0 To Trial_Data.Length - 1 : Trial_StringBuilder.Append(Trial_Data(Trial_IDX).ToString("x2")) : Next Trial_IDX
  58.        Return Trial_StringBuilder.ToString
  59.    End Function
  60.  
  61. #End Region
« Última modificación: 18 Marzo 2013, 10:53 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #49 en: 18 Marzo 2013, 11:26 am »

· String a hexadecimal:

Código
  1. #Region " String To Hex Function "
  2.  
  3.    ' [ String To Hex Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim Hex_str As String = String_To_Hex("Elektro H@cker")
  7.  
  8.    Private Function String_To_Hex(ByVal Source_String As String) As String
  9.        Dim Hex_StringBuilder As New System.Text.StringBuilder()
  10.        For Each c As Char In Source_String : Hex_StringBuilder.Append(Asc(c).ToString("x2")) : Next c
  11.        Return Hex_StringBuilder.ToString()
  12.    End Function
  13.  
  14. #End Region



· Hexadecimal a string:

Código
  1. #Region " Hex To String Function "
  2.  
  3.    ' [ Hex To String Function ]
  4.    '
  5.    ' Examples :
  6.    ' Dim str As String = Hex_To_String("456c656b74726f204840636b6572"))
  7.  
  8.    Private Function Hex_To_String(ByVal Source_String As String) As String
  9.        Dim Hex_StringBuilder As New System.Text.StringBuilder()
  10.        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
  11.        Return Hex_StringBuilder.ToString()
  12.    End Function
  13.  
  14. #End Region



· Effecto Matrix (Aplicación de consola)

Código
  1.    Module Module1
  2.        Sub Main()
  3.            Console.Title = "Matrix Effect"
  4.            Console.ForegroundColor = ConsoleColor.DarkGreen
  5.            Console.WindowLeft = InlineAssignHelper(0, 0)
  6.            Console.WindowHeight = InlineAssignHelper(Console.BufferHeight, Console.LargestWindowHeight)
  7.            Console.WindowWidth = InlineAssignHelper(Console.BufferWidth, Console.LargestWindowWidth)
  8.  
  9.            Console.CursorVisible = False
  10.            Dim width As Integer, height As Integer
  11.            Dim y As Integer()
  12.            Dim l As Integer()
  13.            Initialize(width, height, y, l)
  14.            Dim ms As Integer
  15.            While True
  16.                Dim t1 As DateTime = DateTime.Now
  17.                MatrixStep(width, height, y, l)
  18.                ms = 10 - CInt(Math.Truncate(CType(DateTime.Now - t1, TimeSpan).TotalMilliseconds))
  19.                If ms > 0 Then
  20.                    System.Threading.Thread.Sleep(ms)
  21.                End If
  22.                If Console.KeyAvailable Then
  23.                    If Console.ReadKey().Key = ConsoleKey.F5 Then
  24.                        Initialize(width, height, y, l)
  25.                    End If
  26.                End If
  27.            End While
  28.        End Sub
  29.  
  30.        Dim thistime As Boolean = False
  31.  
  32.        Private Sub MatrixStep(ByVal width As Integer, ByVal height As Integer, ByVal y As Integer(), ByVal l As Integer())
  33.            Dim x As Integer
  34.            thistime = Not thistime
  35.            For x = 0 To width - 1
  36.                If x Mod 11 = 10 Then
  37.                    If Not thistime Then
  38.                        Continue For
  39.                    End If
  40.                    Console.ForegroundColor = ConsoleColor.White
  41.                Else
  42.                    Console.ForegroundColor = ConsoleColor.DarkGreen
  43.                    Console.SetCursorPosition(x, inBoxY(y(x) - 2 - ((l(x) \ 40) * 2), height))
  44.                    Console.Write(R)
  45.                    Console.ForegroundColor = ConsoleColor.Green
  46.                End If
  47.                Console.SetCursorPosition(x, y(x))
  48.                Console.Write(R)
  49.                y(x) = inBoxY(y(x) + 1, height)
  50.                Console.SetCursorPosition(x, inBoxY(y(x) - l(x), height))
  51.                Console.Write(" "c)
  52.            Next
  53.        End Sub
  54.  
  55.        Private Sub Initialize(ByRef width As Integer, ByRef height As Integer, ByRef y As Integer(), ByRef l As Integer())
  56.            Dim h1 As Integer
  57.            Dim h2 As Integer = (InlineAssignHelper(h1, (InlineAssignHelper(height, Console.WindowHeight)) \ 2)) \ 2
  58.            width = Console.WindowWidth - 1
  59.            y = New Integer(width - 1) {}
  60.            l = New Integer(width - 1) {}
  61.            Dim x As Integer
  62.            Console.Clear()
  63.            For x = 0 To width - 1
  64.                y(x) = m_r.[Next](height)
  65.                l(x) = m_r.[Next](h2 * (If((x Mod 11 <> 10), 2, 1)), h1 * (If((x Mod 11 <> 10), 2, 1)))
  66.            Next
  67.        End Sub
  68.  
  69.        Dim m_r As New Random()
  70.        Private ReadOnly Property R() As Char
  71.            Get
  72.                Dim t As Integer = m_r.[Next](10)
  73.                If t <= 2 Then
  74.                    Return ChrW(CInt(AscW("0"c)) + m_r.[Next](10))
  75.                ElseIf t <= 4 Then
  76.                    Return ChrW(CInt(AscW("a"c)) + m_r.[Next](27))
  77.                ElseIf t <= 6 Then
  78.                    Return ChrW(CInt(AscW("A"c) + m_r.[Next](27)))
  79.                Else
  80.                    Return ChrW(m_r.[Next](32, 255))
  81.                End If
  82.            End Get
  83.        End Property
  84.  
  85.        Public Function inBoxY(ByVal n As Integer, ByVal height As Integer) As Integer
  86.            n = n Mod height
  87.            If n < 0 Then
  88.                Return n + height
  89.            Else
  90.                Return n
  91.            End If
  92.        End Function
  93.        Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
  94.            target = value
  95.            Return value
  96.        End Function
  97.  
  98.    End Module
En línea

Páginas: 1 2 3 4 [5] 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

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