假设您使用ContextMenuStrip
托盘菜单:
IntPtr lastHandle;
public IntPtr GetForegroundWin(){
IntPtr hwnd = GetForegroundWindow();
if(hwnd != contextMenuStrip1.Handle) lastHandle = hwnd;
return lastHandle;
}
//Add a timer
Timer t = new Timer();
t.Interval = 1;
t.Tick += (s,e) => {
GetForegroundWin();
};//Then you can get the foreground Handle by lastHandle
t.Start();//this timer will run as long as your application runs.
好的,不使用定时器,我们还有另一个选择使用SetWinEventHook
. 这个函数可以帮助你挂钩一些回调来捕获一些事件,包括active window change
事件。这是您了解更多信息的链接:Detect active window changed using C# without polling
这是不使用计时器(轮询)的解决方案的代码:
//Must add using System.Runtime.InteropServices;
public partial class Form1 : Form
{
[DllImport("user32")]
private static extern IntPtr SetWinEventHook(int minEvent, int maxEvent, IntPtr hModule, WinEventProcDelegate proc, int procId, int threadId, int flags);
private delegate void WinEventProcDelegate(IntPtr hHook, int ev, IntPtr hwnd, int objectId, int childId, int eventThread, int eventTime);
private void WinEventProc(IntPtr hHook, int ev, IntPtr hwnd, int objectId, int childId, int eventThread, int eventTime)
{
if(hwnd != contextMenuStrip1.Handle) lastHandle = hwnd;
}
public Form1()
{
InitializeComponent();
//EVENT_SYSTEM_FOREGROUND = 3
//WINEVENT_OUTOFCONTEXT = 0
SetWinEventHook(3, 3, IntPtr.Zero, WinEventProc, 0, 0, 0);
}
IntPtr lastHandle;
}
//You can access the lastHandle to get the current active/foreground window. This doesn't require GetForegroundWindow()