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

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Clase que Captura el Inicio y Cierre de Procesos [Aporte] [WMI]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Clase que Captura el Inicio y Cierre de Procesos [Aporte] [WMI]  (Leído 1,910 veces)
Keyen Night


Desconectado Desconectado

Mensajes: 496


Nothing


Ver Perfil
Clase que Captura el Inicio y Cierre de Procesos [Aporte] [WMI]
« 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.


« Última modificación: 29 Septiembre 2011, 02:30 am por Keyen Night » En línea

La Fé Mueve Montañas...
                                    ...De Dinero

La programación es más que un trabajo es más que un hobby es una pasión...
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Duda: MSN + saber inicio y cierre de sesion
Programación Visual Basic
Anteros 5 2,552 Último mensaje 1 Mayo 2008, 20:55 pm
por Anteros
[Aporte by 4ng3r] Ver Procesos de Windows « 1 2 »
Java
AFelipeTrujillo 14 11,403 Último mensaje 25 Febrero 2010, 21:37 pm
por Debci
[Aporte] ....::: Clase Arrays del paquete java.util :::...
Java
horny3 0 3,901 Último mensaje 24 Septiembre 2012, 06:43 am
por horny3
[Aporte] ....::: Clase Object del paquete java.lang :::...
Java
horny3 0 2,594 Último mensaje 1 Octubre 2012, 02:58 am
por horny3
[Aporte] Captura de Pantalla en C#
.NET (C#, VB.NET, ASP)
samuelhm 1 1,817 Último mensaje 30 Mayo 2014, 13:13 pm
por samuelhm
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines