Determine Whether Program is the Active Window in .NET

前端 未结 3 1115
你的背包
你的背包 2020-12-11 10:27

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

I have a popup menu. Whenever the user clicks on anything within the application that

3条回答
  •  我在风中等你
    2020-12-11 10:58

    I stumbled upon your question while working on a project and based on Reed Copsey's answer, I wrote this quick code which seems to do the job well.

    Here's the code:

    Public Class Form1
        '''
        '''Returns a handle to the foreground window.
        '''
         _
        Private Shared Function GetForegroundWindow() As IntPtr
        End Function
    
        '''
        '''Gets a value indicating whether this instance is foreground window.
        '''
        '''
        '''true if this is the foreground window; otherwise, false.
        '''
        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
    

    I didn't have too much time to convert it to C# as I'm working on a project with a deadline in 2 days but I believe you can quickly do the conversion.

    Here is the C# version of the VB.NET code:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
    
        ///Gets a value indicating whether this instance is foreground window.
        ///true if this is the foreground window; otherwise, false.
        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);
            }
        }
    }
    

提交回复
热议问题