Home » .Net FrameworkRSS

Detect when the active window changes.

In my application I want to detect when the active window changes. These windows are not a part of my application. I want to call GetForegroundWindow() periodically; how can I do that?
 

3 Answers Found

 

Answer 1

Call GetForegroundWindow() inside a timer event handler.  You can identify when the resulting window  changes.

--
Mike
 

Answer 2

I thought of that, but I had no idea how to do it. How do I initialize a timer event handler?

edit: Never mind, I figured it out.

 

Answer 3

Here is an example form:
 
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();
 
        IntPtr LastWindow { get; set; }
        Label MessageLabel {get; set;}
 
        public Form1()
        {
            InitializeComponent();
 
            MessageLabel = new Label();
            MessageLabel.Text = "Waiting...";
            LastWindow = IntPtr.Zero;
            Controls.Add(MessageLabel);
            Timer t = new Timer();
            t.Interval = 1000;
            t.Tick += new EventHandler(t_Tick);
            t.Start();
        }
 
        void t_Tick(object sender, EventArgs e)
        {
            IntPtr hwnd = GetForegroundWindow();
            if (LastWindow != hwnd)
            {
                MessageLabel.Text = hwnd.ToString();
                LastWindow = hwnd;
            }
        }
    }
}

 

--
Mike
 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter