1. Startseite
  2. Wissensdatenbank
  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!”.

Aktualisiert am Juli 3, 2019

War dieser Beitrag hilfreich?

Verwandte Artikel

Nicht die Lösung nach der du gesucht hast?
Klicke hier unten um ein Support-Ticket zu erstellen.
Visist our Forum!

Kommentare

  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

Hinterlasse einen Kommentar

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.