Identify if a particular program is the focus by C#

Asked

Viewed 526 times

1

I am developing an application, which will insert data into another program (using Sendkeys, etc).

For this I need to know if the program is what is in focus.

For example: The application open the internet explorer, and browse a website making insertions in the elements of it.

So how would I know if Internet Explorer is the program that is with Focus?

1 answer

4


Diego, to accomplish such a task you will need to interact with the Operating System API, in this case Windows.

When you start a new instance of Internet Explorer you will need to get Handler (identifier) from IE on Windows. This information is obtained by searching for hwnd.

Once this is done, you should call user32.dll’s Getactivewindow function to check if the hwnd obtained by the function is the same as the one you already got from IE. If the same IE is the active window.

Follow code to exemplify what I said above:

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

namespace ManipulaApp
{
    class Program
    {        
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        static void Main(string[] args)
        {
            var ie = Process.Start("iexplore.exe");

            while (true)
            {
                IntPtr hWnd = GetForegroundWindow();

                if (hWnd == ie.MainWindowHandle)
                {
                    Console.WriteLine("IE ativo.");
                }

                Thread.Sleep(1000);
            }
        }
    }
}

Note: Even if there is another open EI only what was opened by its application will be identified in this way.

I hope I’ve been able to help you.

  • If it’s not the active window, there’s a way I can bring it forward?

  • 1

    Yes, the Windows API allows you to manipulate windows almost completely through hwnd. The appropriate function to focus a window through Handler is "Setforegroundwindow(Intptr hwnd)". You should include it in the same way I put Getforegroundwindow in the sample code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.