Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see if my form is currently on top of the other ones?

Basically, how do I tell if my program is layered above all the other ones?

like image 283
Jon Avatar asked Aug 21 '12 04:08

Jon


2 Answers

A fairly simple way is to P/Invoke GetForegroundWindow() and compare the HWND returned to the application's form.Handle property.

using System;
using System.Runtime.InteropServices;

namespace MyNamespace
{
    class GFW
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        public bool IsActive(IntPtr handle)
        {
            IntPtr activeHandle = GetForegroundWindow();
            return (activeHandle == handle);
        }
    }
}

Then, from your form:

if (MyNamespace.GFW.IsActive(this.Handle))
{
  // Do whatever.
}
like image 50
Euric Avatar answered Oct 05 '22 03:10

Euric


You can use:

if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle)
{
     //do stuff
}

WINAPI imports (at class level):

[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool GetForegroundWindow();

Assign a property to hold the value, and add the check to the form's GotFocus event through IDE, or after InitializeComponent();

e.g.:

//.....
InitalizeComponent();
this.GotFocus += (myFocusCheck);
//...

private bool onTop = false;

private void myFocusCheck(object s, EventArgs e)
{
    if(GetFore......){ onTop = true; }
}
like image 45
Chibueze Opata Avatar answered Oct 05 '22 03:10

Chibueze Opata