using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
namespace ExampleApp
{
class ExampleForm : Form
{
delegate void WinEventDelegate(IntPtr hWinEventHook,
uint eventType, IntPtr hwnd, int idObject,
int idChild, uint dwEventThread, uint dwmsEventTime);
const uint WINEVENT_OUTOFCONTEXT = 0;
const uint EVENT_SYSTEM_FOREGROUND = 3;
[DllImport("user32.dll")]
static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin,
uint eventMax, IntPtr hmodWinEventProc,
WinEventDelegate lpfnWinEventProc, uint idProcess,
uint idThread, uint dwFlags);
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd,
StringBuilder lpString, int nMaxCount);
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ExampleForm());
}
ListBox m_list;
IntPtr m_hhook;
public ExampleForm()
{
m_list = new ListBox();
m_list.IntegralHeight = false;
m_list.Dock = DockStyle.Fill;
Controls.Add(m_list);
Text = "SetWinEventHook Example";
Load += new EventHandler(Program_Load);
FormClosing +=
new FormClosingEventHandler(Program_FormClosing);
}
void Program_Load(object sender, EventArgs e)
{
m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND,
EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,
WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT);
}
void WinEventProc(IntPtr hWinEventHook, uint eventType,
IntPtr hwnd, int idObject, int idChild,
uint dwEventThread, uint dwmsEventTime)
{
if (eventType == EVENT_SYSTEM_FOREGROUND)
{
StringBuilder sb = new StringBuilder(500);
GetWindowText(hwnd, sb, sb.Capacity);
m_list.Items.Insert(0,
"Switched to: " + sb.ToString());
}
}
void Program_FormClosing(
object sender, FormClosingEventArgs e)
{
UnhookWinEvent(m_hhook);
}
}
}
source: http://social.msdn.microsoft.com/Forums/en/clr/thread/c04e343f-f2e7-469a-8a54-48ca84f78c28 (may also refer to msdn library for the theory)
No comments:
Post a Comment