0

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?

Hypersapien
  • 617
  • 2
  • 8
  • 23
  • Why does the TextBox have to be responsible for this? – 15ee8f99-57ff-4f92-890c-b56153 Sep 06 '17 at 20:19
  • I have a label that you double-click on. When that happens, the label hides and a TextBox with the same text unhides, so the user can edit the text. If the user clicks anywhere other than the TextBox without hitting Enter, the text is restored, the TextBox is hidden again, and the Label is made visible again. – Hypersapien Sep 06 '17 at 20:22
  • I think what you want is to put the TextBox in a `Popup`. `Popup` does what you want automatically, by default: Click outside it, it goes away. You can bind its IsOpen property or handle its Closed event if you want to unhide the Label when it closes. The WPF team already did all the miserable work you're trying to do here; let their code handle the ugly details. – 15ee8f99-57ff-4f92-890c-b56153 Sep 06 '17 at 20:24

1 Answers1

1

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

RJ Thompson
  • 126
  • 7
  • I like the LostFocus approach - even if there is no other control to get focus this sounds like the only right way – Tom Schardt Sep 06 '17 at 21:38