我在屏幕上更改活动窗口时是否有任何事件或方法可以检测到?

时间:2013-05-29 22:11:03

标签: c# winforms

我的意思是,例如,我现在正在观看视觉工作室窗口,然后点击Chrome图标的底部,现在我在Chrome窗口中。

我希望它能够检测到我现在正在改变的窗口。如果我点击铬图标或视觉工作室图标,但不知道我改变了窗口,我现在正在观看/主动/使用。

例如这段代码:

在我的Form1的顶部,我添加了:

public delegate void ActiveWindowChangedHandler(object sender, String windowHeader, IntPtr hwnd);
        public event ActiveWindowChangedHandler ActiveWindowChanged;
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

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

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

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

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

        IntPtr m_hhook;
        private WinEventDelegate _winEventProc;

然后在构造函数中:

_winEventProc = new WinEventDelegate(WinEventProc);
            m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND,
                EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _winEventProc,
                0, 0, WINEVENT_OUTOFCONTEXT);

然后添加了事件和功能:

void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd,
            int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
       {
            if (eventType == EVENT_SYSTEM_FOREGROUND)
            {
               if (ActiveWindowChanged != null)
                  ActiveWindowChanged(this,GetActiveWindowTitle(hwnd),hwnd);
            }
       }

       private string GetActiveWindowTitle(IntPtr hwnd)
       {
          StringBuilder Buff = new StringBuilder(500);
          GetWindowText(hwnd, Buff, Buff.Capacity);
          return Buff.ToString();
       }

       ~Form1()
       { 
        UnhookWinEvent(m_hhook);
       }

但我不确定如何使用它以及如何使用它以及它是否是正确的代码。

你能告诉我一个代码如何做的例子吗?

1 个答案:

答案 0 :(得分:0)

是的,您可以使用SetWinEventHook函数。

hEvent = SetWinEventHook(EVENT_SYSTEM_FOREGROUND , 
    EVENT_SYSTEM_FOREGROUND , NULL, 
    WinEventProcCallback, 0, 0, 
    WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);

.......

VOID CALLBACK WinEventProcCallback ( HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    /* your code here */
}

引自here的DReJ。