From ad7ea1457c6d501ac654592a7b1f6fecb0e1a3b2 Mon Sep 17 00:00:00 2001 From: Daniel Kraus Date: Mon, 31 Aug 2015 12:28:50 +0200 Subject: [PATCH] Make TextBoxes select all text on focus. --- zaaReloaded2/ThisAddIn.cs | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/zaaReloaded2/ThisAddIn.cs b/zaaReloaded2/ThisAddIn.cs index 5838ea0..738e2a7 100755 --- a/zaaReloaded2/ThisAddIn.cs +++ b/zaaReloaded2/ThisAddIn.cs @@ -27,6 +27,10 @@ using Microsoft.Office.Tools.Word; using Bovender.Versioning; using Bovender.Mvvm.Messaging; using zaaReloaded2.ExceptionHandler; +using System.Windows; +using System.Windows.Input; +using System.Windows.Controls; +using System.Windows.Media; namespace zaaReloaded2 { @@ -48,6 +52,7 @@ namespace zaaReloaded2 private void ThisAddIn_Startup(object sender, System.EventArgs e) { Bovender.ExceptionHandler.CentralHandler.ManageExceptionCallback += CentralHandler_ManageExceptionCallback; + RegisterTextBoxSelectAll(); CheckForUpdates(); _oldCaption = Globals.ThisAddIn.Application.Caption; Globals.ThisAddIn.Application.Caption = @@ -156,5 +161,43 @@ namespace zaaReloaded2 } #endregion + + void RegisterTextBoxSelectAll() + { + // Select the text in a TextBox when it receives focus. + EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, + new MouseButtonEventHandler(SelectivelyIgnoreMouseButton)); + EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent, + new RoutedEventHandler(SelectAllText)); + EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent, + new RoutedEventHandler(SelectAllText)); + } + + void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) + { + // Find the TextBox + DependencyObject parent = e.OriginalSource as UIElement; + while (parent != null && !(parent is TextBox)) + parent = VisualTreeHelper.GetParent(parent); + + if (parent != null) + { + var textBox = (TextBox)parent; + if (!textBox.IsKeyboardFocusWithin) + { + // If the text box is not yet focused, give it the focus and + // stop further processing of this click event. + textBox.Focus(); + e.Handled = true; + } + } + } + + void SelectAllText(object sender, RoutedEventArgs e) + { + var textBox = e.OriginalSource as TextBox; + if (textBox != null) + textBox.SelectAll(); + } } }