简体   繁体   中英

How to know if a form is not selected?

I have a lots of problem to distinguish such a simple thing.

I need to know if a form is currently in front of everything, the one which receives key entries.

I have no way to know if it is.

I can check if not minimized. But then it may just be behind other windows, or just not being selected (for example it is openend, desktop is behind, you click on desktop, then you still see the application, but it doesn't receive key inputs).

The property focus is irrevelant for this.

Here is the code

    protected override void OnActivated(EventArgs e)
    {
        base.OnActivated(e);

        if (this.Focused)
        {
            gotFocus = true;
            // never reaches tis
        }

Check if window is the current active window.

Code:

using System.Runtime.InteropServices; // To use DllImport

...

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

        if ((IntPtr)GetForegroundWindow() == this.Handle)
        {
            // Do stuff
        }

See: Use GetForegroundWindow result in an if statement to check user's current window

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM