c#全局系统钩子,用于检测活动窗口的变化

c#全局系统钩子,用于检测活动窗口的变化,c#,C#,我一直在使用下面的代码来检测C#活动窗口的变化,但在一些奇怪的情况下,当它确实发生时,它根本不注册活动窗口的变化。在大多数情况下,它工作得非常好。我已经研究过了,但在我看来,我唯一能做的就是求助于C++来获得一个可靠的解决方案,但在这样做之前,我想我会问下面的代码问题 GlobalEventHook.Start(); GlobalEventHook.WinEventActive += new EventHandler(GlobalEventHook_WinEventActive);

我一直在使用下面的代码来检测C#活动窗口的变化,但在一些奇怪的情况下,当它确实发生时,它根本不注册活动窗口的变化。在大多数情况下,它工作得非常好。我已经研究过了,但在我看来,我唯一能做的就是求助于C++来获得一个可靠的解决方案,但在这样做之前,我想我会问下面的代码问题

GlobalEventHook.Start();
GlobalEventHook.WinEventActive += new EventHandler(GlobalEventHook_WinEventActive);                         //set up the global hook events

private void GlobalEventHook_WinEventActive(object sender, EventArgs e)
{
// do whatever
}  

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Pro
{
public static class GlobalEventHook
{
    [DllImport("user32.dll")]
    internal static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, 
        WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

    [DllImport("user32.dll")]
    internal static extern bool UnhookWinEvent(IntPtr hWinEventHook);

    public static event EventHandler WinEventActive = delegate { };
    public static event EventHandler WinEventContentScrolled = delegate { };

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

    private static WinEventDelegate dele = null;
    private static IntPtr _hookID = IntPtr.Zero;



    public static void Start()
    {
        dele = new WinEventDelegate(WinEventProc);
        _hookID = SetWinEventHook(Win32API.EVENT_SYSTEM_FOREGROUND, Win32API.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, Win32API.WINEVENT_OUTOFCONTEXT);
    }

    public static void stop()
    {
        UnhookWinEvent(_hookID);
    }

    public static void restart()
    {

        _hookID = SetWinEventHook(Win32API.EVENT_SYSTEM_FOREGROUND, Win32API.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, Win32API.WINEVENT_OUTOFCONTEXT);
    }

    public static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        try
        {
            if (eventType == Win32API.EVENT_SYSTEM_FOREGROUND)
            {
                if (hwnd == Win32API.GetForegroundWindow())
                {
                    WinEventActive(null, new EventArgs());
                }                    
            }                                    
        }

        catch (Exception exc)
        {
        }
    }

我会放弃对getForeGroundIndow()的检查,这是不必要的,而且是潜在的竞争。当然还有空钓。这在C++中不会有任何不同。