Search code examples
c#winformsrichtextboxkeyeventmodifiers

modifier + different char, Win Forms


Let's say my application consists of Rich Text Box and a button. I want the button to be enabled when users press a key in RTB, but it can't be any of modifiers.

I can handle this in some KeyEvent like PreviewKeyDown, but it doesn't work when I press modifier + other char, for instance SHIFT + S, which is valid, cause the result is letter S. Is there a way to separate my demand or should I make use of some different approach? I could use TextChanged, but there are many more actions that I've already written and I would prefer to do it that way.

Simple explanation:

 private void richTextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (!e.Alt && !e.Control && !e.Shift)
            {
                this.button1.Enabled = true;
                    else
                this.button1.Enabled = false;
            }
        }

Solution

  • Since the KeyPress event Occurs when a character, space or backspace key is pressed while the control has focus and modifier keys has no impact on this event, it seems using KeyPress may help you.

    But you better consider handling TextChangedevent and checking TextLength, since the user can paste something in the RichtextBox, and this way none of key events will fire.