Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

#150
Recorre todos los controles de "X" tipo en un container.

Código (vbnet) [Seleccionar]
#Region " Disable Controls "

   ' [ Disable Controls ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   '
   ' Disable_Controls(Of CheckBox)(Me.Controls, False)
   ' Disable_Controls(Of Button)(GroupBox1.Controls, False)

   Public Sub Disable_Controls(Of T As Control)(ByVal Container As Object, ByVal Enabled As Boolean)
       For Each control As T In Container : control.Enabled = Enabled : Next
   End Sub

#End Region







Pequeño ejemplo de como saber el tipo de objeto:

Código (vbnet) [Seleccionar]
MsgBox(TypeName(Me))      ' Result: Form1
MsgBox(TypeName(Me.Text)) ' Result: String
MsgBox(TypeName(Panel1))  ' Result: Panel








Eleкtro

#151
Hide-Restore Process

Para ocultar o reestablecer la visibilidad de un proceso,
Esto solo oculta la ventana del proceso, no lo oculta del administrador de tareas,
la función "Restore" no está muy pulida, para perfeccionarlo habría que guardar cada handle de los procesos escondidos en un tipo de diccionario si se quiere usar con más de un proceso simultáneamente, ya que cuando ocultas una ventana, el handle se vuelve "0".

EDITO: Código mejorado:

Código (vbnet) [Seleccionar]
#Region " Hide-Restore Process "

    ' [ Hide-Restore Process Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    '
    ' Hide_Process(Process.GetCurrentProcess().MainModule.ModuleName, False)
    ' Hide_Process("notepad.exe", False)
    ' Hide_Process("notepad", True)
    '
    ' Restore_Process(Process.GetCurrentProcess().MainModule.ModuleName, False)
    ' Restore_Process("notepad.exe", False)
    ' Restore_Process("notepad", True)

    Dim Process_Handle_Dictionary As New Dictionary(Of String, IntPtr)

    <System.Runtime.InteropServices.DllImport("User32")> Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Int32) As Int32
    End Function

    Private Sub Hide_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False)

        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)

        Dim proc() As Process = Process.GetProcessesByName(Process_Name)

        If Recursive Then
            For proc_num As Integer = 0 To proc.Length - 1
                Try
                    Process_Handle_Dictionary.Add(Process_Name & ";" & proc(proc_num).Handle.ToString, proc(proc_num).MainWindowHandle)
                    ShowWindow(proc(proc_num).MainWindowHandle, 0)
                Catch ex As Exception
                    ' MsgBox(ex.Message) ' The handle already exist in the Dictionary
                End Try
                Application.DoEvents()
            Next
        Else
            If Not proc.Length = 0 AndAlso Not proc(0).MainWindowHandle = 0 Then
                Process_Handle_Dictionary.Add(Process_Name & ";" & proc(0).Handle.ToString, proc(0).MainWindowHandle)
                ShowWindow(proc(0).MainWindowHandle, 0)
            End If
        End If

    End Sub

    Private Sub Restore_Process(ByVal Process_Name As String, Optional ByVal Recursive As Boolean = False)

        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)

        Dim Temp_Dictionary As New Dictionary(Of String, IntPtr) ' Replic of the "Process_Handle_Dictionary" dictionary
        For Each Process In Process_Handle_Dictionary : Temp_Dictionary.Add(Process.Key, Process.Value) : Next

        If Recursive Then
            For Each Process In Temp_Dictionary
                If Process.Key.ToLower.Contains(Process_Name.ToLower) Then
                    ShowWindow(Process.Value, 9)
                    Process_Handle_Dictionary.Remove(Process.Key)
                End If
                Application.DoEvents()
            Next
        Else
            For Each Process In Temp_Dictionary
                If Process.Key.ToLower.Contains(Process_Name.ToLower) Then
                    ShowWindow(Process.Value, 9)
                    Process_Handle_Dictionary.Remove(Process.Key)
                    Exit For
                End If
                Application.DoEvents()
            Next
        End If

    End Sub

#End Region








Eleкtro

Un panel extendido con varias propiedades nuevas e interesantes...

Código (vbnet) [Seleccionar]
'
'  /*               *\
' |#* Panel Elektro *#|
'  \*               */
'
' // By Elektro H@cker
'
'   Properties:
'   ...........
' · Disable_Flickering
' · Double_Buffer
' · Opaccity
' · Scroll_Loop

Public Class Panel_Elektro
   Inherits Panel

   Private _Opaccity As Int16 = 100
   Private _Diable_Flickering As Boolean = True
   Private _Scroll_Loop As Boolean = False

   Dim Scroll_Range As Int64 = 0

   Public Sub New()
       Me.Name = "Panel_Elektro"
       ' Me.AutoScroll = True
       ' ResumeLayout(False)
   End Sub

#Region " Properties "

   ''' <summary>
   ''' Enable/Disable any flickering effect on the panel.
   ''' </summary>
   Protected Overrides ReadOnly Property CreateParams() As CreateParams
       Get
           If _Diable_Flickering Then
               Dim cp As CreateParams = MyBase.CreateParams
               cp.ExStyle = cp.ExStyle Or &H2000000
               Return cp
           Else
               Return MyBase.CreateParams
           End If
       End Get
   End Property

   ''' <summary>
   ''' Set the Double Buffer.
   ''' </summary>
   Public Property Double_Buffer() As Boolean
       Get
           Return Me.DoubleBuffered
       End Get
       Set(ByVal Value As Boolean)
           Me.DoubleBuffered = Value
       End Set
   End Property

   ''' <summary>
   ''' Set the transparency for this panel.
   ''' </summary>
   Public Property Opaccity() As Short
       Get
           Return _Opaccity
       End Get
       Set(ByVal Value As Short)
           If Value > 100 Then Throw New Exception("Opaccity range is from 0 to 100")
           If Value < 0 Then Throw New Exception("Opaccity range is from 0 to 100")
           Me._Opaccity = Value
           Make_Opaccity(Value, Me.BackColor)
       End Set
   End Property

   ''' <summary>
   ''' Enable/Disable the flickering effects on this panel.
   '''
   ''' This property turns off any Flicker effect on the panel
   ''' ...but also reduces the performance (speed) of the panel about 30% slower.
   ''' This don't affect to the performance of the application itself, only to the performance of this control.
   ''' </summary>
   Public Property Diable_Flickering() As Boolean
       Get
           Return _Diable_Flickering
       End Get
       Set(ByVal Value As Boolean)
           Me._Diable_Flickering = Value
       End Set
   End Property

   ''' <summary>
   ''' Enable/Disable the scroll loop effect.
   ''' Only when AutoScroll option is set to "True".
   ''' </summary>
   Public Property Scroll_Loop() As Boolean
       Get
           Return _Scroll_Loop
       End Get
       Set(ByVal Value As Boolean)
           Me._Scroll_Loop = Value
       End Set
   End Property

#End Region

#Region " Event handlers "

   ' Scroll
   Private Sub Infinite_Scroll_Button(sender As Object, e As ScrollEventArgs) Handles Me.Scroll

       If _Scroll_Loop AndAlso Me.AutoScroll Then

           Set_Scroll_Range()

           If Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' Button Down
               Me.VerticalScroll.Value = 1
           ElseIf Me.VerticalScroll.Value <= 0 Then ' Button Up
               Me.VerticalScroll.Value = Scroll_Range
           End If

       End If

   End Sub

   ' MouseWheel (Scroll)
   Private Sub Infinite_Scroll_MouseWheel(sender As Object, e As MouseEventArgs) Handles Me.MouseWheel

       If _Scroll_Loop AndAlso Me.AutoScroll Then

           Set_Scroll_Range()

           If e.Delta < 0 AndAlso Me.VerticalScroll.Value >= Scroll_Range - 4 Then ' MouseWheel Down
               Me.VerticalScroll.Value = 1
           ElseIf e.Delta > 0 AndAlso Me.VerticalScroll.Value <= 0 Then ' MouseWheel Up
               Me.VerticalScroll.Value = Scroll_Range
           End If

       End If

   End Sub

#End Region

#Region " Methods / Functions "

   ''' <summary>
   ''' Changes the transparency of this panel.
   ''' </summary>
   Private Sub Make_Opaccity(ByVal Percent As Short, ByVal colour As Color)
       Me.BackColor = Color.FromArgb(Percent * 255 / 100, colour.R, colour.G, colour.B)
   End Sub

   ''' <summary>
   ''' Set the VerticalScrollBar Range.
   ''' </summary>
   Private Sub Set_Scroll_Range()
       Scroll_Range = Me.VerticalScroll.Maximum - Me.VerticalScroll.LargeChange + Me.VerticalScroll.SmallChange
   End Sub

