The problem here is that you are not really starting a process, but rather passing a file path to the Windows Shell (explorer.exe
) to handle. The shell figures out how to open the file and it starts the process.
When this happens your code doesn't get the process id back, so it doesn't know which process to kill.
What you should do, is find the default application for the file and then start that application explicitly (rather than letting the shell figure it out).
The most compact way I can think of to find the default application for a file is to use the Win32 API FindExecutable()
.
Things are complicated a little when the default application is contained within a dll. This is the case with the default Windows photo viewer (C:\Program Files (x86)\Windows Photo Viewer\PhotoViewer.dll
). Since it is not a exe
you cannot start it directly, however the application can be started using rundll32
.
This should work for you:
[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();
}
This code demonstrates the concept, but if you want to cater for more default applications with unusual argument formats (as shown by photoviewer.dll
), you should search the registry yourself or use a third party library to find the correct command line to use.
For example,