1. Home
  2. Knowledge Base
  3. Visual Studio
  4. CSharp
  5. Bring an application to front with CSharp

Bring an application to front with CSharp

Focus Application

This code example will show you how to bring a running app to front and set the focus on it while using a C# console application. Just copy the code in your existing project and replace the application name with the one you want to focues.

Important

It doesn’t work if the application is minimized!

Code

[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace AppToFront
{
class Program
{

[DllImport(“USER32.DLL”)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

/// Lists all processes running.
/// (Debug)
///

private static void listProcess()
{
List p = new List();
foreach (Process process in Process.GetProcesses())
{
p.Add(process);
Console.WriteLine(process.ProcessName);
}
}

static void Main(string[] args)
{
//Checks if application is running
try
{
Process process = Process.GetProcessesByName(“chrome”)[0];
if (process != null)
{
process.WaitForInputIdle();
IntPtr s = process.MainWindowHandle;
SetForegroundWindow(s);

Console.Write(“Proccess found: ” + process.ToString());
}
//listProcess();
}
catch (Exception exc)
{
Console.WriteLine(“ERROR: Application is not running!\nException: ” + exc.Message);
Console.ReadKey();
return;
}

}

}
}
[/csharp]

Get application name

Just run the task manager. The process name is the name in the first row without the extension.

For instance: chrome.exe -> chrome

Insert the name in your code and run the project. If the application is running, it will bring back the focus to it. If not, the code will say “Application not running!”.

Updated on July 3, 2019
Was this article helpful?

Related Articles

Not the solution you were looking for?
Click the link below to submit a support ticket
Visist our Forum!

Comments

  1. Am I missing something? As far as I can tell the following function is not being used:

    public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);

    And the following line refers to an inexistent object “spectrum”:

    IntPtr processFoundWindow = spectrum.MainWindowHandle;

    1. Hi,
      Yes you are absolutely right. I took the example out of my project, so I missed to remove some unneeded stuff.

      I‘ll check the code snippet again and remove the unneeded lines of code.

      Thanks for letting me know 🙂

      Best Andy

    2. Hi Cesar,
      I just cleaned the code snippet above.
      Thank you again for letting me know about this!

      Best,
      Andy

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.