c#-当UWP进程退出时获取

c#-当UWP进程退出时获取,c#,winforms,C#,Winforms,我想知道我的表单启动到关闭需要多长时间 当前的实现如下所示: var p = new Process(); p.StProcess p = new Process(); p.StartInfo.FileName = EpFile.FullName; //EpFile is FileInfo p.StartInfo.CreateNoWindow = true; p.EnableRaisingEvents = true; p.Exited += (s, e) => { // Some

我想知道我的表单启动到关闭需要多长时间

当前的实现如下所示:

var p = new Process();
p.StProcess p = new Process();
p.StartInfo.FileName = EpFile.FullName; //EpFile is FileInfo
p.StartInfo.CreateNoWindow = true;
p.EnableRaisingEvents = true;

p.Exited += (s, e) =>
{
    // Some Stuff
};

p.Start();

问题是,如果一个普通的可执行文件处理给定的文件,但如果一个UWP(在我的例子中是Movies&TV)处理该文件,那么这种方法可以正常工作。
p.Existed
永远不会启动,使用
p.WaitForExit()
会抛出一个异常,声明该进程与任何东西都没有关联。

在有人找到更好的答案之前,我尝试了一种(工作)解决方法:

    public void Open(FileInfo epFile)
    {
        Process p = new Process();
        p.StartInfo.FileName = epFile.FullName;
        p.StartInfo.CreateNoWindow = true;
        p.EnableRaisingEvents = true;

        p.Start();

        try
        {
            var h = p.Handle; //Needed to know if the process is UWP
            p.Exited += (s, e) =>
            {
                // Code
            };
        }
        catch
        {
            GetLastWindow().WhenClosed(() =>
            {
                // Code
            });
        }
    }

    private Process GetLastWindow()
        => Process.GetProcesses().OrderBy(GetZOrder).Where(x => !string.IsNullOrEmpty(x.MainWindowTitle)).FirstOrDefault();

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr GetWindow(IntPtr hWnd, int nIndex);

    const int GW_HWNDPREV = 3;

    private int GetZOrder(Process p)
    {
        IntPtr hWnd = p.MainWindowHandle;
        var z = 0;
        for (var h = hWnd; h != IntPtr.Zero; h = GetWindow(h, GW_HWNDPREV))
            z++;
        return z;
    }
通过此扩展:

    public delegate void action();

    public static void WhenClosed(this Process process, action action)
    {
        var T = new System.Timers.Timer(1000);
        T.Elapsed += (s, e) =>
        {
            if (IntPtr.Zero == GetWindow(process.MainWindowHandle, GW_HWNDPREV))
            {
                T.Dispose();
                action();
            }
        };
        T.Start();
    }

这回答了你的问题吗@JanMattsson不是真的,您示例的用户正在使用UWP应用程序。我正在开发WinForms应用程序