Search code examples
c#winapiprocesskill

Closing a minimized/iconized process from C#


Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window.

The other requirement that I have is that the application be closed not killed. I need it to write it's memory buffers to disk - and killing it causes data loss.

Here's what I tried so far:

        foreach (Process proc in Process.GetProcesses())
        {
            if (proc.ProcessName.ToLower().StartsWith("myapp"))
            {
                if (proc.MainWindowHandle.ToInt32() != 0)
                {
                    proc.CloseMainWindow();
                    proc.Close();
                    //proc.Kill();  <--- not good!
                }
            }
        }

I've added the if clause, after discovering that MainWindowHandle == 0 when the window was minimized. Removing the if doesn't help. Neither the CloseMainWindow() nor the Close() work. The Kill() does, but as mentioned above - it's not what I need.

Any idea would be accepted, including the use of arcane Win32 API functions :)


Solution

  • Here are some answers and clarifications:

    rpetrich: Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0.

    Roger: Yes, I did mean the taskbar notification area - thanks for the clarification. I NEED to call PostQuitMessage. I just don't know how, given a processs only, and not a Window.

    Craig: I'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'.

    Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it.

    Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down.

    Hope that clarifies my situation, and again, thanks everyone who's trying to help!