Identify if a particular program is the focus by C #

1

I'm 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 will open internet explorer, and navigate a site making insertions in the elements of it.

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

    
asked by anonymous 25.08.2016 / 16:42

1 answer

4

Diego, to fulfill this 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 the IE handler on Windows. This information is obtained by searching for hWnd.

Once you've done this, you should call the GetActiveWindow function of user32.dll to verify that the hWnd obtained by the function is the same as the IE that you already have. If it is the same IE is the active window.

Here is some 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: Although there is another IE open only what was opened by your application will be identified this way.

I hope I have succeeded in helping you.

    
25.08.2016 / 18:56