#End Region

End Class








Eleкtro

#153
· Ocultar uno o varios procesos en el Task Manager (Si, en el administrador de tareas!)

(Este código es originálmente de un anónimo (La class "TMListViewDelete", no sé ni me voy a molestar en buscar el nombre del autor), modificado por Kub0x, y vuelto a modificar por mí.)

-> http://foro.elhacker.net/net/aporte_ocultar_aplicacion_en_administrador_de_tareas-t359259.0.html

· Añadida compatibilidad para Windows en el lenguaje Inglés y Alemán, y con posibilidad de añadir fácilmente más soporte para otros lenguajes.

· Ahora se puede ocultar varios procesos al mismo tiempo.

· Añadida opción para poder especificar el/los proceso(s) que queremos ocultar.

· Añadida opción para controlar el intervalo de tiempo en el que se procesa la lista del TaskManager (Por defecto 3 ms, para evitar efectos visuales sospechosos en el TaskManager).

· Reorganización de la estructura del código original (Contenía demasiadas regiones para mi gusto y me dificultaba la lectura).

NOTAS: Si se ocultan varios procesos al mismo tiempo, aunque se use 1 ms para el intervalo del timer puede dar esos efectos visuales extraños en la lista del task manager, así que no excederse si se requiere perfección xD.

Lo he testeado en:
WinXP x86 Inglés
WinXP x86 Español
Win7 x86 Inglés
Win7 x64 Español
Win7 x64 Inglés
Win7 x64 Español


En Windows 8 No funciona.
A menos que se utilice el replacamiento NO oficial del TaskManager por el TaskManager de Windows 7 (como hago yo) porque el TaskManager de windows 8 no me gusta)


Ejemplos de uso:

Código (vbnet) [Seleccionar]
Hide_Process_From_TaskManager.Processes_Names = _
{Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide.

Hide_Process_From_TaskManager.Task_Manager_Window_Titles = _
{"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles.

Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval.

Hide_Process_From_TaskManager.Running = True ' Start hidding processes.

Hide_Process_From_TaskManager.Running = False ' Stop hidding processes.


Los créditos son por orden para el creador de la Class TMListViewDelete que ronda por internet,
luego para las modificaciones de Kub0x y por tener la generosidad de haber compartido el código,
y por último para mis modificaciones y compartirlo con vosotros.    :)


Aquí tienen:

Código (vbnet) [Seleccionar]

#Region " Hide Process From TaskManager "

' [ Hide Process From TaskManager ]
'
' // By Elektro H@cker
'
' Examples :
'
' Hide_Process_From_TaskManager.Processes_Names = {Process.GetCurrentProcess.ProcessName, "cmd", "notepad.exe"} ' Processes to hide.
' Hide_Process_From_TaskManager.Task_Manager_Window_Titles = {"Administrador de tareas de Windows", "Windows Task Manager"} ' Support for unknown TaskManager Window Titles.
' Hide_Process_From_TaskManager.Hide_Interval = 3 ' Hidding Interval.
' Hide_Process_From_TaskManager.Running = True ' Start hidding processes.
' Hide_Process_From_TaskManager.Running = False ' Stop hidding processes.

#Region " Hide Process From TaskManager Class "

Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.ComponentModel

Module Hide_Process_From_TaskManager

#Region " API's "

   Private Delegate Function EnumDelegate(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
   Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal Hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
   Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumDelegate, ByVal lParam As Integer) As Integer
   Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
   Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As IntPtr) As Integer
   Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer

   <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
   Private Sub GetClassName(ByVal hWnd As System.IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer)
   End Sub

#End Region

#Region " Variables "

   ''' <summary>
   ''' The processses to hide from TaskManager.
   ''' Caution: The process name is Case-Sensitive.
   ''' </summary>
   Public Processes_Names() As String = {Process.GetCurrentProcess.ProcessName} ' The current process.

   ''' <summary>
   ''' The interval time in ms to hide the process from TaskManager.
   ''' Values greater than "5" can cause bad visual effects in TaskManager processes list.
   ''' </summary>
   Public Hide_Interval As Int32 = 3 ' ms

   ''' <summary>
   ''' The known Window Titles for Task Manager process.
   ''' This is necessary to work properly in all languages.
   ''' Add here your own Task Manager Window Tittle if is not inside.
   ''' Default support: Spanish, English, Deutsch
   ''' </summary>
   Public Task_Manager_Window_Titles() As String = { _
       "Administrador de tareas de Windows", _
       "Windows Task Manager", _
       "Windows Task-Manager", _
   }

   ''' <summary>
   ''' Gets the next process in the Processes_Names array to hide it.
   ''' Don't touch this.
   ''' </summary>
   Public MyProc As String

   Dim t As New Timer
   Dim hwnd As IntPtr
   Dim controls As String
   Dim ProcLV As IntPtr = IntPtr.Zero

   Private Const LVM_FIRST = &H1000
   Private Const LVM_DELETECOLUMN = LVM_FIRST + 28
   Private Const LVM_GETITEMCOUNT = (LVM_FIRST + 4)
   Private Const LVM_SORTITEMS = (LVM_FIRST + 48)
   Private Const LVM_DELETEITEM = (LVM_FIRST + 8)
   Private Const LVM_GETNEXTITEM = (LVM_FIRST + 12)
   Private Const LVM_GETITEM = (LVM_FIRST + 75)

#End Region

