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

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  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 5 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 21 22 23 24 25 26 27 28 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 533,739 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #120 en: 17 Mayo 2013, 19:32 pm »

Redimensionar una imágen:

Código
  1. #Region " Resize Image "
  2.  
  3.    ' [ Save Resize Image Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' PictureBox1.Image = Resize_Image(System.Drawing.Image.FromFile("C:\Image.png"), 256, 256)
  8.  
  9.    Private Function Resize_Image(ByVal img As Image, ByVal Width As Int32, ByVal Height As Int32) As Bitmap
  10.        Dim Bitmap_Source As New Bitmap(img)
  11.        Dim Bitmap_Dest As New Bitmap(CInt(Width), CInt(Height))
  12.        Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest)
  13.        Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1)
  14.        Return Bitmap_Dest
  15.    End Function
  16.  
  17. #End Region





Redimensionar una imágen a escala:

Código
  1. #Region " Scale Image "
  2.  
  3.    ' [ Save Scale Image Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' PictureBox1.Image = Scale_Image(System.Drawing.Image.FromFile("C:\Image.png"), 3) ' Scales to x3 of original size
  8.  
  9.    Private Function Scale_Image(ByVal img As Image, ByVal ScaleFactor As Single)
  10.        Dim Bitmap_Source As New Bitmap(img)
  11.        Dim Bitmap_Dest As New Bitmap(CInt(Bitmap_Source.Width * ScaleFactor), CInt(Bitmap_Source.Height * ScaleFactor))
  12.        Dim Graphic As Graphics = Graphics.FromImage(Bitmap_Dest)
  13.        Graphic.DrawImage(Bitmap_Source, 0, 0, Bitmap_Dest.Width + 1, Bitmap_Dest.Height + 1)
  14.        Return Bitmap_Dest
  15.    End Function
  16.  
  17. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #121 en: 18 Mayo 2013, 12:28 pm »

Reproducir, pausar, detener archivos MP3/WAV/MIDI

