1

I can't figure out why it is not working ?

static void ActivateApp(string processName)
{
    Process[] p = Process.GetProcessesByName(processName);

    // Activate the first application we find with this name
    if (p.Any()) SetForegroundWindow(p[0].MainWindowHandle);
    else
    {
        Console.WriteLine("Something wrong");
    }
}


    [STAThread]
    static void Main(string[] args)
    {
        ActivateApp("Acrobat.exe");
    }

Output :

Something is wrong

But I'm sure that Acrobat.exe exist.

Ydhem
  • 928
  • 2
  • 14
  • 36
  • 2
    Change `Acrobat.exe` to just `Acrobat`. – User 12345678 Apr 18 '13 at 09:40
  • What do you mean by its not working? Exception? "Something wrong" in console? Please elaborate. – jordanhill123 Apr 18 '13 at 09:41
  • Thank you @ByteBlast, jordanhill123, yes there was "Something wrong", now it is gone, but my window still won't show up, maybe I'm wrong, but this method is supposed to put the selected process' Windows to the top of all others Windows, right ? – Ydhem Apr 18 '13 at 09:43
  • Do you mean, it doesn't say "Something wrong" now, but the window still won't go to the foreground? (I just undeleted my answer below which I deleted when I thought ByteBlast had the right answer) – Matthew Watson Apr 18 '13 at 09:45
  • Oh, just saw, Matthew Watson's answer, I think I'm wrong, should I delete this question ? – Ydhem Apr 18 '13 at 09:46
  • @Meds Nope. If his answer suffices you should mark it as the accepted answer. – User 12345678 Apr 18 '13 at 09:47

1 Answers1

2

There are some weird rules for whether SetForegroundWindow() will actually work.

At least one of the following must be true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked.
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

Is this the case?

See the MSDN documentation for full details.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276