How Can I Monitor Which Window Currently Has Keybo

2019-01-18 10:43发布

Is there a way to track which window currently has keyboard focus. I could handle WM_SETFOCUS for every window but I'm wondering if there's an alternative, simpler method (i.e. a single message handler somewhere).

I could use OnIdle() in MFC and call GetFocus() but that seems a little hacky.

标签: winapi mfc
7条回答
来,给爷笑一个
2楼-- · 2019-01-18 11:28

There is an easy way using .Net Framework 3.5 : the library UI Automation provides an event focus changed that fires every time the focus change to a new control.

Page on MSDN

Sample:

public void SubscribeToFocusChange()
{
    AutomationFocusChangedEventHandler focusHandler 
       = new AutomationFocusChangedEventHandler(OnFocusChanged);
    Automation.AddAutomationFocusChangedEventHandler(focusHandler);
}

private void OnFocusChanged(object src, AutomationFocusChangedEventArgs e)
{
    AutomationElement focusedElement = sender as AutomationElement;
    //...
}

This api in fact use windows hook behind the scenes to do that. However you have to use the .Net Framework...

查看更多
登录 后发表回答