Code It
Code It

Reputation: 396

Global window hook in C#

Currently I'm using the following code to get active window title-

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

[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

It's working great.

Now I would like to capture global active window change event in my C# app. I don't know how it can be done.

Any help?

Upvotes: 0

Views: 1427

Answers (1)

s.k.paul
s.k.paul

Reputation: 7291

Here is a complete code snippet taken from here-

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace ActiveWindowChangeEvent
{
    public partial class Form1 : Form
    {
        delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
        WinEventDelegate dele = null;
        [DllImport("user32.dll")]
        static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
        private const uint WINEVENT_OUTOFCONTEXT = 0;
        private const uint EVENT_SYSTEM_FOREGROUND = 3;

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        private string GetActiveWindowTitle()
        {
           const int nChars = 256;
           IntPtr handle = IntPtr.Zero;
           StringBuilder Buff = new StringBuilder(nChars);
           handle = GetForegroundWindow();

           if (GetWindowText(handle, Buff, nChars) > 0)
           {
               return Buff.ToString();
           }
           return null;
       }

        public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
           Log.Text += GetActiveWindowTitle() + "\r\n";  //Log= RichTextBox
        } 

        public Form1()
        {
           InitializeComponent();
           dele = new WinEventDelegate(WinEventProc);
           IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
        }
    }
}

Hope, this will help.

Upvotes: 2

Related Questions