.NET WinForms - 如何监听系统LogOff,用户锁定,Hibernate启动和系统恢复的事件?

时间:2010-02-11 05:36:29

标签: c# .net vb.net winforms events

我想在我的Windows窗体.NET应用程序中监听以下系统范围事件中的事件:

注销 锁定Windows Hibernate开始了 睡眠开始 系统已恢复

这些可能吗?

由于

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)

如上所述,您可以使用WMI捕获事件 我正在添加一些我几年前写的代码示例(希望它仍然有效,因为它是在VS2010上用.Net3.5编写的)

这是一个收集所有活动的课程

Imports Microsoft.Win32
Imports System.Windows.Forms

Public Class PowerMessageFilter
    Implements IMessageFilter
    Const WM_POWERBROADCAST As Integer = &H218
    Const PBT_APMSUSPEND As Integer = &H4
    Const PBT_APMSTANDBY As Integer = &H5
    Const PBT_APMRESUMESUSPEND As Integer = &H7
    Const PBT_APMRESUMESTANDBY As Integer = &H8

   Protected Sub reportpowerchange(ByVal reason As Integer)
       Dim report As String = String.Empty
       Select Case (reason)
           Case PBT_APMSUSPEND
               report = "system is suspending operation "
               suspend_service()
               Exit Select
           Case PBT_APMSTANDBY
               report = "system is standing by "
               suspend_service()
               Exit Select
           Case PBT_APMRESUMESUSPEND
               report = "operation resuming after suspension."
               suspend_service()
               Exit Select
           Case PBT_APMRESUMESTANDBY
               report = "operation resuming after stand by."
               suspend_service()
           Exit Select
       End Select
   End Sub

   Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
       If WM_POWERBROADCAST = m.Msg Then
           Console.Out.WriteLine("Power Broadcast recieved.")
           Dim reason As Integer = m.WParam.ToInt32()
           reportpowerchange(reason)
       End If
       Return False
   End Function

   Private Sub suspend_service()
      ' Your suspend code
   End Sub
End Class

现在,对于监听器,我有一个在后台运行的Win32服务并完成了监听工作

Dim Filter As New PowerMessageFilter 'The Standby/Hibernation Filter catch;
Application.AddMessageFilter(Filter)

对不起,我没有参考我从中获取示例的网站,我想这可能来自上面的MSDN链接。

希望它可以提供帮助,
Liron