.NET WinForms - How to listen to events for system LogOff, User Locked, Hibernate Started and System resumed?
I want to listen to events in my windows forms .NET application for the following sy开发者_JAVA技巧stem wide events :
Log Off Lock Windows Hibernate Started Sleep Started System Resumed
Are these possible?
Thanks
You need to look WMI (Windows media instrumentation). You would need to create event watchers for the above mentioned events.
http://msdn.microsoft.com/en-us/library/ms257340%28VS.80%29.aspx
Useful links:
Get Log off event from system
How to create a WMI Event Watcher for a user logoff event?
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/0c1bded8-0cce-4260-bd28-4b4ffce0d27d
http://www.aspfree.com/c/a/VB.NET/WMI-Programming-with-Visual-BasicNET-Trapping-System-Events/1/
As suggested above, you can use the WMI to trap events.
I'm adding some code sample I wrote few years back (hope it will still work since it was written on VS2010 With .Net3.5)
Here's a class that gathers all the events
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
Now, for the listener, I had a Win32 service that ran in the background and did the listening work
Dim Filter As New PowerMessageFilter 'The Standby/Hibernation Filter catch;
Application.AddMessageFilter(Filter)
I sorry that I don't have any references for the sites I've taken the examples from, I guess it was probably from the MSDN links above.
Hope it can help,
Liron
精彩评论