C# - 获取UWP进程退出时间

3

我希望了解提交表单后,流程关闭所需的时间。

当前的实现方式如下:

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() 会抛出一个异常,指出该进程未与任何东西关联。

这个回答解决了你的问题吗?https://dev59.com/apfga4cB1Zd3GeqPBdEh - Jan Mattsson
@JanMattsson 并不是很相关,你的例子中的用户正在处理一个 UWP 应用程序。而我正在处理一个 WinForms 应用程序。 - J. Hajjar
1个回答

0

在找到更好的答案之前,我尝试了一个(可行的)解决方法:

    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();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接