How Can I Monitor Which Window Currently Has Keyboard Focus

前端 未结 7 648
情话喂你
情话喂你 2020-12-09 17:12

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

相关标签:
7条回答
  • 2020-12-09 18:00

    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 sender, 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...

    0 讨论(0)
提交回复
热议问题