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.
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!”.
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;
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
Hi Cesar,
I just cleaned the code snippet above.
Thank you again for letting me know about this!
Best,
Andy