Alex
Alex

Reputation: 987

Duplicate process (strange issue)

I am trying to prevent opening help file more than once. This is the method I am using:

    public void openHelp()
    {
        int count = 0;
        string helpPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\MyApp\Help\eHelp.chm";

        System.Diagnostics.Process[] helpProcs = System.Diagnostics.Process.GetProcesses();
        foreach (System.Diagnostics.Process proc in helpProcs)
        {
            if (proc.MainWindowTitle == "Sample App Help")
            {
                count++;
            }
        }

        if (count == 0)
        {
            System.Diagnostics.Process.Start(helpPath);
        }
        else
        {
        }
    }

The idea is, if you find the process with the same MainWindowTitle, then do not start a new one. However, this is not reliable. In some cases it still starts the process, even though one is already running. Is there an issue with a logic?

Thank you.

P.S. Of course the MainWindowTitle is "Sample App Help", at least that is what I see while debugging.

Update: Issue only occurs when user has minimised help file. So I suspect something happens in the system and I need to check something. Any suggestions?

Upvotes: 0

Views: 1025

Answers (1)

Clemens
Clemens

Reputation: 128061

The Remarks section in Process.MainWindowTitle contains the following note:

The main window is the window that currently has the focus; note that this might not be the primary window for the process. You must use the Refresh method to refresh the Process object to get the current main window handle if it has changed.

Could this perhaps be the cause of your problem?

What about keeping the process id of a newly started help viewer and before starting another one, just check if the old one is still alive.

int id = ...

try
{
    var proc = Process.GetProcessById(id);
}
catch
{
    // no process running with that id
}

Upvotes: 4

Related Questions