简体   繁体   中英

How to know when ctrl+space pushed?

I want to call function when Ctrl + space pushed. I searched more but couldn't find what I want.

You need to add an event handler for KeyDown like: KeyDown="TextBox_KeyDown" on your TextBox. And then in the event handler:

if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{ 
      //Do Stuff
}

Use something like this:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space && 
       (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
    {
        // Do what you need here
    }
}

This should get you working -

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
  if (e.Key == Key.Space && Keyboard.Modifiers == ModifierKeys.Control)
  { 
  }
}

If you want to catch all the keys, whether you have the focus or not, in your class you just need to add in the constructor:

// To capture keyboard
EventManager.RegisterClassHandler(typeof(Window), Keyboard.KeyDownEvent, new System.Windows.Input.KeyEventHandler(keyDown), true);

And add the method: (it's an example, it's not for adapted for what you want)

private void keyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        code;
    }
    else if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&    Keyboard.IsKeyDown(Key.T))
    {
        code;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM