Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Keyen Night en 28 Septiembre 2011, 22:20 pm



Título: Clase que Captura el Inicio y Cierre de Procesos [Aporte] [WMI]
Publicado por: Keyen Night en 28 Septiembre 2011, 22:20 pm
Bueno decidí compartir este código lo acabo de hacer sirve para capturar los procesos que se han iniciado y los que se han terminado, me parece bastante útil, utiliza como base WMI solo que en la clase está mucho más administrado y más cómodo de utilizar. Deben liberar el objeto con .Dispose cuando vayan a cerrar la aplicación que use la clase o lanza un error.

Código
  1. Public Class ProcessWatcher
  2.  
  3.    Partial Class StoppedProcess
  4.  
  5.        Public Sub New(ByVal PropertiesDictionary As Dictionary(Of String, Object))
  6.  
  7.            Dim AllFlags As BindingFlags = &H107FF7F
  8.            Dim Field As FieldInfo = Nothing
  9.  
  10.            For Each FieldProperty As KeyValuePair(Of String, Object) In PropertiesDictionary
  11.                Field = Me.GetType.GetField("_" & FieldProperty.Key, AllFlags)
  12.                If Field IsNot Nothing Then
  13.                    Field.SetValue(Me, FieldProperty.Value)
  14.                End If
  15.            Next
  16.  
  17.        End Sub
  18.  
  19. #Region " Properties "
  20.  
  21.        Private _ProcessName As String
  22.        Public ReadOnly Property ProcessName() As String
  23.            Get
  24.                Return _ProcessName
  25.            End Get
  26.        End Property
  27.  
  28.        Private _ProcessID As UInteger
  29.        Public ReadOnly Property Id() As UInteger
  30.            Get
  31.                Return _ProcessID
  32.            End Get
  33.        End Property
  34.  
  35.        Private _ParentProcessID As UInteger
  36.        Public ReadOnly Property ParentProcessId() As UInteger
  37.            Get
  38.                Return _ParentProcessID
  39.            End Get
  40.        End Property
  41.  
  42.        Private _ExitStatus As UInteger
  43.        Public ReadOnly Property ExitCode() As UInteger
  44.            Get
  45.                Return _ExitStatus
  46.                Process.GetCurrentProcess()
  47.            End Get
  48.        End Property
  49.  
  50.        Private _SessionID As UInteger
  51.        Public ReadOnly Property SessionId() As UInteger
  52.            Get
  53.                Return _SessionID
  54.            End Get
  55.        End Property
  56.  
  57. #End Region
  58.  
  59.    End Class
  60.  
  61.    Public Event Started(ByVal e As Process)
  62.    Public Event Stopped(ByVal e As StoppedProcess)
  63.  
  64.    Private ProcessQueryEvent_Start As WqlEventQuery
  65.    Private ProcessWatcher_Start As ManagementEventWatcher
  66.  
  67.    Private ProcessQueryEvent_Stop As WqlEventQuery
  68.    Private ProcessWatcher_Stop As ManagementEventWatcher
  69.  
  70.    Private WatcherEnabled As Boolean = False
  71.  
  72.    Public Sub New(Optional ByVal AutoStart As Boolean = True, _
  73.                   Optional ByVal SetAsFalseCheckForIllegalCrossThreadCalls As Boolean = False, _
  74.                   Optional ByVal Frequency As Double = 1000)
  75.  
  76.        ProcessQueryEvent_Start = New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")
  77.        ProcessWatcher_Start = New ManagementEventWatcher(ProcessQueryEvent_Start)
  78.  
  79.        ProcessQueryEvent_Stop = New WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")
  80.        ProcessWatcher_Stop = New ManagementEventWatcher(ProcessQueryEvent_Stop)
  81.  
  82.        AddHandler ProcessWatcher_Start.EventArrived, AddressOf StartEvent
  83.        AddHandler ProcessWatcher_Stop.EventArrived, AddressOf StopEvent
  84.  
  85.        ProcessQueryEvent_Start.WithinInterval = TimeSpan.FromMilliseconds(Frequency)
  86.        ProcessQueryEvent_Stop.WithinInterval = TimeSpan.FromMilliseconds(Frequency)
  87.  
  88.        Control.CheckForIllegalCrossThreadCalls = Not SetAsFalseCheckForIllegalCrossThreadCalls
  89.  
  90.        If AutoStart Then
  91.            Enabled = True
  92.        End If
  93.  
  94.    End Sub
  95.  
  96.    Private Sub StopEvent(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
  97.  
  98.        Dim RawDictionary As New Dictionary(Of String, Object)
  99.  
  100.        For Each ProcessProperty As PropertyData In e.NewEvent.Properties
  101.            If Not ProcessProperty.IsArray Then
  102.                RawDictionary.Add(ProcessProperty.Name, e.NewEvent(ProcessProperty.Name))
  103.            End If
  104.        Next
  105.  
  106.        RaiseEvent Stopped(New StoppedProcess(RawDictionary))
  107.  
  108.    End Sub
  109.  
  110.    Private Sub StartEvent(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
  111.        RaiseEvent Started(Process.GetProcessById(e.NewEvent("ProcessID")))
  112.    End Sub
  113.  
  114.    Public Property Frequency() As Double
  115.        Get
  116.            Return ProcessQueryEvent_Start.WithinInterval.TotalMilliseconds
  117.        End Get
  118.        Set(ByVal value As Double)
  119.            If value < 0 Then
  120.                Throw New ArgumentException("value")
  121.            Else
  122.                ProcessQueryEvent_Start.WithinInterval = TimeSpan.FromMilliseconds(value)
  123.                ProcessQueryEvent_Stop.WithinInterval = TimeSpan.FromMilliseconds(value)
  124.            End If
  125.        End Set
  126.    End Property
  127.  
  128.    Public Property Enabled() As Boolean
  129.        Get
  130.            Return WatcherEnabled
  131.        End Get
  132.        Set(ByVal value As Boolean)
  133.            If WatcherEnabled Then
  134.                ProcessWatcher_Start.Stop()
  135.                ProcessWatcher_Stop.Stop()
  136.            Else
  137.                ProcessWatcher_Start.Start()
  138.                ProcessWatcher_Stop.Start()
  139.            End If
  140.            WatcherEnabled = Not WatcherEnabled
  141.        End Set
  142.    End Property
  143.  
  144.    Public Sub Dispose()
  145.  
  146.        If Enabled Then
  147.            ProcessWatcher_Start.Stop()
  148.            ProcessWatcher_Stop.Stop()
  149.        End If
  150.  
  151.        ProcessWatcher_Start.Dispose()
  152.        ProcessWatcher_Stop.Dispose()
  153.  
  154.    End Sub
  155.  
  156. End Class
  157.  

Un poco largo el código :-X

Los parametros del constructor son:

AutoStart, Boolean, True para iniciar automáticamente con la construcción y False para iniciar después mediante la propiedad Enabled.

SetAsFalseCheckForIllegalCrossThreadCalls
, Boolean, True para desactivar la detección de llamadas de controles fuera del MainThread y false para activar.

Frequency, Double, el intervalo en milisegundos en cuál se va a chequear.