SystemEvents.SessionEnding在Process(之前打开)关闭之前不会被触发

时间:2012-10-23 17:15:55

标签: c# multithreading events

当用户关闭会话时,我正试图在程序中做一些事情。

以下是代码:

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稍后。

  • 如果我在记事本中更改了某些内容,记事本会问我是否愿意 保存,直到记事本过程关闭才会触发我的事件。

换句话说,我的程序仅在我启动的进程未运行时才收到通知。无论过程是否开放,我都想在任何情况下调用我的事件。

提前致谢。

0 个答案:

没有答案