Código
  1.    ' PlayFile
  2.    '
  3.    ' Examples:
  4.    ' Dim Audio As New PlayFile("C:\File.mp3")
  5.    ' Audio.Play()
  6.    ' Audio.Pause()
  7.    ' Audio.Resume()
  8.    ' Audio.Stop()
  9.  
  10. #Region " PlayFile Class"
  11.  
  12. ''' <summary>
  13. ''' This class is a wrapper for the Windows API calls to play wave, midi or mp3 files.
  14. ''' </summary>
  15. ''' <remarks>
  16. ''' </remarks>
  17. Public Class PlayFile
  18.    '***********************************************************************************************************
  19.    '        Class:  PlayFile
  20.    '   Written By:  Blake Pell (bpell@indiana.edu)
  21.    ' Initial Date:  03/31/2007
  22.    ' Last Updated:  02/04/2009
  23.    '***********************************************************************************************************
  24.  
  25.    ' Windows API Declarations
  26.    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
  27.  
  28.    ''' <summary>
  29.    ''' Constructor:  Location is the filename of the media to play.  Wave files and Mp3 files are the supported formats.
  30.    ''' </summary>
  31.    ''' <param name="Location"></param>
  32.    ''' <remarks></remarks>
  33.    Public Sub New(ByVal location As String)
  34.        Me.Filename = location
  35.    End Sub
  36.  
  37.    ''' <summary>
  38.    ''' Plays the file that is specified as the filename.
  39.    ''' </summary>
  40.    ''' <remarks></remarks>
  41.    Public Sub Play()
  42.  
  43.        If _filename = "" Or Filename.Length <= 4 Then Exit Sub
  44.  
  45.        Select Case Right(Filename, 3).ToLower
  46.            Case "mp3"
  47.                mciSendString("open """ & _filename & """ type mpegvideo alias audiofile", Nothing, 0, IntPtr.Zero)
  48.  
  49.                Dim playCommand As String = "play audiofile from 0"
  50.  
  51.                If _wait = True Then playCommand += " wait"
  52.  
  53.                mciSendString(playCommand, Nothing, 0, IntPtr.Zero)
  54.            Case "wav"
  55.                mciSendString("open """ & _filename & """ type waveaudio alias audiofile", Nothing, 0, IntPtr.Zero)
  56.                mciSendString("play audiofile from 0", Nothing, 0, IntPtr.Zero)
  57.            Case "mid", "idi"
  58.                mciSendString("stop midi", "", 0, 0)
  59.                mciSendString("close midi", "", 0, 0)
  60.                mciSendString("open sequencer!" & _filename & " alias midi", "", 0, 0)
  61.                mciSendString("play midi", "", 0, 0)
  62.            Case Else
  63.                Throw New Exception("File type not supported.")
  64.                Call Close()
  65.        End Select
  66.  
  67.        IsPaused = False
  68.  
  69.    End Sub
  70.  
  71.    ''' <summary>
  72.    ''' Pause the current play back.
  73.    ''' </summary>
  74.    ''' <remarks></remarks>
  75.    Public Sub Pause()
  76.        mciSendString("pause audiofile", Nothing, 0, IntPtr.Zero)
  77.        IsPaused = True
  78.    End Sub
  79.  
  80.    ''' <summary>
  81.    ''' Resume the current play back if it is currently paused.
  82.    ''' </summary>
  83.    ''' <remarks></remarks>
  84.    Public Sub [Resume]()
  85.        mciSendString("resume audiofile", Nothing, 0, IntPtr.Zero)
  86.        IsPaused = False
  87.    End Sub
  88.  
  89.    ''' <summary>
  90.    ''' Stop the current file if it's playing.
  91.    ''' </summary>
  92.    ''' <remarks></remarks>
  93.    Public Sub [Stop]()
  94.        mciSendString("stop audiofile", Nothing, 0, IntPtr.Zero)
  95.    End Sub
  96.  
  97.    ''' <summary>
  98.    ''' Close the file.
  99.    ''' </summary>
  100.    ''' <remarks></remarks>
  101.    Public Sub Close()
  102.        mciSendString("close audiofile", Nothing, 0, IntPtr.Zero)
  103.    End Sub
  104.  
  105.    Private _wait As Boolean = False
  106.    ''' <summary>
  107.    ''' Halt the program until the .wav file is done playing.  Be careful, this will lock the entire program up until the
  108.    ''' 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
  109.    ''' actually know, I'm just theorizing).  :P
  110.    ''' </summary>
  111.    ''' <value></value>
  112.    ''' <returns></returns>
  113.    ''' <remarks></remarks>
  114.    Public Property Wait() As Boolean
  115.        Get
  116.            Return _wait
  117.        End Get
  118.        Set(ByVal value As Boolean)
  119.            _wait = value
  120.        End Set
  121.    End Property
  122.  
  123.    ''' <summary>
  124.    ''' Sets the audio file's time format via the mciSendString API.
  125.    ''' </summary>
  126.    ''' <value></value>
  127.    ''' <returns></returns>
  128.    ''' <remarks></remarks>
  129.    ReadOnly Property Milleseconds() As Integer
  130.        Get
  131.            Dim buf As String = Space(255)
  132.            mciSendString("set audiofile time format milliseconds", Nothing, 0, IntPtr.Zero)
  133.            mciSendString("status audiofile length", buf, 255, IntPtr.Zero)
  134.  
  135.            buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up
  136.  
  137.            If buf = "" Then
  138.                Return 0
  139.            Else
  140.                Return CInt(buf)
  141.            End If
  142.        End Get
  143.    End Property
  144.  
  145.    ''' <summary>
  146.    ''' Gets the status of the current playback file via the mciSendString API.
  147.    ''' </summary>
  148.    ''' <value></value>
  149.    ''' <returns></returns>
  150.    ''' <remarks></remarks>
  151.    ReadOnly Property Status() As String
  152.        Get
  153.            Dim buf As String = Space(255)
  154.            mciSendString("status audiofile mode", buf, 255, IntPtr.Zero)
  155.            buf = Replace(buf, Chr(0), "")  ' Get rid of the nulls, they muck things up
  156.            Return buf
  157.        End Get
  158.    End Property
  159.  
  160.    ''' <summary>
  161.    ''' Gets the file size of the current audio file.
  162.    ''' </summary>
  163.    ''' <value></value>
  164.    ''' <returns></returns>
  165.    ''' <remarks></remarks>
  166.    ReadOnly Property FileSize() As Integer
  167.        Get
  168.            Try
  169.                Return My.Computer.FileSystem.GetFileInfo(_filename).Length
  170.            Catch ex As Exception
  171.                Return 0
  172.            End Try
  173.        End Get
  174.    End Property
  175.  
  176.    ''' <summary>
  177.    ''' Gets the channels of the file via the mciSendString API.
  178.    ''' </summary>
  179.    ''' <value></value>
  180.    ''' <returns></returns>
  181.    ''' <remarks></remarks>
  182.    ReadOnly Property Channels() As Integer
  183.        Get
  184.            Dim buf As String = Space(255)
  185.            mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
  186.  
  187.            If IsNumeric(buf) = True Then
  188.                Return CInt(buf)
  189.            Else
  190.                Return -1
  191.            End If
  192.        End Get
  193.    End Property
  194.  
  195.    ''' <summary>
  196.    ''' Used for debugging purposes.
  197.    ''' </summary>
  198.    ''' <value></value>
  199.    ''' <returns></returns>
  200.    ''' <remarks></remarks>
  201.    ReadOnly Property Debug() As String
  202.        Get
  203.            Dim buf As String = Space(255)
  204.            mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
  205.  
  206.            Return Str(buf)
  207.        End Get
  208.    End Property
  209.  
  210.    Private _isPaused As Boolean = False
  211.    ''' <summary>
  212.    ''' Whether or not the current playback is paused.
  213.    ''' </summary>
  214.    ''' <value></value>
  215.    ''' <returns></returns>
  216.    ''' <remarks></remarks>
  217.    Public Property IsPaused() As Boolean
  218.        Get
  219.            Return _isPaused
  220.        End Get
  221.        Set(ByVal value As Boolean)
  222.            _isPaused = value
  223.        End Set
  224.    End Property
  225.  
  226.    Private _filename As String
  227.    ''' <summary>
  228.    ''' The current filename of the file that is to be played back.
  229.    ''' </summary>
  230.    ''' <value></value>
  231.    ''' <returns></returns>
  232.    ''' <remarks></remarks>
  233.    Public Property Filename() As String
  234.        Get
  235.            Return _filename
  236.        End Get
  237.        Set(ByVal value As String)
  238.  
  239.            If My.Computer.FileSystem.FileExists(value) = False Then
  240.                Throw New System.IO.FileNotFoundException
  241.                Exit Property
  242.            End If
  243.  
  244.            _filename = value
  245.        End Set
  246.    End Property
  247. End Class
  248.  
  249. #End Region




Ejemplos de uso del Windows Media Player control:

Código
  1. #Region " Windows Media Player "
  2.  
  3.        AxWindowsMediaPlayer1.Visible = False
  4.        AxWindowsMediaPlayer1.URL = "C:\Audio.mp3"
  5.        AxWindowsMediaPlayer1.URL = "C:\Video.avi"
  6.        AxWindowsMediaPlayer1.settings.volume = 50
  7.        AxWindowsMediaPlayer1.settings.setMode("autoRewind", False) ' Mode indicating whether the tracks are rewound to the beginning after playing to the end. Default state is true.
  8.        AxWindowsMediaPlayer1.settings.setMode("loop", False) ' Mode indicating whether the sequence of tracks repeats itself. Default state is false.
  9.        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.
  10.        AxWindowsMediaPlayer1.settings.setMode("shuffle", False) ' Mode indicating whether the tracks are played in random order. Default state is false.
  11.        AxWindowsMediaPlayer1.Ctlcontrols.play()
  12.        AxWindowsMediaPlayer1.Ctlcontrols.stop()
  13.  
  14. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



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

Código
  1. Public Class Form1
  2.  
  3.     Private WithEvents PicBox As New PictureBox
  4.     Private WithEvents ColorDlg As ColorDialog_RealTime.Colordialog_Realtime = Nothing
  5.  
  6.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  7.         PicBox.BackColor = Color.Blue
  8.         Me.Controls.Add(PicBox)
  9.     End Sub
  10.  
  11.     Private Sub PicBox_Click(sender As Object, e As EventArgs) Handles PicBox.Click
  12.         ColorDlg = New ColorDialog_RealTime.Colordialog_Realtime
  13.         ColorDlg.Title = "Hello!"
  14.         ColorDlg.Location = New Point(Me.Right, Me.Top)
  15.         ColorDlg.Color = sender.backcolor
  16.         If ColorDlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
  17.             sender.BackColor = ColorDlg.Color
  18.         End If
  19.         ColorDlg = Nothing
  20.     End Sub
  21.  
  22.     Private Sub ColorDlg_CurrentColor(c As System.Drawing.Color) Handles ColorDlg.CurrentColor
  23.         PicBox.BackColor = c
  24.     End Sub
  25.  
  26. End Class


Código
  1. Public Class Colordialog_Realtime
  2.    Inherits ColorDialog
  3.  
  4.    Public Event CurrentColor(ByVal c As Color)
  5.  
  6.    Private Const GA_ROOT As Integer = 2
  7.    Private Const WM_PAINT As Integer = &HF
  8.    Private Const WM_CTLCOLOREDIT As Integer = &H133
  9.  
  10.    Public Declare Function GetAncestor Lib "user32.dll" _
  11.        (ByVal hWnd As IntPtr, ByVal gaFlags As Integer) As IntPtr
  12.  
  13.    Private EditWindows As List(Of ApiWindow) = Nothing
  14.  
  15.    Public Sub New()
  16.        Me.FullOpen = True
  17.    End Sub
  18.  
  19.    <Runtime.InteropServices.DllImport("user32.dll")> _
  20.    Private Shared Function SetWindowText(hWnd As IntPtr, lpString As String) As Boolean
  21.    End Function
  22.  
  23.    Private Const SWP_NOSIZE As Integer = &H1
  24.    Private Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" _
  25.        (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
  26.  
  27.    Private m_title As String = String.Empty
  28.    Private titleSet As Boolean = False
  29.  
  30.    Public Property Title() As String
  31.        Get
  32.            Return m_title
  33.        End Get
  34.        Set(value As String)
  35.            If value IsNot Nothing AndAlso value <> m_title Then
  36.                m_title = value
  37.                titleSet = False
  38.            End If
  39.        End Set
  40.    End Property
  41.  
  42.    Private m_location As Point = Point.Empty
  43.    Private locationSet As Boolean = False
  44.  
  45.    Public Property Location() As Point
  46.        Get
  47.            Return m_location
  48.        End Get
  49.        Set(value As Point)
  50.            If Not value.Equals(Point.Empty) AndAlso Not value.Equals(m_location) Then
  51.                m_location = value
  52.                locationSet = False
  53.            End If
  54.        End Set
  55.    End Property
  56.  
  57.    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
  58.    Protected Overrides Function HookProc(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  59.        Select Case msg
  60.            Case WM_PAINT
  61.                If Not titleSet AndAlso Title <> String.Empty Then
  62.                    SetWindowText(GetAncestor(hWnd, GA_ROOT), Title)
  63.                    titleSet = True
  64.                End If
  65.                If Not locationSet AndAlso Not m_location.Equals(Point.Empty) Then
  66.                    SetWindowPos(GetAncestor(hWnd, GA_ROOT), 0, m_location.X, m_location.Y, 0, 0, SWP_NOSIZE)
  67.                    locationSet = True
  68.                End If
  69.  
  70.            Case WM_CTLCOLOREDIT
  71.                If IsNothing(EditWindows) Then
  72.                    Dim mainWindow As IntPtr = GetAncestor(hWnd, GA_ROOT)
  73.                    If Not mainWindow.Equals(IntPtr.Zero) Then
  74.                        EditWindows = New List(Of ApiWindow)((New WindowsEnumerator).GetChildWindows(mainWindow, "Edit"))
  75.                    End If
  76.                End If
  77.  
  78.                If Not IsNothing(EditWindows) AndAlso EditWindows.Count = 6 Then
  79.                    Dim strRed As String = WindowsEnumerator.WindowText(EditWindows(3).hWnd)
  80.                    Dim strGreen As String = WindowsEnumerator.WindowText(EditWindows(4).hWnd)
  81.                    Dim strBlue As String = WindowsEnumerator.WindowText(EditWindows(5).hWnd)
  82.  
  83.                    Dim Red, Green, Blue As Integer
  84.                    If Integer.TryParse(strRed, Red) Then
  85.                        If Integer.TryParse(strGreen, Green) Then
  86.                            If Integer.TryParse(strBlue, Blue) Then
  87.                                RaiseEvent CurrentColor(Color.FromArgb(Red, Green, Blue))
  88.                            End If
  89.                        End If
  90.                    End If
  91.                End If
  92.        End Select
  93.  
  94.        Return MyBase.HookProc(hWnd, msg, wParam, lParam)
  95.    End Function
  96.  
  97. End Class
  98.  
  99. Class ApiWindow
  100.    Public hWnd As IntPtr
  101.    Public ClassName As String
  102.    Public MainWindowTitle As String
  103. End Class
  104.  
  105. Class WindowsEnumerator
  106.  
  107.    Private Delegate Function EnumCallBackDelegate(ByVal hwnd As IntPtr, ByVal lParam As Integer) As Integer
  108.  
  109.    Private Declare Function EnumWindows Lib "user32" _
  110.        (ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
  111.  
  112.    Private Declare Function EnumChildWindows Lib "user32" _
  113.        (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
  114.  
  115.    Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
  116.        (ByVal hwnd As IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) As Integer
  117.  
  118.    Private Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As IntPtr) As Integer
  119.  
  120.    Private Declare Function GetParent Lib "user32" (ByVal hwnd As IntPtr) As Integer
  121.  
  122.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
  123.        (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
  124.  
  125.    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
  126.        (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As System.Text.StringBuilder) As Integer
  127.  
  128.    Private _listChildren As New List(Of ApiWindow)
  129.    Private _listTopLevel As New List(Of ApiWindow)
  130.  
  131.    Private _topLevelClass As String = String.Empty
  132.    Private _childClass As String = String.Empty
  133.  
  134.    Public Overloads Function GetTopLevelWindows() As ApiWindow()
  135.        EnumWindows(AddressOf EnumWindowProc, &H0)
  136.        Return _listTopLevel.ToArray
  137.    End Function
  138.  
  139.    Public Overloads Function GetTopLevelWindows(ByVal className As String) As ApiWindow()
  140.        _topLevelClass = className
  141.        Return Me.GetTopLevelWindows()
  142.    End Function
  143.  
  144.    Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As ApiWindow()
  145.        _listChildren.Clear()
  146.        EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0)
  147.        Return _listChildren.ToArray
  148.    End Function
  149.  
  150.    Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As ApiWindow()
  151.        _childClass = childClass
  152.        Return Me.GetChildWindows(hwnd)
  153.    End Function
  154.  
  155.    Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
  156.        If GetParent(hwnd) = 0 AndAlso IsWindowVisible(hwnd) Then
  157.            Dim window As ApiWindow = GetWindowIdentification(hwnd)
  158.            If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then
  159.                _listTopLevel.Add(window)
  160.            End If
  161.        End If
  162.        Return 1
  163.    End Function
  164.  
  165.    Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
  166.        Dim window As ApiWindow = GetWindowIdentification(hwnd)
  167.        If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then
  168.            _listChildren.Add(window)
  169.        End If
  170.        Return 1
  171.    End Function
  172.  
  173.    Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow
  174.        Dim classBuilder As New System.Text.StringBuilder(64)
  175.        GetClassName(hwnd, classBuilder, 64)
  176.  
  177.        Dim window As New ApiWindow
  178.        window.ClassName = classBuilder.ToString()
  179.        window.MainWindowTitle = WindowText(hwnd)
  180.        window.hWnd = hwnd
  181.        Return window
  182.    End Function
  183.  
  184.    Public Shared Function WindowText(ByVal hwnd As IntPtr) As String
  185.        Const W_GETTEXT As Integer = &HD
  186.        Const W_GETTEXTLENGTH As Integer = &HE
  187.  
  188.        Dim SB As New System.Text.StringBuilder
  189.        Dim length As Integer = SendMessage(hwnd, W_GETTEXTLENGTH, 0, 0)
  190.        If length > 0 Then
  191.            SB = New System.Text.StringBuilder(length + 1)
  192.            SendMessage(hwnd, W_GETTEXT, SB.Capacity, SB)
  193.        End If
  194.        Return SB.ToString
  195.    End Function
  196.  
  197. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



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



Código
  1. #Region " Record Mouse Class "
  2.  
  3. ' [ Record Mouse Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. ' Record_Mouse.Start_Record()
  9. ' Record_Mouse.Stop_Record()
  10. ' Record_Mouse.Play() : While Not Record_Mouse.Play_Is_Completed : Application.DoEvents() : End While
  11. ' Record_Mouse.Mouse_Speed = 50
  12.  
  13. Public Class Record_Mouse
  14.  
  15.    ''' <summary>
  16.    ''' Sets the speed of recording/playing the mouse actions.
  17.    ''' Default value is 25.
  18.    ''' </summary>
  19.    Public Shared Mouse_Speed As Int64 = 30
  20.  
  21.    ''' <summary>
  22.    ''' Gets the status pf the current mouse play.
  23.    ''' False = Mouse task is still playing.
  24.    ''' True = Mouse task play is done.
  25.    ''' </summary>
  26.    Public Shared Play_Is_Completed As Boolean
  27.  
  28.    ' Where the mouse coordenates will be stored:
  29.    Private Shared Coordenates_List As New List(Of Point)
  30.    ' Where the mouse clicks will be stored:
  31.    Private Shared Clicks_Dictionary As New Dictionary(Of Int64, MouseButton)
  32.    ' Timer to record the mouse:
  33.    Private Shared WithEvents Record_Timer As New Timer
  34.    ' Button click count to rec/play clicks:
  35.    Private Shared Click_Count As Int32 = 0
  36.    ' Thread to reproduce the mouse actions:
  37.    Private Shared Thread_MousePlay_Var As System.Threading.Thread = New Threading.Thread(AddressOf Thread_MousePlay)
  38.    ' API to record the current mouse button state:
  39.    Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
  40.    ' API to reproduce a mouse button click:
  41.    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)
  42.    ' GetAsyncKeyState buttons status
  43.    Private Shared Last_ClickState_Left As Int64 = -1
  44.    Private Shared Last_ClickState_Right As Int64 = -1
  45.    Private Shared Last_ClickState_Middle As Int64 = -1
  46.  
  47.    Enum MouseButton
  48.  
  49.        Left_Down = &H2    ' Left button (hold)
  50.        Left_Up = &H4      ' Left button (release)
  51.  
  52.        Right_Down = &H8   ' Right button (hold)
  53.        Right_Up = &H10    ' Right button (release)
  54.  
  55.        Middle_Down = &H20 ' Middle button (hold)
  56.        Middle_Up = &H40   ' Middle button (release)
  57.  
  58.        Left               ' Left   button (press)
  59.        Right              ' Right  button (press)
  60.        Middle             ' Middle button (press)
  61.  
  62.    End Enum
  63.  
  64.    ''' <summary>
  65.    ''' Starts recording the mouse actions over the screen.
  66.    ''' It records the position of the mouse and left/right button clicks.
  67.    ''' </summary>
  68.    Public Shared Sub Start_Record()
  69.  
  70.        ' Reset vars:
  71.        Play_Is_Completed = False
  72.        Coordenates_List.Clear() : Clicks_Dictionary.Clear()
  73.        Last_ClickState_Left = -1 : Last_ClickState_Right = -1 : Last_ClickState_Middle = -1
  74.        Click_Count = 0
  75.  
  76.        ' Set Mouse Speed
  77.        Record_Timer.Interval = Mouse_Speed
  78.  
  79.        ' Start Recording:
  80.        Record_Timer.Start()
  81.  
  82.    End Sub
  83.  
  84.    ''' <summary>
  85.    ''' Stop recording the mouse actions.
  86.    ''' </summary>
  87.    Public Shared Sub Stop_Record()
  88.        Record_Timer.Stop()
  89.    End Sub
  90.  
  91.    ''' <summary>
  92.    ''' Reproduce the mouse actions.
  93.    ''' </summary>
  94.    Public Shared Sub Play()
  95.        Thread_MousePlay_Var = New Threading.Thread(AddressOf Thread_MousePlay)
  96.        Thread_MousePlay_Var.IsBackground = True
  97.        Thread_MousePlay_Var.Start()
  98.    End Sub
  99.  
  100.    ' Procedure used to store the mouse actions
  101.    Private Shared Sub Record_Timer_Tick(sender As Object, e As EventArgs) Handles Record_Timer.Tick
  102.  
  103.        Coordenates_List.Add(Control.MousePosition)
  104.  
  105.        ' Record Left click
  106.        If Not Last_ClickState_Left = GetAsyncKeyState(1) Then
  107.            Last_ClickState_Left = GetAsyncKeyState(1)
  108.            If GetAsyncKeyState(1) = 32768 Then
  109.                Click_Count += 1
  110.                Coordenates_List.Add(Nothing)
  111.                Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Down)
  112.            ElseIf GetAsyncKeyState(1) = 0 Then
  113.                Click_Count += 1
  114.                Coordenates_List.Add(Nothing)
  115.                Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Up)
  116.            End If
  117.        End If
  118.  
  119.        ' Record Right click
  120.        If Not Last_ClickState_Right = GetAsyncKeyState(2) Then
  121.            Last_ClickState_Right = GetAsyncKeyState(2)
  122.            If GetAsyncKeyState(2) = 32768 Then
  123.                Click_Count += 1
  124.                Coordenates_List.Add(Nothing)
  125.                Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Down)
  126.            ElseIf GetAsyncKeyState(2) = 0 Then
  127.                Click_Count += 1
  128.                Coordenates_List.Add(Nothing)
  129.                Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Up)
  130.            End If
  131.        End If
  132.  
  133.        ' Record Middle click
  134.        If Not Last_ClickState_Middle = GetAsyncKeyState(4) Then
  135.            Last_ClickState_Middle = GetAsyncKeyState(4)
  136.            If GetAsyncKeyState(4) = 32768 Then
  137.                Click_Count += 1
  138.                Coordenates_List.Add(Nothing)
  139.                Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Down)
  140.            ElseIf GetAsyncKeyState(4) = 0 Then
  141.                Click_Count += 1
  142.                Coordenates_List.Add(Nothing)
  143.                Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Up)
  144.            End If
  145.        End If
  146.  
  147.    End Sub
  148.  
  149.    ' Procedure to play a mouse button (click)
  150.    Private Shared Sub Mouse_Click(ByVal MouseButton As MouseButton)
  151.        Select Case MouseButton
  152.            Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
  153.            Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
  154.            Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
  155.            Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
  156.        End Select
  157.    End Sub
  158.  
  159.    ' Thread used for reproduce the mouse actions
  160.    Private Shared Sub Thread_MousePlay()
  161.  
  162.        Click_Count = 0
  163.        Clicks_Dictionary.Item(0) = Nothing
  164.  
  165.        For Each Coordenate In Coordenates_List
  166.  
  167.            Threading.Thread.Sleep(Mouse_Speed)
  168.  
  169.            If Coordenate = Nothing Then
  170.                Click_Count += 1
  171.                If Click_Count > 1 Then
  172.                    Mouse_Click(Clicks_Dictionary.Item(Click_Count))
  173.                End If
  174.            Else
  175.                Cursor.Position = Coordenate
  176.            End If
  177.  
  178.        Next
  179.  
  180.        Mouse_Click(MouseButton.Left_Up)
  181.        Mouse_Click(MouseButton.Right_Up)
  182.        Mouse_Click(MouseButton.Middle_Up)
  183.  
  184.        Play_Is_Completed = True
  185.  
  186.    End Sub
  187.  
  188. End Class
  189.  
  190. #End Region
« Última modificación: 12 Julio 2013, 09:50 am por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #124 en: 28 Mayo 2013, 18:39 pm »

Sección de ayuda para aplicaciones CommandLine.



Código
  1. #Region " Help Section "
  2.  
  3.    Private Sub Help()
  4.  
  5.        Dim Logo As String = <a><![CDATA[
  6. .____                        
  7. |    |    ____   ____   ____  
  8. |    |   /  _ \ / ___\ /  _ \
  9. |    |__(  <_> ) /_/  >  <_> )
  10. |_______ \____/\___  / \____/
  11.        \/    /_____/    By Elektro H@cker
  12. ]]></a>.Value
  13.  
  14.        Dim Help As String = <a><![CDATA[  
  15.  
  16. [+] Syntax:
  17.  
  18.    Program.exe [FILE] [SWITCHES]
  19.  
  20. [+] Switches:
  21.  
  22.    /Switch1   | Description.    (Default Value: X)
  23.    /Switch2   | Description.
  24.    /? (or) -? | Show this help.
  25.  
  26. [+] Switch value Syntax:
  27.  
  28.    /Switch1   (ms)
  29.    /Switch2   (X,Y)
  30.  
  31. [+] Usage examples:
  32.  
  33.    Program.exe "C:\File.txt" /Switch1
  34.    (Short explanation)
  35.  
  36. ]]></a>.Value
  37.  
  38.        Console.WriteLine(Logo & Help)
  39.        Application.Exit()
  40.  
  41.    End Sub
  42.  
  43. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #125 en: 29 Mayo 2013, 02:55 am »

Descarga el código fuente de una URL al disco duro

Código
  1. #Region " Download URL SourceCode "
  2.  
  3.    ' [ Download URL SourceCode ]
  4.    '
  5.    ' Examples :
  6.    ' Download_URL_SourceCode("http://www.elhacker.net", "C:\Source.html")
  7.  
  8.    Private Sub Download_URL_SourceCode(ByVal url As String, ByVal OutputFile As String)
  9.  
  10.        Try
  11.            Using TextFile As New IO.StreamWriter(OutputFile, False, System.Text.Encoding.Default)
  12.                TextFile.WriteLine(New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd())
  13.            End Using
  14.  
  15.        Catch ex As Exception
  16.            MsgBox(ex.Message)
  17.        End Try
  18.  
  19.    End Sub
  20.  
  21. #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.google.com"))
  7.    ' Clipboard.SetText(Get_URL_SourceCode("http://www.google.com"))
  8.  
  9.    Private Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing) As String
  10.  
  11.        Try
  12.            Return New System.IO.StreamReader(System.Net.HttpWebRequest.Create(url).GetResponse().GetResponseStream()).ReadToEnd()
  13.        Catch ex As Exception
  14.            MsgBox(ex.Message)
  15.            Return Nothing
  16.        End Try
  17.  
  18.    End Function
  19.  
  20. #End Region




Parsear un HTML usando RegEx

Código
  1.    Private Sub Parse_HTML(ByVal TextFile As String)
  2.  
  3.        ' RegEx
  4.        Dim RegEx_Url As New System.Text.RegularExpressions.Regex("http://www.mp3crank.com.*\.html?")
  5.        Dim RegEx_Year As New System.Text.RegularExpressions.Regex("[1-2][0-9][0-9][0-9]")
  6.  
  7.        Dim Line As String = Nothing
  8.        Dim Text As New IO.StringReader(My.Computer.FileSystem.ReadAllText(TextFile))
  9.  
  10.        Do
  11.  
  12.            Line = Text.ReadLine()
  13.  
  14.            If Line Is Nothing Then
  15.  
  16.                Exit Do ' End of file
  17.  
  18.            Else
  19.  
  20.                ' Strip Year
  21.                '
  22.                ' Example:
  23.                ' <span class="year">2009</span>
  24.                '
  25.                If Line.Contains(<a><![CDATA[<span class="year">]]></a>.Value) Then
  26.                    MsgBox(RegEx_Year.Match(Line).Groups(0).ToString)
  27.                End If
  28.  
  29.                ' Strip URL
  30.                '
  31.                ' Example:
  32.                ' <div class="album"><h2><a href="http://www.mp3crank.com/echo-movement/in-the-ocean.htm"</a></h2></div>
  33.                '
  34.                If Line.Contains(<a><![CDATA[<div class="album">]]></a>.Value) Then
  35.                    MsgBox(RegEx_Url.Match(Line).Groups(0).ToString)
  36.                End If
  37.  
  38.            End If
  39.  
  40.        Loop
  41.  
  42.        Text.Close() : Text.Dispose()
  43.  
  44.    End Sub
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #126 en: 29 Mayo 2013, 03:07 am »

Elimina un Item de un Array

Código
  1. #Region " Remove Item From Array "
  2.  
  3.    ' [ Remove Item From Array ]
  4.    '
  5.    ' Examples :
  6.    ' Dim MyArray() As String = {"Elektro", "H@cker", "Christian"}
  7.    ' Remove_Item_From_Array(MyArray, 0)               ' Remove first element => {"H@cker", "Christian"}
  8.    ' Remove_Item_From_Array(MyArray, UBound(MyArray)) ' Remove last element => {"Elektro", "H@cker"}
  9.  
  10.    Public Sub Remove_Item_From_Array(Of T)(ByRef Array_Name() As T, ByVal Index As Integer)
  11.        Array.Copy(Array_Name, Index + 1, Array_Name, Index, UBound(Array_Name) - Index)
  12.        ReDim Preserve Array_Name(UBound(Array_Name) - 1)
  13.    End Sub
  14.  
  15. #End Region



Concatena un array, con opción de enumerarlo...

Código
  1. #Region " Join Array "
  2.  
  3.    ' [ Join Array Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim MyArray() As String = {"Hola", "que", "ase?"}
  9.    ' MsgBox(Join_Array(MyArray, vbNewLine))
  10.    ' MsgBox(Join_Array(MyArray, vbNewLine, True))
  11.  
  12.    Private Function Join_Array(ByRef Array_Name As Array, ByVal Separator As String, _
  13.                                Optional ByVal Enumerate As Boolean = False) As String
  14.  
  15.        Try
  16.            If Enumerate Then
  17.                Dim Index As Int64 = 0
  18.                Dim Joined_str As String = String.Empty
  19.  
  20.                For Each Item In Array_Name
  21.                    Joined_str += Index & ". " & Item & Separator
  22.                    Index += 1
  23.                Next
  24.  
  25.                Return Joined_str
  26.            Else
  27.                Return String.Join(Separator, Array_Name)
  28.            End If
  29.  
  30.        Catch ex As Exception
  31.            MsgBox(ex.Message)
  32.            Return Nothing
  33.        End Try
  34.  
  35.    End Function
  36.  
  37. #End Region



Revierte el contenido de un texto

Código
  1. #Region " Reverse TextFile "
  2.  
  3.    ' [ Reverse TextFile ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reverse_TextFile("C:\File.txt")
  9.  
  10.    Private Sub Reverse_TextFile(ByVal File As String)
  11.  
  12.        Try
  13.  
  14.            Dim strArray() As String = IO.File.ReadAllLines(File)
  15.            Array.Reverse(strArray)
  16.  
  17.            Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  18.                WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  19.            End Using
  20.  
  21.        Catch ex As Exception
  22.            MsgBox(ex.Message)
  23.        End Try
  24.  
  25.    End Sub
  26.  
  27. #End Region



Elimina una línea de un texto

Código
  1. #Region " Delete Line From TextFile "
  2.  
  3.    ' [ Delete Line From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Delete_Line_From_TextFile("C:\File.txt", 3)
  9.    ' Delete_Line_From_TextFile("C:\File.txt", 3, True)
  10.  
  11.    Private Sub Delete_Line_From_TextFile(ByVal File As String, ByVal Line_Number As Int64, _
  12.                                          Optional ByVal Make_Empty_Line As Boolean = False)
  13.  
  14.        Dim Line_Length As Int64 = 0
  15.        Line_Number -= 1
  16.  
  17.        Try
  18.            Line_Length = IO.File.ReadAllLines(File).Length
  19.        Catch ex As Exception
  20.            MsgBox(ex.Message)
  21.            Exit Sub
  22.        End Try
  23.  
  24.        Select Case Line_Number
  25.  
  26.            Case Is <= (0 Or 1), Is > Line_Length
  27.  
  28.                MsgBox("Want to cut first " & (Line_Number - 1) & " lines" & vbNewLine & _
  29.                       "But """ & File & """ have " & Line_Length & " lines.")
  30.                Exit Sub
  31.  
  32.            Case Else
  33.  
  34.                Dim strArray() As String = IO.File.ReadAllLines(File)
  35.  
  36.                If Make_Empty_Line Then
  37.                    Array.Copy(strArray, Line_Number + 1, strArray, Line_Number, UBound(strArray) - Line_Number)
  38.                    ReDim Preserve strArray(UBound(strArray) - 1)
  39.                End If
  40.  
  41.                MsgBox(String.Join(vbNewLine, strArray))
  42.  
  43.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  44.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  45.                End Using
  46.  
  47.        End Select
  48.  
  49.    End Sub
  50.  
  51. #End Region



Elimina las primeras X líneas de un archivo de texto

Código
  1. #Region " Cut First Lines From TextFile "
  2.  
  3.    ' [ Cut First Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Cut_First_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Cut_First_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines += 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is <= (0 Or 1), Is > Line_Length
  25.  
  26.                MsgBox("Want to cut first " & (Lines - 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                Array.Reverse(strArray)
  34.                ReDim Preserve strArray(strArray.Length - (Lines))
  35.                Array.Reverse(strArray)
  36.  
  37.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  38.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  39.                End Using
  40.  
  41.        End Select
  42.  
  43.    End Sub
  44.  
  45. #End Region



Elimina las últimas X líneas de un archivo de texto

Código
  1. #Region " Cut Last Lines From TextFile "
  2.  
  3.    ' [ Cut Last Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Cut_Last_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Cut_Last_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines += 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is <= (0 Or 1), Is > Line_Length
  25.  
  26.                MsgBox("Want to cut last " & (Lines - 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                ReDim Preserve strArray(strArray.Length - (Lines))
  34.  
  35.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  36.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  37.                End Using
  38.  
  39.        End Select
  40.  
  41.    End Sub
  42.  
  43. #End Region



Guarda las primmeras X líneas y elimina el resto de líneas de un archivo de texto.

Código
  1. #Region " Keep First Lines From TextFile "
  2.  
  3.    ' [ Keep First Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Keep_First_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Keep_First_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines -= 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is < 0, Is >= Line_Length
  25.  
  26.                MsgBox("Want to keep first " & (Lines + 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                ReDim Preserve strArray(Lines)
  34.  
  35.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  36.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  37.                End Using
  38.  
  39.        End Select
  40.  
  41.    End Sub
  42.  
  43. #End Region



Guarda las últimas X líneas y elimina el resto de líneas de un archivo de texto.

Código
  1. #Region " Keep Last Lines From TextFile "
  2.  
  3.    ' [ Keep Last Lines From TextFile Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Keep_Last_Lines_From_TextFile("C:\File.txt", 3)
  9.  
  10.    Private Sub Keep_Last_Lines_From_TextFile(ByVal File As String, ByVal Lines As Int64)
  11.  
  12.        Dim Line_Length As Int64 = 0
  13.        Lines -= 1
  14.  
  15.        Try
  16.            Line_Length = IO.File.ReadAllLines(File).Length
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.            Exit Sub
  20.        End Try
  21.  
  22.        Select Case Lines
  23.  
  24.            Case Is < 0, Is >= Line_Length
  25.  
  26.                MsgBox("Want to keep last " & (Lines + 1) & " lines" & vbNewLine & _
  27.                       "But """ & File & """ have " & Line_Length & " lines.")
  28.                Exit Sub
  29.  
  30.            Case Else
  31.  
  32.                Dim strArray() As String = IO.File.ReadAllLines(File)
  33.                Array.Reverse(strArray)
  34.                ReDim Preserve strArray(Lines)
  35.                Array.Reverse(strArray)
  36.  
  37.                Using WriteFile As New IO.StreamWriter(File, False, System.Text.Encoding.Default)
  38.                    WriteFile.WriteLine(String.Join(vbNewLine, strArray))
  39.                End Using
  40.  
  41.        End Select
  42.  
  43.    End Sub
  44.  
  45. #End Region



Devuelve el el total de líneas de un archivo de texto, con opción de incluir líneas en blanco

Código
  1. #Region " Get TextFile Total Lines "
  2.  
  3.    ' [ Get TextFile Total Lines Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt"))
  8.    ' MsgBox(Get_TextFile_Total_Lines("C:\File.txt", False))
  9.  
  10.    Private Function Get_TextFile_Total_Lines(ByVal File As String, _
  11.                                              Optional ByVal Include_BlankLines As Boolean = True) As Int64
  12.        Try
  13.            If Include_BlankLines Then
  14.                Return IO.File.ReadAllLines(File).Length
  15.            Else
  16.                Dim LineCount As Int64
  17.                For Each Line In IO.File.ReadAllLines(File)
  18.                    If Not Line = String.Empty Then LineCount += 1
  19.                    ' Application.DoEvents()
  20.                Next
  21.                Return LineCount
  22.            End If
  23.        Catch ex As Exception
  24.            MsgBox(ex.Message)
  25.            Return -1
  26.        End Try
  27.    End Function
  28.  
  29. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #127 en: 29 Mayo 2013, 03:23 am »

Unos snippets especiálmente para un RichTextBox:

Devuelve la posición actual del cursor.

Código
  1. #Region " Get RichTextBox Cursor Position "
  2.  
  3.    ' [ Get RichTextBox Cursor Position Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_RichTextBox_Cursor_Position(RichTextBox1))
  9.    ' RichTextBox1.SelectionStart = (Get_RichTextBox_Cursor_Position(RichTextBox1) + 1) : RichTextBox1.Focus()
  10.  
  11.    Public Function Get_RichTextBox_Cursor_Position(ByVal RichTextBox_Object As RichTextBox) As Int64
  12.        Return RichTextBox_Object.SelectionStart
  13.    End Function
  14.  
  15. #End Region



Copia todo el texto del RichTextBox al portapapeles

Código
  1. #Region " Copy All RichTextBox Text "
  2.  
  3.    ' [ Copy All RichTextBox Text Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Copy_All_RichTextBox_Text(RichTextBox1)
  9.  
  10.    Public Sub Copy_All_RichTextBox_Text(ByVal RichTextBox_Object As RichTextBox)
  11.  
  12.        ' Save the current cursor position
  13.        Dim Caret_Position As Int64 = RichTextBox_Object.SelectionStart
  14.  
  15.        ' Save the current selected text (If any)
  16.        Dim Selected_Text_Start As Int64, Selected_Text_Length As Int64
  17.        If RichTextBox_Object.SelectionLength > 0 Then
  18.            Selected_Text_Start = RichTextBox_Object.SelectionStart
  19.            Selected_Text_Length = RichTextBox_Object.SelectionLength
  20.        End If
  21.  
  22.        RichTextBox_Object.SelectAll() ' Select all text
  23.        RichTextBox_Object.Copy() ' Copy all text
  24.        RichTextBox_Object.Select(Selected_Text_Start, Selected_Text_Length) ' Returns to the previous selected text
  25.        RichTextBox_Object.SelectionStart = Caret_Position ' Returns to the previous cursor position
  26.        ' RichTextBox_Object.Focus() ' Focus again the richtextbox
  27.  
  28.    End Sub
  29.  
  30. #End Region



Desactiva un menú contextual si el RichTextBox no contiene texto, activa el menú si el RichTextBox contiene texto.

Código
  1. #Region " Toggle RichTextBox Menu "
  2.  
  3.    ' [ Toggle RichTextBox Menu ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
  9.    '     Toogle_RichTextBox_Menu(sender, ContextMenuStrip1)
  10.    ' End Sub
  11.  
  12.    Private Sub Toggle_RichTextBox_Menu(ByVal RichTextBox As RichTextBox, ByVal ContextMenuStrip As ContextMenuStrip)
  13.        If RichTextBox.Lines.Count > 0 Then
  14.            ContextMenuStrip.Enabled = True
  15.        Else
  16.            ContextMenuStrip.Enabled = False
  17.        End If
  18.    End Sub
  19.  
  20. #End Region



Seleccionar líneas enteras

Código
  1.     ' RichTextBox [ MouseDown ]
  2.    Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown
  3.  
  4.        Try
  5.            Dim line = sender.GetLineFromCharIndex(sender.GetCharIndexFromPosition(e.Location))
  6.            Dim lineStart = sender.GetFirstCharIndexFromLine(line)
  7.            Dim lineEnd = sender.GetFirstCharIndexFromLine(line + 1) - 1
  8.            sender.SelectionStart = lineStart
  9.  
  10.            If (lineEnd - lineStart) > 0 Then
  11.                sender.SelectionLength = lineEnd - lineStart
  12.            Else
  13.                sender.SelectionLength = lineStart - lineEnd ' Reverse the values because is the last line of RichTextBox
  14.            End If
  15.  
  16.        Catch ex As Exception : MsgBox(ex.Message)
  17.        End Try
  18.  
  19.    End Sub



Abrir links en el navegador

Código
  1.    ' RichTextBox [ LinkClicked ]
  2.    Private Sub RichTextBox1_LinkClicked(sender As Object, e As LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
  3.        Process.Start(e.LinkText)
  4.    End Sub
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #128 en: 29 Mayo 2013, 03:30 am »

Comprobar la conectividad de red

Código
  1. #Region " Is Connectivity Avaliable? function "
  2.  
  3.    ' [ Is Connectivity Avaliable? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Is_Connectivity_Avaliable())
  9.    ' While Not Is_Connectivity_Avaliable() : Application.DoEvents() : End While
  10.  
  11.    Private Function Is_Connectivity_Avaliable()
  12.  
  13.        Dim WebSites() As String = {"Google.com", "Facebook.com", "Microsoft.com"}
  14.  
  15.        If My.Computer.Network.IsAvailable Then
  16.            For Each WebSite In WebSites
  17.                Try
  18.                    My.Computer.Network.Ping(WebSite)
  19.                    Return True ' Network connectivity is OK.
  20.                Catch : End Try
  21.            Next
  22.            Return False ' Network connectivity is down.
  23.        Else
  24.            Return False ' No network adapter is connected.
  25.        End If
  26.  
  27.    End Function
  28.  
  29. #End Region



Comprobar si un número es negativo

Código
  1. #Region " Number Is Negavite "
  2.  
  3.    ' [ Number Is Negavite? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Number_Is_Negavite(-5)) ' Result: True
  9.    ' MsgBox(Number_Is_Negavite(5))  ' Result: False
  10.  
  11.    Private Function Number_Is_Negavite(ByVal Number As Int64) As Boolean
  12.        Return Number < 0
  13.    End Function
  14.  
  15. #End Region



Comprobar si un número es positivo

Código
  1. #Region " Number Is Positive "
  2.  
  3.    ' [ Number Is Positive? Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Number_Is_Positive(5))  ' Result: True
  9.    ' MsgBox(Number_Is_Positive(-5)) ' Result: False
  10.  
  11.    Private Function Number_Is_Positive(ByVal Number As Int64) As Boolean
  12.        Return Number > 0
  13.    End Function
  14.  
  15. #End Region



Convierte un color html a rgb

Código
  1. #Region " HTML To RGB "
  2.  
  3.    ' [ HTML To RGB Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(HTML_To_RGB("#FFFFFF"))        ' Result: 255,255,255
  9.    ' MsgBox(HTML_To_RGB("#FFFFFF", RGB.R)) ' Result: 255
  10.  
  11.    Public Enum RGB As Int16
  12.        RGB
  13.        R
  14.        G
  15.        B
  16.    End Enum
  17.  
  18.    Private Function HTML_To_RGB(ByVal HTML_Color As String, Optional ByVal R_G_B As RGB = RGB.RGB) As String
  19.        Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color)
  20.  
  21.        Select Case R_G_B
  22.            Case RGB.R : Return Temp_Color.R
  23.            Case RGB.G : Return Temp_Color.G
  24.            Case RGB.B : Return Temp_Color.B
  25.            Case RGB.RGB : Return (Temp_Color.R & "," & Temp_Color.G & "," & Temp_Color.B)
  26.            Case Else : Return Nothing
  27.        End Select
  28.  
  29.    End Function
  30.  
  31. #End Region



Convierte color hexadecimal a html

Código
  1. #Region " HTML To HEX "
  2.  
  3.    ' [ HTML To HEX Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(HTML_To_HEX("#FFFFFF")) ' Result: 0xFFFFFF
  9.  
  10.    Private Function HTML_To_HEX(ByVal HTML_Color As String) As String
  11.        Dim Temp_Color As Color = ColorTranslator.FromHtml(HTML_Color)
  12.        Return ("0x" & Hex(Temp_Color.R) & Hex(Temp_Color.G) & Hex(Temp_Color.B))
  13.    End Function
  14.  
  15. #End Region



color rgb a html

Código
  1. #Region " RGB To HTML "
  2.  
  3.    ' [ RGB To HTML Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(RGB_To_HTML(255, 255, 255)) ' Result: #FFFFFF
  9.    ' PictureBox1.BackColor = ColorTranslator.FromHtml(RGB_To_HTML(255, 255, 255))
  10.  
  11.    Private Function RGB_To_HTML(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String
  12.        Return ColorTranslator.ToHtml(Color.FromArgb(R, G, B))
  13.    End Function
  14.  
  15. #End Region



color rgb a hexadecimal

Código
  1. #Region " RGB To HEX "
  2.  
  3.    ' [ RGB To HEX Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(RGB_To_HEX(255, 255, 255)) ' Result: 0xFFFFFF
  9.  
  10.    Private Function RGB_To_HEX(ByVal R As Int16, ByVal G As Int16, ByVal B As Int16) As String
  11.        Return ("0x" & Hex(R) & Hex(G) & Hex(B))
  12.    End Function
  13.  
  14. #End Region



color conocido a rgb

Código
  1. #Region " Color To RGB "
  2.  
  3.    ' [ Color To RGB Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_RGB(Color.White))
  9.    ' MsgBox(Color_To_RGB(Color.White, RGB.R))
  10.    ' 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))
  11.  
  12.    Public Enum RGB As Int16
  13.        RGB
  14.        R
  15.        G
  16.        B
  17.    End Enum
  18.  
  19.    Private Function Color_To_RGB(ByVal Color As Color, Optional ByVal R_G_B As RGB = RGB.RGB) As String
  20.  
  21.        Select Case R_G_B
  22.            Case RGB.R : Return Color.R
  23.            Case RGB.G : Return Color.G
  24.            Case RGB.B : Return Color.B
  25.            Case RGB.RGB : Return (Color.R & "," & Color.G & "," & Color.B)
  26.            Case Else : Return Nothing
  27.        End Select
  28.  
  29.    End Function
  30.  
  31. #End Region



color conocido a html

Código
  1. #Region " Color To HTML "
  2.  
  3.    ' [ Color To HTML Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_HTML(Color.White))
  9.    ' PictureBox1.BackColor = ColorTranslator.FromHtml(Color_To_HTML(Color.White))
  10.  
  11.    Private Function Color_To_HTML(ByVal Color As Color) As String
  12.        Return ColorTranslator.ToHtml(Color.FromArgb(Color.R, Color.G, Color.B))
  13.    End Function
  14.  
  15. #End Region



color conocido a hexadecimal

Código
  1. #Region " Color To Hex "
  2.  
  3.    ' [ Color To Hex Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Color_To_Hex(Color.White))
  9.  
  10.    Private Function Color_To_Hex(ByVal Color As Color) As String
  11.        Return ("0x" & Hex(Color.R) & Hex(Color.G) & Hex(Color.B))
  12.    End Function
  13.  
  14. #End Region



Guardar configuración en archivo INI

Código
  1.       ' By Elektro H@cker
  2.       '
  3.       ' Example content of Test.ini:
  4.       '
  5.       ' File=C:\File.txt
  6.       ' SaveFile=True
  7.  
  8.       Dim INI_File As String = ".\Test.ini"
  9.  
  10.    ' Save INI Settings
  11.    Private Sub Save_INI_Settings()
  12.  
  13.        Dim Current_Settings As String = _
  14.            "File=" & TextBox_file.Text & Environment.NewLine & _
  15.            "SaveFile=" & CheckBox_SaveFile.Checked
  16.  
  17.        My.Computer.FileSystem.WriteAllText(INI_File, Current_Settings, False)
  18.  
  19.    End Sub



Descargar imágen web

Código
  1. #Region " Get Url Image Function "
  2.  
  3.    ' [ Get Url Image Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' PictureBox1.Image = Get_URL_Image("http://www.google.com/recaptcha/static/images/smallCaptchaSpaceWithRoughAlpha.png")
  10.  
  11.    Public Function Get_URL_Image(ByVal URL As String) As System.Drawing.Bitmap
  12.        Try
  13.            Return New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(URL)))
  14.        Catch ex As Exception
  15.          MsgBox(ex.Message)
  16.          Return Nothing
  17.        End Try
  18.    End Function
  19.  
  20. #End Region



Cargar configuración desde archivo INI
(Este snippet es una versión mejorada del otro que posteé)

Código
  1.       ' By Elektro H@cker
  2.       '
  3.       ' Example content of Test.ini:
  4.       '
  5.       ' File=C:\File.txt
  6.       ' SaveFile=True
  7.  
  8.       Dim INI_File As String = ".\Test.ini"
  9.  
  10.       ' Load INI Settings
  11.       Private Sub Load_INI_Settings()
  12.  
  13.           Dim xRead As IO.StreamReader = IO.File.OpenText(INI_File)
  14.           Dim Line As String = String.Empty
  15.           Dim Delimiter As String = "="
  16.           Dim ValueName As String = String.Empty
  17.           Dim Value As Object
  18.  
  19.           Do Until xRead.EndOfStream
  20.  
  21.               Line = xRead.ReadLine().ToLower
  22.               ValueName = Line.Split(Delimiter).First
  23.               Value = Line.Split(Delimiter).Last
  24.  
  25.               Select Case ValueName.ToLower
  26.                   Case "File".ToLower : TextBox_File.Text = Value
  27.                   Case "SaveFile".ToLower : CheckBox_SaveFile.Checked()
  28.               End Select
  29.  
  30.               Application.DoEvents()
  31.  
  32.           Loop
  33.  
  34.           xRead.Close() : xRead.Dispose()
  35.  
  36.       End Sub



Obtener respuesta http

Código
  1. #Region " Get Http Response "
  2.  
  3.    ' [ Validate URL Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Response As System.Net.HttpWebResponse = Get_Http_Response(System.Net.HttpWebRequest.Create("http://www.google.com/StatusCode404"))
  8.    ' If Response.StatusCode = System.Net.HttpStatusCode.NotFound Then MsgBox("Error 404")
  9.  
  10.    Public Shared Function Get_Http_Response(request As System.Net.HttpWebRequest) As System.Net.HttpWebResponse
  11.        Try : Return DirectCast(request.GetResponse(), System.Net.HttpWebResponse)
  12.        Catch ex As System.Net.WebException
  13.            If ex.Response Is Nothing OrElse ex.Status <> System.Net.WebExceptionStatus.ProtocolError Then Throw
  14.            Return DirectCast(ex.Response, System.Net.HttpWebResponse)
  15.        End Try
  16.    End Function
  17.  
  18. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #129 en: 31 Mayo 2013, 09:27 am »

Cancelar el evento OnMove

Código
  1.    #Region " Cancel Move Form "
  2.  
  3.       ' Examples:
  4.       ' Me.Moveable = False
  5.       ' Me.Moveable = True
  6.  
  7.       Private Declare Function EnableMenuItem Lib "user32.dll" Alias "EnableMenuItem" (ByVal hMenu As IntPtr, ByVal uIDEnableItem As Int32, ByVal uEnable As Int32) As Int32
  8.  
  9.       Private bMoveable As Boolean = True
  10.  
  11.       Public Overridable Property Moveable() As Boolean
  12.           Get
  13.               Return bMoveable
  14.           End Get
  15.           Set(ByVal Value As Boolean)
  16.               If bMoveable <> Value Then
  17.                   bMoveable = Value
  18.               End If
  19.           End Set
  20.       End Property
  21.  
  22.       Protected Overrides Sub WndProc(ByRef m As Message)
  23.  
  24.           If m.Msg = &H117& Then
  25.               'Handles popup of system menu.
  26.               If m.LParam.ToInt32 \ 65536 <> 0 Then 'divide by 65536 to get hiword.
  27.                   Dim AbleFlags As Int32 = &H0&
  28.                   If Not Moveable Then AbleFlags = &H2& Or &H1&
  29.                   EnableMenuItem(m.WParam, &HF010&, &H0& Or AbleFlags)
  30.               End If
  31.           End If
  32.  
  33.           If Not Moveable Then
  34.               'Cancels any attempt to drag the window by it's caption.
  35.               If m.Msg = &HA1 Then If m.WParam.ToInt32 = &H2 Then Return
  36.               'Redundant but cancels any clicks on the Move system menu item.
  37.               If m.Msg = &H112 Then If (m.WParam.ToInt32 And &HFFF0) = &HF010& Then Return
  38.           End If
  39.  
  40.           'Return control to base message handler.
  41.           MyBase.WndProc(m)
  42.  
  43.       End Sub
  44.  
  45.    #End Region
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 21 22 23 24 25 26 27 28 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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