Intercepting click event for all controls in an app in C# (WinForms)

六月ゝ 毕业季﹏ 提交于 2019-11-30 15:28:22

问题


I want to make an application to intercept all UI events in all the forms of my application and to write them to a log. This data can than be used to see which controls are the most used, in what order, etc. The problem is that I want this to happen automatically, without modifying the 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 needs a target object when manipulating events, but only the startup form can be easily accessed.

Is there a way to hook the constructor of an object? Then I could "inject" my method in all the events of the new form. Or maybe there is another way to do this.

Thanks in advance!


回答1:


You can install a message filter.

A message filter is an object that implements IMessageFilter. WinForms calls your PreFilterMessage method for every message that passes through your thread's message loop. This is enough to monitor user input across the application (and gives you the option of manipulating it).




回答2:


In Windows API this is done using local hooks (you can set local mouse hook using SetWindowsHookEx function). This is the proper way to do your task. In C# you need to use P/Invoke in order to get access to SetWindowsHookEx.

One more task would be to match the HWND (windows handle) to corresponding WinForms control. Read this article for how to do this (via WM_GETCONTROLNAME message).

Also see this question which is a duplicate of yours.




回答3:


You will have to work with the Win32's API Messages, I guess.

Here's a little example under the form of tutorial.




回答4:


You should be able to achieve what you want with message filters - no direct P/Invoke to Win32-APIs required!

See the help on the IMessageFilter interface for more info.



来源:https://stackoverflow.com/questions/4279732/intercepting-click-event-for-all-controls-in-an-app-in-c-sharp-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!