2

アクティブなウィンドウのスクリーンショットを撮るコードがいくつかあります。私の上司は、アクティブなウィンドウが変更されるたびに実行する必要があるコードを求めています。例:

  • 電卓を開く - スクリーンショットが撮られます
  • フォーカスをメモ帳に切り替える - スクリーンショットが撮影されます
  • フォーカスを Chrome に切り替えます - スクリーンショットが撮影されます

私の頭に浮かんだ最初の考えは、現在アクティブなウィンドウのハンドルのハンドルを変数に格納し、現在のアクティブなウィンドウのハンドルが変数の値と同じかどうかを継続的に確認することでした。コンピューターで発生しているイベントをサブスクライブして、アクティブなウィンドウが変更されるたびに知らせてもらう方法はありますか?

4

1 に答える 1

4

Win32 API で利用可能な以下のメソッドを見てください。

    SetWinEventHook()
    UnhookWinEvent()

これは、ウィンドウ変更イベントを検出するのに役立ちます。

サンプルコード

using System;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class NameChangeTracker
{
    delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

    [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 bool UnhookWinEvent(IntPtr hWinEventHook);

    const uint EVENT_OBJECT_NAMECHANGE = 0x800C;
    const uint WINEVENT_OUTOFCONTEXT = 0;

    // Need to ensure delegate is not collected while we're using it,
    // storing it in a class field is simplest way to do this.
    static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc);

    public static void Main()
    {
        // Listen for name change changes across all processes/threads on current desktop...
        IntPtr hhook = SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, IntPtr.Zero,
                procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);

        // MessageBox provides the necessary mesage loop that SetWinEventHook requires.
        // In real-world code, use a regular message loop (GetMessage/TranslateMessage/
        // DispatchMessage etc or equivalent.)
        MessageBox.Show("Tracking name changes on HWNDs, close message box to exit.");

        UnhookWinEvent(hhook);
    }

    static void WinEventProc(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        // filter out non-HWND namechanges... (eg. items within a listbox)
        if(idObject != 0 || idChild != 0)
        {
            return;
        }
        Console.WriteLine("Text of hwnd changed {0:x8}", hwnd.ToInt32()); 
    }
}
于 2013-09-16T14:27:02.323 に答える