在默认图像查看器中打开和关闭图像

use*_*562 0 c# process

我正在尝试创建一个在默认图像查看器中打开图像的简短方法,并在time几毫秒后关闭它.

现在它看起来像这样:

    public static async void OpenImage(string path, int time)
    {
        var process = new Process();
        process.StartInfo.FileName = path;
        process.Start();
        await Task.Delay(time);
        process.Kill()
        process.Close()
    }
Run Code Online (Sandbox Code Playgroud)

我可以看到图像,但随后process.Kill()抛出InvalidOperationException"没有进程与此对象相关联".

我错过了什么或者还有其他办法吗?


更新:

现在也测试了这个:

    public static async void OpenImage(string path, int time)
    {
        var process = Process.Start(path)
        await Task.Delay(time);
        process.Kill()
        process.Close()
    }
Run Code Online (Sandbox Code Playgroud)

但后来Process.Start()回归null.所以也许我必须.exe直接打电话给faljbour评论?

Chr*_*ill 5

这里的问题是你并没有真正开始一个进程,而是将文件路径传递给Windows Shell(explorer.exe)来处理.外壳数字如何打开该文件,启动过程.

当发生这种情况时,您的代码不会返回进程ID,因此它不知道要杀死哪个进程.

您应该做的是找到该文件的默认应用程序,然后显式启动该应用程序(而不是让shell弄明白).

我能想到的找到文件默认应用程序的最紧凑的方法是使用Win32 API FindExecutable().


当默认应用程序包含在dll中时,事情会变得复杂一些.这是默认Windows照片查看器(C:\Program Files (x86)\Windows Photo Viewer\PhotoViewer.dll)的情况.因为它不是exe你不能直接启动它,但是应用程序可以开始使用rundll32.


这应该适合你:

[DllImport("shell32.dll")]
static extern int FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult);

public static async void OpenImage(string imagePath, int time)
{
    var exePathReturnValue = new StringBuilder();
    FindExecutable(Path.GetFileName(imagePath), Path.GetDirectoryName(imagePath), exePathReturnValue);
    var exePath = exePathReturnValue.ToString();
    var arguments = "\"" + imagePath + "\"";

    // Handle cases where the default application is photoviewer.dll.
    if (Path.GetFileName(exePath).Equals("photoviewer.dll", StringComparison.InvariantCultureIgnoreCase))
    {
        arguments = "\"" + exePath + "\", ImageView_Fullscreen " + imagePath;
        exePath = "rundll32";
    }

    var process = new Process();
    process.StartInfo.FileName = exePath;
    process.StartInfo.Arguments = arguments;

    process.Start();

    await Task.Delay(time);

    process.Kill();
    process.Close();
}
Run Code Online (Sandbox Code Playgroud)

此代码演示了该概念,但如果您希望使用不常见的参数格式(如图所示photoviewer.dll)来处理更多默认应用程序,则应自行搜索注册表或使用第三方库查找要使用的正确命令行.

例如,