Search code examples
c#winformstopmost

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?


Solution

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