Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

C# PreviewKeyDown Event - Allow Special Characters

$
0
0

Hello,

I have a textbox and a PreviewKeyDown Event in which i want to allow Special Characters,A-Z and 0-9 only. Other keys such as keyboard modifiers, F1-F12, Esc,Tab, etc are not allowed.

 private void PART_SearchText_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            TextBox searchTextBox = sender as TextBox;

           if (((e.Key >= Key.A && e.Key <= Key.Z)
                || (e.Key >= Key.D0 && e.Key <= Key.D9)
                || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
                || (e.Key == Key.Back || e.Key == Key.Delete))&& (Keyboard.Modifiers != ModifierKeys.Shift)&& (Keyboard.Modifiers != ModifierKeys.Alt)&& (Keyboard.Modifiers != ModifierKeys.Control)&& (Keyboard.Modifiers != ModifierKeys.Windows)&& (searchTextBox.SelectedText.Length > 0 && searchTextBox.Text.Length > 0)&& (searchTextBox.SelectedText.Length == searchTextBox.Text.Length))
            {
                if (SearchDeletionCommand != null)
                {
                    searchTextBox.IsReadOnly = false;
                    SearchDeletionCommand.Execute(null);
                }
            }
      }

The issue I am facing when hitting special characters (!,@,#...).

So on my laptop if i press Shift 1, i am eventually entering a punctuation mark (!) and that should work. But in above code what happens is that the conditions does not get satisfied.

Thanks,

Abdi


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>