Click event capture for all controls in a C # application (WinForms)

I want to make an application to intercept all user interface events in all forms of my application and write them to the log. This data can be used to determine which controls are most used, in which order, etc. The problem is that I want this to happen automatically, without changing existing classes.

I made a prototype that attaches a method to a click event for all controls in a form, but how can this be done for all forms? Reflection requires a target when handling events, but you can easily access only the launch form.

Is there a way to bind an object constructor? Then I could “introduce” my method into all the events of the new form. Or maybe there is another way to do this.

Thanks in advance!

+6
source share
4 answers

You can set a message filter .

A message filter is an object that implements IMessageFilter . WinForms calls your PreFilterMessage method for each message that passes through the thread's message loop. This is enough to control user input in the application (and gives you the ability to manipulate it).

+7
source

In the Windows API, this is done using local hooks (you can set a local mouse hook using SetWindowsHookEx ). This is the right way to accomplish your task. In C #, you need to use P / Invoke to access SetWindowsHookEx.

Another task is to combine the HWND (Windows descriptor) with the corresponding WinForms control. Read this article to learn how to do this (via the WM_GETCONTROLNAME message).

Also see this question , which is your duplicate.

+1
source

You may have to work with Win32 API messages.

Here is a small example in the form of a textbook .

0
source

You can achieve what you want with message filters - no direct P / Invoke for Win32-API required!

For more information, see help on IMessageFilter .

0
source

All Articles