Check this code: How to
get active window handle and title
Namespaces:
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
Methods:
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
The Call:
// get handle
IntPtr handle = GetForegroundWindow();
// get title
const int count = 512;
var text = new StringBuilder(count);
if (GetWindowText(handle, text, count) > 0)
{
MessageBox.Show(text.ToString());
}
I used this code a few times. Really easy to use. You could set up an timer which fires up every 10ms. Save up 2 variables. One with the active window and one with the last window that was focused. In pseudo-code said: If newWindow != oldWindow -> listView.Add(Window).
Could look like this:
public partial class Form1 : Form
{
// DECLARE GLOBALS //
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string oldWindow = "";
public static string currentWindow = "";
// TIMER EVENT //
private void timerCheckFocus_Tick(object sender, EventArgs e)
{
// get handle
IntPtr handle = GetForegroundWindow();
// get title
const int count = 512;
var currentWindow = new StringBuilder(count);
if (currentWindow.ToString() != oldWindow)
{
// add your window to a listView //
oldWindow = currentWindow.ToString();
}
}