This sample tracks the input focus on the desktop and displays information about focus changes, using Microsoft UI Automation. This is a simple console application that might be used as a starting-point for an application that uses UI Automation to track events on the desktop.
The program announces when the input focus changes. If the focus moves to a different application window, the caption of the window is announced. If the focus moves within an application window, the type and name of the control being read are announced.
To know when the focus switches from one application to another, the program keeps a list of the runtime identifiers of all open top-level windows. In response to each focus-changed event, a TreeWalker is used to find the parent window, and that window is compared with the last window that had focus.
The program subscribes to three event types:
Structure changed. The only event of interest is the addition of a new top-level window.
Focus changed. All events are captured.
Window closed. When a top-level window is closed, its runtime ID is removed from the list.
For simplicity, no caching is done. A full-scale application would likely cache all immediate children of an application window as soon as that window received focus.
This sample demonstrates a specific feature of the Windows Presentation Foundation (WPF) and, consequently, does not follow application development best practices. For comprehensive coverage of Windows Presentation Foundation (WPF) and Microsoft .NET Framework application development best practices, refer to the following as appropriate:
Accessibility - Accessibility Best Practices
Security - Windows Presentation Foundation Security
Localization - WPF Globalization and Localization Overview
Install the Windows Software Development Kit (SDK) and open its build environment command window. On the Start menu, point to All Programs, Microsoft Windows SDK, and then click CMD Shell.
Download the sample, usually from the software development kit (SDK) documentation, to your hard disk drive.
To build the sample from the build environment command window, go to the source directory of the sample. At the command prompt, type MSBUILD.
To build the sample in Microsoft Visual Studio, load the sample solution or project file and then press CTRL+SHIFT+B.