Make TextBoxes select all text on focus.

This commit is contained in:
Daniel Kraus 2015-08-31 12:28:50 +02:00
parent 9068dde1c3
commit ad7ea1457c

View File

@ -27,6 +27,10 @@ using Microsoft.Office.Tools.Word;
using Bovender.Versioning; using Bovender.Versioning;
using Bovender.Mvvm.Messaging; using Bovender.Mvvm.Messaging;
using zaaReloaded2.ExceptionHandler; using zaaReloaded2.ExceptionHandler;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
namespace zaaReloaded2 namespace zaaReloaded2
{ {
@ -48,6 +52,7 @@ namespace zaaReloaded2
private void ThisAddIn_Startup(object sender, System.EventArgs e) private void ThisAddIn_Startup(object sender, System.EventArgs e)
{ {
Bovender.ExceptionHandler.CentralHandler.ManageExceptionCallback += CentralHandler_ManageExceptionCallback; Bovender.ExceptionHandler.CentralHandler.ManageExceptionCallback += CentralHandler_ManageExceptionCallback;
RegisterTextBoxSelectAll();
CheckForUpdates(); CheckForUpdates();
_oldCaption = Globals.ThisAddIn.Application.Caption; _oldCaption = Globals.ThisAddIn.Application.Caption;
Globals.ThisAddIn.Application.Caption = Globals.ThisAddIn.Application.Caption =
@ -156,5 +161,43 @@ namespace zaaReloaded2
} }
#endregion #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();
}
} }
} }