键组合(CTRL + F9)导致调用方法,只有在按下F9时才应调用该方法

时间:2017-12-27 12:41:27

标签: c# wpf xaml keydown

我正在使用WPF应用程序,并且在按下组合键时我显示模态/表单,所以在我的情况下它是CTRL + F9, 所以这是我的代码:

//Listening on Window_PreviewKeyDown any key pressing
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{ 

 if (e.Key == Key.Escape)
 {
    LockAllInputs();
 }

 if (e.Key == Key.Tab)
 {
    e.Handled = true;
 }

 if (e.Key == Key.F11)
 {
     this.Close();
 }
   // Opening modal when Key combination of CTRL AND F9 is pressed
   if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.F9)
   {
     MyModal modal = new MyModal();
    // Do something
   }

   //Hitting a method when only F9 is pressed
    if (e.Key == Key.F9)
    {
      //This is invoked everytime after CTRL+F9
      CallAnotherMethod();
    }
}

但是我的代码中的问题是,当我点击CTRL+F9时它工作正常,但是在按下F9时调用的方法也被调用了。 这是我想要避免的事情,CTRL+F9正在做一件事,F9正在做另外一件事,所以我不希望在按下F9时调用CTRL+F9 ... < / p>

谢谢你们

3 个答案:

答案 0 :(得分:1)

if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.F9)
{
  MyModal modal = new MyModal();
  modal.ShowDialog();
  e.Handled = true;//Here I've tried to prevent hitting another method which is being called when F9 is pressed
 }

//Hitting a method when only F9 is pressed
if (e.Key == Key.F9)
{
  //This is invoked everytime after CTRL+F9
  CallAnotherMethod();
}

您的代码将继续在第一个if 之后执行,因此也会输入第二个if

最简单的解决方案是将第二个if更改为else if

else if (e.Key == Key.F9)
{
  //This is invoked everytime after CTRL+F9
  CallAnotherMethod();
}

另一个选择是停止执行第一个if内的 功能:

if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.F9)
{
  MyModal modal = new MyModal();
  modal.ShowDialog();
  e.Handled = true;
  return;
}

答案 1 :(得分:1)

应该是这样的:

    //Listening on Window_PreviewKeyDown any key pressing
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{ 

 if (e.Key == Key.Escape)
 {
    LockAllInputs();
 }

 if (e.Key == Key.Tab)
 {
    e.Handled = true;
 }

 if (e.Key == Key.F11)
 {
     this.Close();
 }
   // Opening modal when Key combination of CTRL AND F9 is pressed
   if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.F9)
   {
     MyModal modal = new MyModal();
     modal.ShowDialog();
     e.Handled = true;//Here I've tried to prevent hitting another method which is being called when F9 is pressed
   }

   //Hitting a method when only F9 is pressed
    if (Keyboard.Modifiers == ModifierKeys.None && e.Key == Key.F9)
    {
      CallAnotherMethod();
    }
}

答案 2 :(得分:0)

您只是检查F9键是否是触发事件的键,您不检查是否还按下任何其他键。你有两个解决方案:

  1. 将第二个if更改为if else;
  2. 检查是否未按下其他修改器。