0

OK, basically I want to test if the shift key is pressed.
The method i've tried (unsuccessfully) is

private bool shiftPressed = false;
        private void CheckKeys(object sender, KeyPressEventArgs e)
        {
            //If enter is pressed and shift isn't
            //This allows for line breaks in a message by pressing shift & enter at the same time
            if (e.KeyChar == (char)13 && !shiftPressed)
            {
                //remove the line break caused by the enter key
                rtbInput.Text = rtbInput.Text.Substring(0, rtbInput.Text.Length - 1);
                Send();
            }

            //Else if shift is pressed
            else if (e.KeyChar == (char)15)
            {
                shiftPressed = true;
            }

            //Else if shift is depressed
            else if (e.KeyChar == (char)14)
            {
                shiftPressed = false;
            }
        }

This is run every time a key is pressed in the rich text box. Unfortunately, shift doesnt appear to trigger the KeyPressEventHandler

Can anybody show me an alternate method that i can use to test for the shift key?

Thanks,
Josh.

2
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by Geekitygeek
0

You need to use the KeyUp and KeyDown events. The shift key doesnt fire the KeyPress event.
The KeyUp and KeyDown events have an e.KeyData property which will hold a value you can check against the Keys enumeration:

if(e.KeyData== Keys.ShiftKey)

Edited by Geekitygeek: n/a

0

Thanks Ryshad!

Just a note to anyone else who sees this in the future, the KeyData of KeyDown for shift is equal to:
Keys.ShiftKey | Keys.Shift
whereas for KeyUp it's equal to:
Keys.ShiftKey

^^The above gave me a 10 minute debigging headache - Not really sure why MS has done this, but all the same - works now.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.