0

Good morning,

I'm trying to figure out how to put the focus on Google Chrome. That is to say to make as a click on the software in the taskbar (already open).

Thank you for helping me to put the focus on Google Chrome.

ZoneArisK
  • 15
  • 1
  • https://stackoverflow.com/questions/2315561/correct-way-in-net-to-switch-the-focus-to-another-application – Oguz Ozgul Apr 03 '20 at 17:40
  • Did you search for it first? Because this is the first search engine hit. – Oguz Ozgul Apr 03 '20 at 17:41
  • Sorry. You are right. Unfortunately this is not a very easy task and is not provided directly by the .Net Framework. You have to make a windows API call. But I think what that link shows is not that hard to implement. – Oguz Ozgul Apr 03 '20 at 18:15

1 Answers1

0

You can use the following function to bring chrome to front and to focus it.

The code uses 2 windows API calls because what you need is not directly provided by the .Net framework.

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

public class Program
{
    [DllImport("user32.dll")]
    [return: MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
    private static extern bool ShowWindow(IntPtr hWnd, int flags);

    [DllImport("user32.dll")]
    public static extern int SetForegroundWindow(IntPtr hwnd);

    private static bool FocusChromeWindow()
    {
        foreach (Process chrome in Process.GetProcessesByName("chrome"))
        {
            // In case the process did not reveal a main window handle
            // try to restore it in case it is hidden 
            if (chrome.MainWindowHandle == IntPtr.Zero)
            {
                ShowWindow(chrome.Handle, 9); // 9 = Restore
            }
            // If main window handle is still zero,
            // this chrome process is one of the background
            // workers chrome starts. Skip it.
            if (chrome.MainWindowHandle != IntPtr.Zero)
            {
                SetForegroundWindow(chrome.MainWindowHandle);
                return true;
            }
        }
        return false;
    }

    static void Main(string[] args)
    {
        FocusChromeWindow();
        Console.ReadLine();
    }
}
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26