4

ユーザーがセッションを閉じたときに、プログラムでいくつかのことを実行しようとしています。

コードは次のとおりです。

using System;
using System.Diagnostics;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Threading;

public class MyProgram
{
    static Process myProcess = null;
    public MyProgram()
    {
    }

    // Entry point
    static void Main(string[] args)
    {
        SystemEvents.SessionEnding += SessionEndingEvent; // Does not trigger inmediately, only fires after "myProcess" gets closed/killed 
        myProcess = CreateProcess("notepad.exe", null);
        myProcess.Exited += pr_Exited; // Invoked at "myProcess" close (works ok)
        try
        {
            myProcess.Start();
        }
        catch (Exception e2) { MessageBox.Show(e2.ToString()); }

        System.Windows.Forms.Application.Run(); // Aplication loop
    }

    static void SessionEndingEvent(object sender, EventArgs e)
    {
        MessageBox.Show("Session ending fired!");
    }

    static void pr_Exited(object sender, EventArgs e)
    {
        MessageBox.Show("Process Closed");
    }

    static Process CreateProcess(String path, String WorkingDirPath)
    {
        Process proceso = new Process();
        proceso.StartInfo.FileName = path;
        proceso.StartInfo.WorkingDirectory = WorkingDirPath;
        proceso.EnableRaisingEvents = true;
        return proceso;
    }
}

アプリケーションを開くと、メモ帳が開きます。セッションを閉じると:

  • メモ帳で何も変更していない場合 (終了時に確認する必要がないため)、SO はメモ帳を閉じ、SessionEnding イベントが発生し (この場合は問題ありません)、後で Process.Exited します。

  • メモ帳で何かを変更した場合、メモ帳は保存するかどうかを尋ね、メモ帳プロセスが閉じられるまでイベントは発生しません。

つまり、プログラムは、開始したプロセスが実行されていない場合にのみ通知を受け取ります。プロセスが開いているかどうかに関係なく、どのような状況でもイベントが呼び出されるようにしたいと考えています。

前もって感謝します。

4

0 に答える 0