アプリケーションがダイアログボックスを表示するとき、Windowsオペレーティングシステムの(私にとっては静かに迷惑な)動作は、新しく作成されたウィンドウを他のすべての上に表示することです。したがって、監視するプロセスがわかっていると仮定すると、新しいウィンドウを検出する方法は、Windowsフックを設定することです。
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,
IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr
hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,
uint idThread, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
// Constants from winuser.h
public const uint EVENT_SYSTEM_FOREGROUND = 3;
public const uint WINEVENT_OUTOFCONTEXT = 0;
//The GetForegroundWindow function returns a handle to the foreground window.
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
// For example, in Main() function
// Listen for foreground window changes across all processes/threads on current desktop
IntPtr hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,
new WinEventDelegate(WinEventProc), 0, 0, WINEVENT_OUTOFCONTEXT);
void WinEventProc(IntPtr hWinEventHook, uint eventType,
IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
IntPtr foregroundWinHandle = GetForegroundWindow();
//Do something (f.e check if that is the needed window)
}
//When you Close Your application, remove the hook:
UnhookWinEvent(hhook);
ダイアログボックスに対してそのコードを明示的に試したわけではありませんが、個別のプロセスではうまく機能します。メッセージポンプが必要なため、Windowsサービスまたはコンソールアプリケーションではコードが機能しないことに注意してください(Windowsアプリケーションにはそれがあります)。独自に作成する必要があります。
お役に立てれば