poco
poco

Reputation: 2995

c# how to capture Ctrl-R from a textbox

I have a from that has a text box and I'm trying to determine if Ctrl-R is pressed within this text box. I can detect the keys separately using:

private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if(e.KeyChar == (char)Keys.R)
    {
        // ...
    }
    if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
    {
        // ...
    }
}

How do I determine if they pressed at the same time?

Upvotes: 0

Views: 3467

Answers (2)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59111

See Mitch's answer on how to construct the bit flag logic correctly, as long as he undeletes it. Here's something that will work, if he doesn't decide to. You basically need to check if both conditions are true at the same time:

bool isRKeyPressed = e.KeyChar == (char)Keys.R;
bool isControlKeyPressed = (Control.ModifierKeys & Keys.Control) == Keys.Control;

if (isRKeyPressed && isControlKeyPressed)
{
    // Both ...
}
else if (isRKeyPressed)
{
    // R key only ...
}
else if (isControlKeyPressed)
{
    // CTRL key only ...
}
else
{
    // None of these...
}

Throw away any of these checks that you don't care about.

Also, you might want out check out this alternative approach: http://www.codeguru.com/columns/experts/article.php/c4639

They override the ProcessCmdKey method on their form (possibly on individual controls?): http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx

Upvotes: 3

Cheng Chen
Cheng Chen

Reputation: 43523

If possible, change your event to KeyDown/KeyUp, everything will be easier. (Note that this solution is not always applicable)

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyData == (Keys.Control | Keys.R))
   {

   }
}

Upvotes: 5

Related Questions