Using Mouse.Capture to detect a click outside of a given control

2.4k Views Asked by At

I have a TextBox in a WPF project where I am trying to detect a mouse click anywhere on the Application other than in the TextBox.

Here is the code that I have so far.

System.Windows.Input.MouseButtonEventHandler clickOutsideHandler;

public MyClass() {
    clickOutsideHandler = new System.Windows.Input.MouseButtonEventHandler(HandleClickOutsideOfControl);
}

private void StartCapture() {
    System.Windows.Input.Mouse.Capture(TextBox1, System.Windows.Input.CaptureMode.SubTree);
    AddHandler(System.Windows.Input.Mouse.PreviewMouseDownOutsideCapturedElementEvent, clickOutsideHandler, true);
}

private void HandleClickOutsideOfControl(object sender, System.Windows.Input.MouseButtonEventArgs e) {
    ReleaseMouseCapture();
    RemoveHandler(System.Windows.Input.Mouse.PreviewMouseDownOutsideCapturedElementEvent, clickOutsideHandler);
}

The problem I'm having is that the event handler never gets called. I've tried capturing the return value of the Capture() function, but it shows as true. Can anyone show me what I'm doing wrong?

1

There are 1 best solutions below

1
On

You could instead use LostFocus / LostKeyboardFocus but there has to be another element on the window that can get focus.

Second approach that does more what you what exactly ( yet doesn't make total sense) would be to attach to the global mouse down. Intercept every mouse click to WPF application

then on that one do a hittest and determine what is underneath.https://msdn.microsoft.com/en-us/library/ms608753(v=vs.110).aspx