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

前端 未结 4 1074
别那么骄傲
别那么骄傲 2021-01-13 02:40

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

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 03:41

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

提交回复
热议问题