0

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;
            }
        }
Paweł Poręba
  • 1,084
  • 1
  • 14
  • 37
  • It's enough to check if your `RichTextBox` has text, then enable your button. so you can handle `TextChanged` event and check for `TextLength` property. – Reza Aghaei Sep 23 '15 at 09:51
  • My richtextbox already has a text. I mean, it was just simple explanation, my case is more complicated, I need to know how to solve it when let's say richtextbox.text = "Something" and now now when I press Shift it's disabled, but when i press Shift+char it's enabled. – Paweł Poręba Sep 23 '15 at 09:55
  • @RezaAgheai Yes, I know that, as I've written in a question. But in this particular case I can't use TextChanged, that's the problem. – Paweł Poręba Sep 23 '15 at 09:56
  • So it seems using `KeyPress` event to enabling the button is enough for you, since modifiers and arrow keys , ...don't have any impact on `KeyPress`. – Reza Aghaei Sep 23 '15 at 10:04
  • But you better consider `TextChanged` since the user can paste something in the `RichtextBox`, and this way none of key events will fire. – Reza Aghaei Sep 23 '15 at 10:07
  • Did `KeyPress` solve the problem? – Reza Aghaei Sep 25 '15 at 18:14

1 Answers1

2

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398