Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept every mouse click to WPF application

Tags:

c#

wpf

I'm looking to intercept every mouse click in my WPF application. Seems this should be easy with the command routing mechanism, but sorry I'm not finding anything.

My application implements several security levels, and has the requirement to automatically revert to the most restrictive level if no one interacts with (clicks) the application in x minutes. My plan is to add a timer that expires after x minutes and adjusts the security level. Each mouse click into the application will reset the timer.

like image 762
nmarler Avatar asked Nov 05 '12 13:11

nmarler


2 Answers

You can register a class handler:

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            EventManager.RegisterClassHandler(typeof(Window), Window.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));

            base.OnStartup(e);
        }

        static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Trace.WriteLine("Clicked!!");
        }
    }

This will handle any PreviewMouseDown event on any Window created in the application.

like image 163
Louis Kottmann Avatar answered Oct 10 '22 18:10

Louis Kottmann


<Window .... PreviewMouseDown="Window_PreviewMouseDown_1">
</Window>

This should work for you.

This fires even if other MouseDown events fire for components that it contains.

As per Clemens suggestion in the comments, PreviewMouseDown is a better choice than MouseDown, as that makes sure you can't stop the event bubbling from happening in a different event.

like image 39
Anders Arpi Avatar answered Oct 10 '22 19:10

Anders Arpi