質問

ユーザーがログオフしたときに、温度ファイル、履歴などをクリアするために使用されるアプリケーションを実行しています。では、システムが(C#)にログオフするかどうかをどのようにして知ることができますか?

役に立ちましたか?

解決

にプロパティがあります 環境 シャットダウンプロセスが開始されたかどうかを伝えるクラス:

Environment.HasShutDownStarted

しかし、いくつかのグーグルの後、私はこれがあなたに役立つかもしれないことを知りました:

 using Microsoft.Win32;

 //during init of your application bind to this event  
 SystemEvents.SessionEnding += 
            new SessionEndingEventHandler(SystemEvents_SessionEnding);

 void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
 {
     if (Environment.HasShutdownStarted)
     {
         //Tackle Shutdown
     }
     else
     {
         //Tackle log off
     }
  }

しかし、あなたがTempファイルのみをクリアしたい場合、シャットダウンまたはログオフを区別することはあなたにとって何の結果ではないと思います。

他のヒント

ログオフイベントが特に必要な場合は、次のようにvillageidiotの回答で提供されているコードを変更できます。

using Microsoft.Win32;

//during init of your application bind to this event   
SystemEvents.SessionEnding += 
    new SessionEndingEventHandler(SystemEvents_SessionEnding);

void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) 
{     
    if (e.Reason == SessionEndReasons.Logoff) 
    {  
        // insert your code here
    }
}

WMIを使用して、タイプが0に等しいwin32_computershutdowneventを見ることができます。このイベントの詳細情報を見つけることができます ここ, 、および.netでWMIの使用について詳しく説明します ここ.

あなたが持っている場合 Windowsフォーム, 、あなたは処理できます FormClosing イベント、次にチェックします e.CloseReason 列挙値が等しいかどうかを判断します CloseReason.WindowsShutDown.

private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        // Your code here
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top