#Region " Properties "

   ''' <summary>
   ''' Turns ON/OFF the process hiding.
   ''' </summary>
   Public Property Running() As Boolean
       Get
           If t.Enabled = True Then
               Return True
           Else
               Return False
           End If
       End Get
       Set(ByVal value As Boolean)
           If value = True Then

               If Processes_Names.Length = 0 Then Throw New Exception("Processes_Names Array is empty.")
               If Hide_Interval <= 0 Then Throw New Exception("Hide_Interval value is too low, minimum value: 1")

               MyProc = Processes_Names(0)
               If Not t.Interval = Hide_Interval Then
                   With t
                       AddHandler t.Tick, AddressOf t_Tick
                       .Interval = Hide_Interval
                       .Enabled = True
                       .Start()
                   End With
               Else
                   t.Enabled = True
                   t.Start()
               End If
           Else
               t.Enabled = False
               t.Stop()
               ProcLV = IntPtr.Zero
           End If
       End Set
   End Property

#End Region

#Region " Timer Tick event "

   Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
       If ProcLV = IntPtr.Zero Then

           For Each Title In Task_Manager_Window_Titles
               hwnd = FindWindow(vbNullString, Title)
               If hwnd <> 0 Then
                   EnumChildWindows(hwnd, New EnumDelegate(AddressOf Hide_Process_From_TaskManager.EnumChildWindows), 0)
               End If
           Next

       Else
           GetListView(hwnd, ProcLV)
       End If
   End Sub

#End Region

#Region " Functions "

   ' EnumChildWindows
   Private Function EnumChildWindows(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
       Dim strClassName As String = ObtenerClase(lngHwnd)
       Dim strText As String = ObtenerTextoVentana(lngHwnd)
       If InStr(strClassName, "SysListView32") Then
           GetListView(hwnd, lngHwnd)
           If InStr(strText, "Procesos") Then
               ProcLV = lngHwnd
           End If
       End If
       Dim Classes As String = lngHwnd.ToString & ", " & strClassName & ", " & strText
       Return 1
   End Function

   ' ObtenerClase
   Private Function ObtenerClase(ByVal handle As IntPtr) As String
       Dim strClassName As New System.Text.StringBuilder()
       strClassName.Length = 255
       GetClassName(handle, strClassName, strClassName.Length)
       Return strClassName.ToString
   End Function

   ' ObtenerTextoVentana
   Private Function ObtenerTextoVentana(ByVal handle As IntPtr) As String
       Dim titleText As New System.Text.StringBuilder()
       titleText.Length = GetWindowTextLength(handle) + 1
       GetWindowText(handle, titleText, titleText.Length)
       Return titleText.ToString
   End Function

#End Region

End Module

Module GetItems

#Region " API's "

   ' OpenProcess
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function OpenProcess(ByVal dwDesiredAccess As UInteger, ByVal bInheritHandle As Boolean, ByVal dwProcessId As Integer) As SafeProcessHandle
   End Function

   ' ReadProcessMemoryW
   <DllImport(kernel32, EntryPoint:="ReadProcessMemory", SetLastError:=True, CharSet:=CharSet.Unicode)> _
   Private Function ReadProcessMemoryW(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' ReadProcessMemory
   <DllImport(kernel32, SetLastError:=True, CharSet:=CharSet.Ansi)> _
   Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' ReadProcessMemory
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' ReadProcessMemory
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' ReadProcessMemory
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function ReadProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As IntPtr, ByVal nSize As Integer, ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' SendMessage
   <DllImport(user32, SetLastError:=True)> _
   Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
   End Function

   ' GetHeaderSendMessage
   <DllImport(user32, SetLastError:=True, EntryPoint:="SendMessageA")> _
   Private Function GetHeaderSendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
   End Function

   ' SendMessage
   <DllImport(user32, SetLastError:=True)> _
   Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As StringBuilder) As Integer
   End Function

   ' SendMessage
   <DllImport(user32, SetLastError:=True)> _
   Private Function SendMessage(ByVal hWnd As IntPtr, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
   End Function

   ' VirtualAllocEx
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function VirtualAllocEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal flAllocationType As UInteger, ByVal flProtect As UInteger) As IntPtr
   End Function

   ' VirtualFreeEx
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function VirtualFreeEx(ByVal hProcess As SafeProcessHandle, ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal dwFreeType As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' WriteProcessMemory
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As LV_ITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ' WriteProcessMemory
   <DllImport(kernel32, SetLastError:=True)> _
   Private Function WriteProcessMemory(ByVal hProcess As SafeProcessHandle, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As HDITEM, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

#End Region

#Region " Variables "

   Dim listViewHandle As IntPtr

   Public Const LVM_FIRST As UInteger = &H1000
   Public Const LVM_DELETEITEM As UInteger = (LVM_FIRST + 8)
   Public Const kernel32 As String = "kernel32"
   Public Const user32 As String = "user32"
   Public Const LVM_GETITEMCOUNT As UInteger = &H1004
   Public Const LVM_GETITEMTEXT As UInteger = &H102D
   Public Const LVM_GETHEADER As UInteger = &H101F
   Public Const HDM_GETIEMA As UInteger = &H1203
   Public Const HDM_GETITEMW As UInteger = &H120B
   Public Const HDM_GETITEMCOUNT As UInteger = &H1200
   Public Const HDM_GETUNICODEFORMAT As UInteger = &H2006
   Public Const HDI_TEXT As UInteger = 2
   Public Const MEM_COMMIT As UInteger = &H1000
   Public Const MEM_RELEASE As UInteger = &H8000
   Public Const PAGE_READWRITE As UInteger = 4
   Public Const PROCESS_VM_READ As UInteger = &H10
   Public Const PROCESS_VM_WRITE As UInteger = &H20
   Public Const PROCESS_VM_OPERATION As UInteger = &H8
   Public Const WM_GETTEXT As UInteger = &HD
   Public Const WM_GETTEXTLENGTH As UInteger = &HE

#End Region

#Region " Structures "

   <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
   Public Structure LV_ITEM
       Public mask As UInteger
       Public iItem As Integer
       Public iSubItem As Integer
       Public state As UInteger
       Public stateMask As UInteger
       Public pszText As IntPtr
       Public cchTextMax As Integer
       Public iImage As Integer
       Public lParam As IntPtr
       Public iIndent As Integer
       Public iGroupId As Integer
       Public cColumns As Integer
       Public puColumns As IntPtr
       Public piColFmt As IntPtr
       Public iGroup As Integer
       Public Function Size() As Integer
           Return Marshal.SizeOf(Me)
       End Function
   End Structure

   <StructLayout(LayoutKind.Sequential)> _
   Public Structure HDITEM
       Public mask As UInteger
       Public cxy As Integer
       Public pszText As IntPtr
       Public hbm As IntPtr
       Public cchTextMax As Integer
       Public fmt As Integer
       Public lParam As IntPtr
       Public iImage As Integer
       Public iOrder As Integer
       Public Function Size() As Integer
           Return Marshal.SizeOf(Me)
       End Function
   End Structure

#End Region

#Region " Functions "

   Public Function GetListView(ByVal handle As IntPtr, ByVal lvhandle As IntPtr) As Boolean
       listViewHandle = lvhandle
       Dim hParent As IntPtr = handle

       Dim id As Integer = -1
       Try
           For Each p In Process.GetProcessesByName("taskmgr")
               id = p.Id
           Next
           If id = -1 Then
               Throw New ArgumentException("Can't find process", "processName")
           End If
       Catch : Return False : End Try

       Dim hprocess As SafeProcessHandle = Nothing
       Try
           hprocess = OpenProcess(PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, False, id)

           If hprocess Is Nothing Then
               If Marshal.GetLastWin32Error = 0 Then
                   Throw New System.ComponentModel.Win32Exception
               End If
           End If

           Dim itemCount As Integer = SendMessage(listViewHandle, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero)

           For row As Integer = 0 To itemCount - 1

               Dim lvi As New ListViewItem(GetItem(row, 0, hprocess))

               For Each processname In Processes_Names
                   MyProc = processname
                   If lvi.Text.Contains(Hide_Process_From_TaskManager.MyProc) Then SendMessage(listViewHandle, LVM_DELETEITEM, row, IntPtr.Zero)
               Next

           Next
       Catch : Return False
       Finally
           If hprocess IsNot Nothing Then
               hprocess.Close()
               hprocess.Dispose()
           End If

       End Try
       Return True
   End Function

   Public Function GetItem(ByVal row As Integer, ByVal subitem As Integer, _
                               ByVal hProcess As SafeProcessHandle) As String

       Dim lvitem As New LV_ITEM
       lvitem.cchTextMax = 260
       lvitem.mask = 1
       lvitem.iItem = row
       lvitem.iSubItem = subitem
       Dim pString As IntPtr
       Dim s As New StringBuilder(260)

       Try

           pString = VirtualAllocEx(hProcess, IntPtr.Zero, 260, MEM_COMMIT, PAGE_READWRITE)
           lvitem.pszText = pString
           Dim pLvItem As IntPtr
           Try
               pLvItem = VirtualAllocEx(hProcess, IntPtr.Zero, lvitem.Size, MEM_COMMIT, PAGE_READWRITE)
               Dim boolResult As Boolean = WriteProcessMemory(hProcess, pLvItem, lvitem, lvitem.Size, 0)
               If boolResult = False Then Throw New Win32Exception

               SendMessage(listViewHandle, LVM_GETITEMTEXT, row, pLvItem)
               boolResult = ReadProcessMemory(hProcess, pString, s, 260, 0)
               If boolResult = False Then Throw New Win32Exception
               boolResult = ReadProcessMemory(hProcess, pLvItem, lvitem, Marshal.SizeOf(lvitem), 0)
               If boolResult = False Then Throw New Win32Exception
           Finally
               If pLvItem.Equals(IntPtr.Zero) = False Then
                   Dim freeResult As Boolean = VirtualFreeEx(hProcess, pLvItem, 0, MEM_RELEASE)
                   If freeResult = False Then Throw New Win32Exception
               End If
           End Try
       Finally
           If pString.Equals(IntPtr.Zero) = False Then
               Dim freeResult As Boolean = VirtualFreeEx(hProcess, pString, 0, MEM_RELEASE)
               If freeResult = False Then Throw New Win32Exception
           End If
       End Try

       Return s.ToString

   End Function

   Friend NotInheritable Class SafeProcessHandle : Inherits SafeHandleZeroOrMinusOneIsInvalid

       Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean

       Public Sub New()
           MyBase.New(True)
       End Sub

       Public Sub New(ByVal handle As IntPtr)
           MyBase.New(True)
           MyBase.SetHandle(handle)
       End Sub

       Protected Overrides Function ReleaseHandle() As Boolean
           Return CloseHandle(MyBase.handle)
       End Function

   End Class

#End Region

End Module

#End Region

#End Region








z3nth10n


Interesados hablad por Discord.

Eleкtro

Cita de: Ikillnukes en  6 Junio 2013, 11:02 AMY porque el autor es anónimo? :x

Es anónimo xq me da la gana xD, vi el code del TMListViewDelete posteado por un "guiri" hace mucho tiempo (código que solo funcionaba en XP), lo cierto es que ví la Class en varios sitios buscando una manera de ocultar procesos en el TaskManager, pero no recuerdo el autor, y Kub0x no lo nombra en su code tampoco, así que... anonymous!








Eleкtro

Formatear un número:

Código (vbnet) [Seleccionar]
#Region " Format Number "

    ' [ Format Number Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' MsgBox(Format_Number(50000))     ' Result: 50.000
    ' MsgBox(Format_Number(-12345.33)) ' Result: -12.345,33

    Private Function Format_Number(ByVal Number As Object) As String

        Select Case Number.GetType()
            Case GetType(Int16), GetType(Int32), GetType(Int64)
                Return FormatNumber(Number, TriState.False)
            Case Else
                Return FormatNumber(Number, , TriState.False)
        End Select

    End Function

#End Region







Crear un textbox con una máscara de asteriscos (para introducir passwords):

Código (vbnet) [Seleccionar]
        TextBox1.Text = "Elektro" ' Set a random text.
        TextBox1.PasswordChar = "*" ' The character to use in the mask.
        TextBox1.MaxLength = 8 ' The maximum length of characters inside the textbox.
        MsgBox(TextBox1.Text) ' Result: Elektro







Genera todas las combinaciones posibles de una serie de caracteres:

(Este código es ORO por su sencillez y eficacia):

Código (vbnet) [Seleccionar]
#Region " Permute all combinations of characters"

    ' [ Permute Characters Function ]
    '
    ' Examples :
    ' Dim Permutations As IEnumerable = Permute_Characters("abc", 2)
    ' For Each Permutation As IEnumerable(Of Char) In Permutations : RichTextBox1.Text &= vbNewLine & Permutation.ToArray : Next

    Private Shared Function Permute_Characters(Of T)(list As IEnumerable(Of T), length As Integer) As IEnumerable(Of IEnumerable(Of T))

        If length = 1 Then
            Return list.[Select](Function(x) New T() {x})
        Else
            Return Permute_Characters(list, length - 1).SelectMany(Function(x) list, Function(t1, t2) t1.Concat(New T() {t2}))
        End If

    End Function

#End Region


Resultado:
aa
ab
ac
ba
bb
bc
ca
cb
cc









z3nth10n

Ostia, ese es el code en el que te he ayudado;-)
No verdad, es el siguiente no?

Interesados hablad por Discord.

Eleкtro

Cita de: Ikillnukes en  7 Junio 2013, 07:39 AM
Ostia, ese es el code en el que te he ayudado?  ;-)
No verdad, es el siguiente no?

¿En que parte del código ves algo elevado al cuadrado? xD

Me ayudaste a resolver un problema de una operación matemática en una aplicación donde yo usaba un code, el code o la aplicación es irelevante, pero si, te refieres al code de las combinaciones xD

Salu2








Eleкtro

Modifica el modo de renderizado de IExplorer sobre una aplicación, es decir, el modo de renderizado para un "WebBrowser control"

Código (vbnet) [Seleccionar]
#Region " Set IExplorer Rendering Mode "

    ' [ Set IExplorer Rendering Mode ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10)
    ' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10_DOCTYPE, "Application.exe")

    Public Enum IExplorer_Renders As Int16
        IE10 = 10001         ' Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
        IE10_DOCTYPE = 10000 ' Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
        IE9 = 9999           ' Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
        IE9_DOCTYPE = 9000   ' Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
        IE8 = 8888           ' Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
        IE8_DOCTYPE = 8000   ' Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
        IE7 = 7000           ' Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.
    End Enum

    Private Sub Set_IExplorer_Rendering_Mode(ByVal IExplorer_Render As IExplorer_Renders, _
                                             Optional ByVal Application_Name As String = Nothing)

        If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().ProcessName & ".exe"

        Try
            My.Computer.Registry.SetValue( _
            "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", _
            Application_Name, IExplorer_Render, Microsoft.Win32.RegistryValueKind.DWord)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

#End Region







Bloquear popups en un webbrowser

Código (vbnet) [Seleccionar]
        Private Sub WebBrowser_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
        Handles WebBrowser1.NewWindow
           e.Cancel = True
       End Sub







Bloquear iFrames en un webbrowser

Código (vbnet) [Seleccionar]
    Private Sub WebBrowser_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) _
    Handles WebBrowser1.DocumentCompleted

        For Each element As HtmlElement In CType(sender, WebBrowser).Document.GetElementsByTagName("iframe")
            element.OuterHtml = String.Empty
            Application.DoEvents()
        Next

    End Sub