-1

I use this code to check whether my program is already open:

string RunningProcess = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(RunningProcess);

if (processes.Length > 1)
{ return true; }

It would, if the program is open, bring it to the floor and show it. How can I do? Thank you.

daniel59
  • 906
  • 2
  • 14
  • 31
Alex
  • 15
  • 1
  • 7
  • 1
    check this http://stackoverflow.com/questions/2315561/correct-way-in-net-to-switch-the-focus-to-another-application –  May 09 '16 at 07:09

1 Answers1

2

You have to import the following method:

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);

Then you can call this method this way:

ShowWindow(process.MainWindowHandle, 0);//Hide
ShowWindow(process.MainWindowHandle, 1);//Show

NOTE: The window can just be shown if it is minimized. It won't show it if it is in the background of an other window.

If you want to show a window that is in the background of an other one you have to import this method:

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

Then call it in the same way as ShowWindow:

SetForegroundWindow(process.MainWindowHandle);

NOTE: You can just set the foreground window if it is not minimized.

You can also combine both methods with IsIconic to call the right method:

[DllImport("user32.dll")]
static extern bool IsIconic(IntPtr hWnd);//Returns false if the window is minimized

The full code to show the mainwindow:

static void GotoProcess(Process process)
{
    if (IsIconic(process.MainWindowHandle))
    {
        ShowWindow(process.MainWindowHandle, 1);
    }
    else
    {
        SetForegroundWindow(process.MainWindowHandle);
    }
}
daniel59
  • 906
  • 2
  • 14
  • 31
  • I tried but it does not work. This is my code: System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess(); ShowWindow(process.MainWindowHandle, 1); – Alex May 09 '16 at 08:55
  • I am very sorry, but I tried it and it does not work, always opens a new app. – Alex May 09 '16 at 17:29
  • If you want to avoid opening a new app, you can use `GotoProcess` to go to your already opened app and then close the new the app. You have to check this when you open a new app. – daniel59 May 17 '16 at 12:32