SystemEvents.SessionEnding イベント
アセンブリ: System (system.dll 内)

public: static event SessionEndingEventHandler^ SessionEnding { void add (SessionEndingEventHandler^ value); void remove (SessionEndingEventHandler^ value); }


これはキャンセル可能なイベントです。Cancel プロパティを false に設定すると、セッションを継続して実行するように要求できます。セッションの継続を要求しても、セッションが絶対に終了しないというわけではありません。
Windows フォームでシステムのログオフまたは再起動を検出するために SessionEnding を使用している場合、このイベントの前に Closing イベントが発生するかどうかを確実に知ることはできません。
Closing が発生する前に何らかの特別な処理を実行するには、Closing の前に SessionEnding を発生させる必要があります。これを行うには、WndProc 関数をオーバーライドすることによって、フォームで WM_QUERYENDSESSION をトラップする必要があります。
![]() |
---|
これは静的イベントなので、アプリケーションが破棄されるときにイベント ハンドラをデタッチしないと、メモリ リークが発生します。 |

確実な方法で WndProc 関数をオーバーライドすることにより、フォーム内で WM_QUERYENDSESSION をトラップする方法を次のコード例に示します。
Private Shared WM_QUERYENDSESSION As Integer = &H11 Private Shared systemShutdown As Boolean = False Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) If m.Msg = WM_QUERYENDSESSION Then MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot") systemShutdown = True End If ' If this is WM_QUERYENDSESSION, the closing event should be raised in the base WndProc. MyBase.WndProc(m) End Sub 'WndProc Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing If (systemShutdown) Then ' Reset the variable because the user might cancel the shutdown. systemShutdown = False If (DialogResult.Yes = _ MessageBox.Show("My application", "Do you want to save your work before logging off?", MessageBoxButtons.YesNo)) Then e.Cancel = True Else e.Cancel = False End If End If End Sub
private static int WM_QUERYENDSESSION = 0x11; private static bool systemShutdown = false; protected override void WndProc(ref System.Windows.Forms.Message m) { if (m.Msg==WM_QUERYENDSESSION) { MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot"); systemShutdown = true; } // If this is WM_QUERYENDSESSION, the closing event should be // raised in the base WndProc. base.WndProc(m); } //WndProc private void Form1_Closing( System.Object sender, System.ComponentModel.CancelEventArgs e) { if (systemShutdown) // Reset the variable because the user might cancel the // shutdown. { systemShutdown = false; if (DialogResult.Yes==MessageBox.Show("My application", "Do you want to save your work before logging off?", MessageBoxButtons.YesNo)) { e.Cancel = true; } else { e.Cancel = false; } } }

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- SystemEvents.SessionEnding イベントのページへのリンク