How do I register single event listener for all buttons

c#, event-handling, wpf

Solution

How can I listen to all button clicks in my WPF app?

You can hook events to all objects for a type by using the EventManager:

EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(Button_Click));

private void Button_Click(object sender, RoutedEventArgs e)
{

}

In application new windows are being opened and closed with their own buttons so I can not do it statically.

If you create these Windows in WPF, you can hook into the Window events such as Closed, Sizechanged and Got/LostFocus(). If these Windows are not WPF/Winform based you can use a ShellHook

Problem

How can I listen to all button clicks in my WPF app. Maybe include some of the checkboxes or so but ideally I do not want to have extra event handler. I want to collect initial statistics to know how people use our application. I want to make sure I do not interfere with any other event handling functionality. In application new windows are being opened and closed with their own buttons so I can not do it statically. Alternatively is there any common way to collect usage statistics from WPF apps.

Original source