11

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.

nmarler
  • 1,416
  • 1
  • 11
  • 16
  • 1
    I assume there's no chance they'll be happily typing away and have the application lock on them because they haven't used the mouse? – Ian Nov 05 '12 at 13:16
  • Sorry, everyone, for the delay... was working on this Monday morning but was pulled off onto something else. Thank you very much for quick responses, will get back to this soon – nmarler Nov 07 '12 at 18:42

3 Answers3

24

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.

Louis Kottmann
  • 16,268
  • 4
  • 64
  • 88
  • Wow, took me a long time to get back to this but I finally found the time. @baboon great suggestion to register once and forget about it - it's working great. Thank you – nmarler Feb 01 '13 at 03:31
3
<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.

Anders Arpi
  • 8,277
  • 3
  • 33
  • 49
0

You have a few options:

Low level mouse hook: http://filipandersson.multiply.com/journal/item/7?&show_interstitial=1&u=%2Fjournal%2Fitem

WPF Solution (I'd check to see if this does what you need first): WPF. Catch last window click anywhere

Community
  • 1
  • 1
Kir
  • 2,905
  • 2
  • 27
  • 44