Public Class App Public Shared Sub Main() ' 关联事件 AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf OnSystemShutdown ' 必须有消息循环情况下,事件才会被触发 Application.Run(New Form1) End Sub ''' <summary> ''' 事件过程,将在主线程上被调用 ''' </summary> Private Shared Sub OnSystemShutdown(s As Object, e As Microsoft.Win32.SessionEndingEventArgs) Select Case e.Reason Case Microsoft.Win32.SessionEndReasons.Logoff MessageBox.Show("用户请求注销") Case Microsoft.Win32.SessionEndReasons.SystemShutdown MessageBox.Show("用户请求关机或重启") End Select ' 如需阻止用户注销/关机/重启,并且保持程序继续运行,需设置e.Cancel为True并立即Return 'e.Cancel = True ' 如果允许用户注销/关机/重启,直接在此过程中处理好数据保存等事宜 'SaveUserData() End Sub End Class