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.
OK、タイマーを使用しなくても、 を使用する別の選択肢がありSetWinEventHook
ます。この関数は、コールバックをフックして、イベントを含むいくつかのイベントをキャッチするのに役立ちますactive window change
。詳細については、次のリンクを参照してください:ポーリングせずに C# を使用して変更されたアクティブ ウィンドウを検出する
タイマー(ポーリング)を使用しないソリューションのコードは次のとおりです。
//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()