Home » .Net Framework

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.


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
        static extern IntPtr GetForegroundWindow();
        IntPtr LastWindow { get; set; }
        Label MessageLabel {get; set;}
        public Form1()
            MessageLabel = new Label();
            MessageLabel.Text = "Waiting...";
            LastWindow = IntPtr.Zero;
            Timer t = new Timer();
            t.Interval = 1000;
            t.Tick += new EventHandler(t_Tick);
        void t_Tick(object sender, EventArgs e)
            IntPtr hwnd = GetForegroundWindow();
            if (LastWindow != hwnd)
                MessageLabel.Text = hwnd.ToString();
                LastWindow = hwnd;




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure