0

私はc#でアプリケーションを書いていますが、グラウンドウィンドウのがいつ変更されたかを知る必要があります。SetWindowsHookExを使用しましたが、ウィンドウを切り替えてもコールバックがありません。

私のコード:

private const int WH_CALLWNDPROC = 4;

private delegate IntPtr windowName(int nCode, IntPtr wParam, IntPtr lParam);
private static windowName _name = HookCallback;
private static IntPtr _hook = IntPtr.Zero;

public static void start()
{   
    _hook = SetHook(_name);
    Application.Run();
    UnhookWindowsHookEx(_hook);
}

private static IntPtr SetHook(windowName proc)
{
    using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_CALLWNDPROC, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
}

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{   
    browser = GetActiveWindow();
    Console.WriteLine(browser);
    return CallNextHookEx(_hook, nCode, wParam, lParam);
}
4

1 に答える 1

0

わかりました、答えがあります

    public static void start()
    {
        WinEventDelegate dele = new WinEventDelegate(WinEventProc);
        IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
        string window = GetActiveWindowTitle();
        Console.WriteLine(window);
        while (true)
        {
            if (window != GetActiveWindowTitle())
            {
                window = GetActiveWindowTitle();
                Console.WriteLine(window);
            }
        }
    }

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

    private static string GetActiveWindowTitle()
    {
        const int nChars = 256;
        IntPtr handle = IntPtr.Zero;
        StringBuilder Buff = new StringBuilder(nChars);
        handle = GetForegroundWindow();

        if (GetWindowText(handle, Buff, nChars) > 0)
        {
            return Buff.ToString();
        }
        return null;
    }

    public static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        Console.WriteLine(GetActiveWindowTitle());
    }

    #region imports
    [DllImport("user32.dll")]
    static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

    private const uint WINEVENT_OUTOFCONTEXT = 0;
    private const uint EVENT_SYSTEM_FOREGROUND = 3;

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    #endregion

少し面倒ですが、機能します

于 2012-11-21T11:09:02.673 に答える