我的意思是,例如,我现在正在观看 Visual Studio 窗口,然后单击 Chrome 图标的底部,现在我在 Chrome 窗口中。
我希望它检测到我现在所在的窗口已更改。如果我单击 chrome 图标或 Visual Studio 图标,则不会,而是以某种方式检测到我更改了我现在正在观看/活动/使用的窗口。
例如这段代码:
在我的 Form1 顶部,我添加了:
public delegate void ActiveWindowChangedHandler(object sender, String windowHeader, IntPtr hwnd);
public event ActiveWindowChangedHandler ActiveWindowChanged;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
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);
IntPtr m_hhook;
private WinEventDelegate _winEventProc;
然后在构造函数中:
_winEventProc = new WinEventDelegate(WinEventProc);
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)
{
if (ActiveWindowChanged != null)
ActiveWindowChanged(this,GetActiveWindowTitle(hwnd),hwnd);
}
}
private string GetActiveWindowTitle(IntPtr hwnd)
{
StringBuilder Buff = new StringBuilder(500);
GetWindowText(hwnd, Buff, Buff.Capacity);
return Buff.ToString();
}
~Form1()
{
UnhookWinEvent(m_hhook);
}
但我不确定如何让它工作以及如何使用它以及它是否是正确的代码。
你能告诉我一个如何做的代码示例吗?