【问题标题】:How to capture delete key press in C#?如何在 C# 中捕获删除按键?
【发布时间】:2010-05-23 21:03:11
【问题描述】:

我想捕获删除按键,并且在按键被按下时什么都不做。如何在 WPF 和 Windows 窗体中做到这一点?

【问题讨论】:

  • 哪个 UI 框架?窗体? WPF? ...?
  • 加在什么情况下?文本框、表单等
  • @Mehrdad Afshari。在 WPF 和 Winforms 中

标签: c# wpf winforms keyboard-events


【解决方案1】:

将 MVVM 与 WPF 结合使用时,您可以使用输入绑定在 XAML 中捕获按键。

            <ListView.InputBindings>
                <KeyBinding Command="{Binding COMMANDTORUN}"
                            Key="KEYHERE" />
            </ListView.InputBindings>

【讨论】:

  • 我想知道为什么这没有得到更多的支持:从概念上讲,这是一种更清洁的方式。
  • 我同意弗拉德,这是一种非常干净的方法。 +1
  • 在某些组件上,您可以将绑定放在定义中(我不知道这是否很常见,或者是 Telerik 独有的东西):
  • @Jeff 你会发现这不是太多的绑定,而是更多的事件处理代码。
  • 这里是删除键的工作实现以供将来参考
【解决方案2】:

对于 WPF 添加 KeyDown 处理程序:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        MessageBox.Show("delete pressed");
        e.Handled = true;
    }
}

这几乎与 WinForms 相同:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        MessageBox.Show("delete pressed");
        e.Handled = true;
    }
}

别忘了打开KeyPreview。

如果您想阻止执行键默认操作,请设置e.Handled = true,如上所示。在 WinForms 和 WPF 中是一样的

【讨论】:

  • 感谢您的回复。如何防止删除操作?
  • 很高兴知道!如何检查是否按下了 CTRL 或 SHIFT?
  • @Matt - 看看Keyboard.Modifiers。
【解决方案3】:

我不了解 WPF,但请尝试使用 KeyDown 事件而不是 Winforms 的 KeyPress 事件。

请参阅 Control.KeyPress 上的 MSDN article,特别是短语“非字符键不会引发 KeyPress 事件;但是,非字符键会引发 KeyDown 和 KeyUp 事件。”

【讨论】:

    【解决方案4】:

    只需检查特定控件上的 key_press 或 Key_Down 事件处理程序,然后检查 WPF:

    if (e.Key == Key.Delete)
    {
       e.Handle = false;
    }
    

    对于 Windows 窗体:

    if (e.KeyCode == Keys.Delete)
    {
       e.Handled = false;
    }
    

    【讨论】:

      【解决方案5】:

      我尝试了上面提到的所有东西,但对我没有任何效果,所以我发布了我实际所做和工作的内容,希望能帮助其他与我有同样问题的人:

      在 xaml 文件的代码隐藏中,在构造函数中添加事件处理程序:

      using System;
      using System.Windows;
      using System.Windows.Input;
      public partial class NewView : UserControl
          {
          public NewView()
              {
                  this.RemoveHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown)); 
                  // im not sure if the above line is needed (or if the GC takes care of it
                  // anyway) , im adding it just to be safe  
                  this.AddHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown), true);
                  InitializeComponent();
              }
           //....
            private void NewView_KeyDown(object sender, KeyEventArgs e)
              {
                  if (e.Key == Key.Delete)
                  {
                      //your logic
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多