Dante1986
Dante1986

Reputation: 59939

detect Ctrl + Enter

(using WPF) i try to detect when Ctrl + Enter gets hit. so i tried this code:

if (e.Key == Key.Return && (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl))
 {
   //Do Something            
 }

Obviously this is not correct, as it does not work. Could anyone help me out, explaining what the right way should be ?

thanx

Upvotes: 8

Views: 10345

Answers (4)

Pelican
Pelican

Reputation: 51

if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Enter)

Upvotes: 4

ahmed_soft3
ahmed_soft3

Reputation: 1

   if (e.KeyChar == 10)
            {
             ///Code
            }

Or

 if ((Char)e.KeyChar == '\n')
            {
             ///Code
            }

Upvotes: -1

Pank
Pank

Reputation: 690

I think you need a SpecialKey Handler. I googled a bit a found a solution here.

Following code from the referred link may solve your problem:

  void SpecialKeyHandler(object sender, KeyEventArgs e)
{
    // Ctrl + N
    if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.N))
    {
        MessageBox.Show("New");
    }

    // Ctrl + O
    if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
    {
        MessageBox.Show("Open");
    }

    // Ctrl + S
    if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S))
    {
        MessageBox.Show("Save");
    }

    // Ctrl + Alt + I
    if ((Keyboard.Modifiers == (ModifierKeys.Alt | ModifierKeys.Control)) && (e.Key == Key.I))
    {
        MessageBox.Show("Ctrl + Alt + I");
    }
}

Upvotes: 8

Ben Voigt
Ben Voigt

Reputation: 283624

Obviously e.Key can't be equal to more than one different value in the same event.

You need to handle one of the events that uses KeyEventArgs, there you'll find properties such as Control and Modifiers that will help you detect combinations.

The KeyPress event, which uses KeyPressEventArgs, just doesn't have sufficient information.


Drat, you said WPF didn't you. It looks like you need e.KeyboardDevice.Modifiers.

Upvotes: 16

Related Questions