How to supress the Alt-Key in Silverlight’s TextBox
You can restrict the input-values in Silverlight’s TextBox by handling the KeyDown-Event. But the KeyDown-Event isn’t fired if the user enters a key by pressing e.g. ALT + 123.
Corresponding to the problem mentioned in http://forums.silverlight.net/forums/t/147718.aspx, I’ll show here a short workaround by using the TextChanged and KeyUp-Event of the TextBox. Just use the following snippet, that removes a character that was added by pressing the ALT- and another Key or Key-Combination:
private void TextBox_TextChanged(object sender, TextCh… e)
{
if (_altWasPressed)
{
// remove the added character
var textBox = ((TextBox)sender);
var caretPos = textBox.SelectionStart;
var text = textBox.Text;
var textStart = text.Substring(0, caretPos - 1);
var textEnd = "";
if (caretPos < text.Length)
textEnd = text.Substring(caretPos, text.Length-caretPos);
textBox.Text = textStart + textEnd;
textBox.SelectionStart = caretPos - 1;
_altWasPressed = false;
}
}
private bool _altWasPressed;
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
_altWasPressed = e.Key == Key.Alt;
}
Leave a Reply