Saturday, 4 January 2014

PreviewKeyDown and KeyDown event in WPF

PreviewKeyDown used to pre-handle the typed key before it is handled by the KeyDown event.

For Ex: If you want to allow only digits in text dox, then you can use the PreviewKeyDown event this way


        private void ValidateOnTypingTcpPort(object sender, KeyEventArgs e)
        {
            if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back & e.Key != Key.Delete & e.Key != Key.Left & e.Key != Key.Right & e.Key != Key.Up & e.Key != Key.Down)
            {
                MessageBox.Show("Provide only digits. Other Keyboard Charrecters are not allowed."); 
                e.Handled = true;
            }
        }


This function will let you input only digits.

Other characters are prevented from appearing in the text box by handling it in the above line e.Handled = true;

This way you can prevent the event to traverse below the tree of controls by making setting its flag as e.Handled = true;

No comments:

Post a Comment