是否有任何事件或方法来检测当我改变屏幕上的活动窗口

本文关键字:屏幕 改变 窗口 活动 检测 任何 事件 方法 是否 | 更新日期: 2023-09-27 18:16:03

我的意思是,例如,我现在正在观看visual studio窗口,然后我点击底部的Chrome图标,现在我在Chrome窗口。

我想让它检测到我现在所在的窗口被改变了。不是如果我点击了chrome图标或visual studio图标,而是以某种方式检测到我改变了我正在观看/活动/使用的窗口。

例如:

在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);
       }

但是我不确定如何让它工作,如何使用它,如果它是正确的代码。

你能给我展示一个代码的例子如何做到这一点吗?

是否有任何事件或方法来检测当我改变屏幕上的活动窗口

可以使用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 */
}