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

Jon picture Jon · Aug 21, 2012 · Viewed 7.8k times · Source

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

Answer

Euric picture Euric · Aug 21, 2012

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.
}