[C#]
void HandleMouseInput(object sender, MouseEventArgs args)
{
TextBox tb = args.Source as TextBox;
if (tb == null)
return;
if (ActiveTextBox == null)
Activate(tb);
else
Deactivate(ActiveTextBox);
}
//Deactivates the active TextBox if the Enter
// or ESC key is pressed.
void HandleKeyInput(object sender, KeyEventArgs args)
{
TextBox tb = args.Source as TextBox;
if (tb != null &&
(args.Key == Key.Return || args.Key == Key.Escape))
Deactivate(tb);
}
//Deactivate the Textbox the active TextBox.
void HandleLostFocus(object sender, EventArgs args)
{
TextBox tb = sender as TextBox;
if (tb != null)
Deactivate(tb);
}
//Activate the TextBox by applying the base style
//(thereby removing the basic style.) Set focus, select
//all the content & invalidate the visual.
//Also, dynamically add handlers for losing focus and
//handling key input.
void Activate(TextBox tb)
{
tb.Style = (Style)tb.FindResource("TextBoxBaseStyle");
tb.Focus();
tb.SelectAll();
tb.InvalidateVisual();
tb.LostFocus += new RoutedEventHandler(HandleLostFocus);
tb.KeyDown += new KeyEventHandler(HandleKeyInput);
ActiveTextBox = tb;
}
//Deactivate the TextBox by applying the Basic style.
//Remove the event handlers.
void Deactivate(TextBox tb)
{
tb.Style = (Style)tb.FindResource("BasicTextBox");
tb.LostFocus -= new RoutedEventHandler(HandleLostFocus);
tb.KeyDown -= new KeyEventHandler(HandleKeyInput);
ActiveTextBox = null;
}