Scout Monitor

edit

INTRODUCTION

edit
  • Able to track and fetch active window application details.

Active Window

edit

Opening different applications leads to many windows showing up. But there can be only one active window at a time. An active window is a pop-up window. One that currently holds the keyboard focus.

How to get active window using C#?

Windows 32 API

edit

The Windows 32 API is created for 32-bit processors and relies on 32 bit values. It is portable to any operating system, a wide range of processors and is of a platform independent nature. What is characteristic about that API is that it has the 32 prefix after the library name.

All APIs are implemented using 3 libraries:

  • Kernel
  • User
  • GDI

In this project we will be using the User library. Or to be more precise the “USER32.dll” in Win32. This allows managing entire user interfaces such as: Windows, Menus, Dialog Boxes, Icons etc.

So, the first thing we need to do is import and declare the methods we are going to use.

Import and Declare Win32 methods

edit

In our project, we have a class Call it WinApi.cs. This class will import and declare the native Window API related methods we are going to use in our project.

Inside the class write the following C# code:

[DllImport("user32.dll")]

        internal static extern int GetWindowText(IntPtr handle, StringBuilder text, int count);


[DllImport("user32.dll")]

        internal static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hModWinEventProc,

                                                     WinEventDelegate lpFnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

GetWindowText

edit

The handle is only a pointer to the window. We want to display the title of the currently active window. So, we need the title bar text. GetWindowText copies the text of the specified window’s title bar (if it has one) into a buffer.

We are using this method in ContentReader class to extract the title and child content of an active window.

SetWinEventHook

The system sends this event even if the foreground window has changed to another window. We can use this event to get the current active window.

Create an Active Window Listener

edit

Now it is time to put everything together. We will build up an ActiveWindowListener class. Behind the class there will be a Timer component. It will be a recurring one. This means that after the interval elapses it will fetch the currently active window information. This information will be published to everyone who is subscribed or listening for a specific event.