Determine if the program is an active window in .NET.

I have a C # /. NET application and I want to implement the following behavior:

I have a popup menu. Whenever a user clicks on something in an application that is not a popup menu, I want the popup menu to close.

However, whenever the user is not in the application, I do not want something to happen.

I am trying to control this through the LostFocus event, but I am having problems determining if my application is an active window. The code looks something like this.

    private void Button_LostFocus(object sender, System.EventArgs e)
    {
        if (InActiveWindow()) {
           CloseMenu()
        }
        else {
           // not in active window, do nothing
        }
    }

I need to know how to implement the InActiveWindow () method.

+3
source share
3 answers

P/Invoke GetForegroundWindow() HWND, . Handle.

, P/Invoke GetAncestor(), . , , .

+4

, Reed Copsey, , , , .

:

Public Class Form1
    '''<summary>
    '''Returns a handle to the foreground window.
    '''</summary>
    <Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetForegroundWindow() As IntPtr
    End Function

    '''<summary>
    '''Gets a value indicating whether this instance is foreground window.
    '''</summary>
    '''<value>
    '''<c>true</c> if this is the foreground window; otherwise, <c>false</c>.
    '''</value>
    Private ReadOnly Property IsForegroundWindow As Boolean
        Get
            Dim foreWnd = GetForegroundWindow()
            Return ((From f In Me.MdiChildren Select f.Handle).Union(
                    From f In Me.OwnedForms Select f.Handle).Union(
                    {Me.Handle})).Contains(foreWnd)
        End Get
    End Property
End Class

, #, 2 , , .

VB.NET #:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

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

    ///<summary>Gets a value indicating whether this instance is foreground window.</summary>
    ///<value><c>true</c> if this is the foreground window; otherwise, <c>false</c>.</value>
    private bool IsForegroundWindow
    {
        get
        {
            var foreWnd = GetForegroundWindow();
            return ((from f in this.MdiChildren select f.Handle)
                .Union(from f in this.OwnedForms select f.Handle)
                .Union(new IntPtr[] { this.Handle })).Contains(foreWnd);
        }
    }
}
+2

, , , , , , . , , .

- , , , , , LostFocus Deactivate , , ; , ?

, , , ( , ), Focus , , Click , , (, , ICloseOnLostFocus, , ).

, , , , MSDN , .

+1

Source: https://habr.com/ru/post/1708827/


All Articles