C#: Detecting which application has focus

前端 未结 3 1787
星月不相逢
星月不相逢 2020-11-28 08:27

I\'m looking to create a C# application that changes content according to which application currently has focus. So if the user is using Firefox, my app would know that. Sam

3条回答
  •  旧时难觅i
    2020-11-28 08:36

    This can be done in pure .NET using the Automation framework that is part of the WPF. Add references to UIAutomationClient and UIAutomationTypes and use Automation.AddAutomationFocusChangedEventHandler, e.g.:

    public class FocusMonitor
    {
        public FocusMonitor()
        {
            AutomationFocusChangedEventHandler focusHandler = OnFocusChanged;
            Automation.AddAutomationFocusChangedEventHandler(focusHandler);
        }
    
        private void OnFocusChanged(object sender, AutomationFocusChangedEventArgs e)
        {
            AutomationElement focusedElement = sender as AutomationElement;
            if (focusedElement != null)
            {
                int processId = focusedElement.Current.ProcessId;
                using (Process process = Process.GetProcessById(processId))
                {
                    Debug.WriteLine(process.ProcessName);
                }
            }
        }
    }
    

提交回复
热议问题