How to kill a Shell executed process in c#

466 views Asked by At

I want to display a tiff file using shell execute. I am assuming the default app is the photoviewer. My Problem is that when i want to kill the process with photoviewer.Kill() i get an System.InvalidOperationException. When setting a breakpoint after photoViewer.Start() i realised that photoviewer does not conatain an Id. I there a sufficent way to kill it? As it runs via dllhost.exe i do not want to retrun all processes named dllhost and kill them all since i do not know what else is run by dllhost.

Process photoViewer = new Process();
  private void StartProcessUsingShellExecute(string filePath)
        {
            photoViewer.StartInfo = new ProcessStartInfo(filePath);
            photoViewer.StartInfo.UseShellExecute = true;
            photoViewer.Start();
        }

I have another approach without shell execute but this approach seems to have dpi issues. Approach without shell execute

1

There are 1 answers

4
Little-God On

Found a solution, may help anyone with a similar problem. When i looked into the task manager i found that the windows 10 photoviewer runs detached from the application via dllhost. So since i have 4 dllhost processes up and running and just want to close the window. I do:

        private void StartProcessAsShellExecute(string filePath)
    {
        photoViewer.StartInfo = new ProcessStartInfo(filePath);
        photoViewer.StartInfo.UseShellExecute = true;
        photoViewer.Start();

        Process[] processes = Process.GetProcessesByName("dllhost");

        foreach (Process p in processes)
        {
            IntPtr windowHandle = p.MainWindowHandle;
            CloseWindow(windowHandle);
            // do something with windowHandle
        }


        viewerOpen = true;
    }


    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    //I'd double check this constant, just in case
    static uint WM_CLOSE = 0x10;

    public void CloseWindow(IntPtr hWindow)
    {
        SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    }

that closes all dllhost windows (of which i have just 1, the photoviewer)