如何在C#中捕获删除按键?
我想捕获删除按键,但按键时不执行任何操作。如何在WPF和Windows窗体中执行此操作?我不知道WPF,但请尝试使用如何在C#中捕获删除按键?,c#,wpf,winforms,keyboard-events,C#,Wpf,Winforms,Keyboard Events,我想捕获删除按键,但按键时不执行任何操作。如何在WPF和Windows窗体中执行此操作?我不知道WPF,但请尝试使用KeyDown事件,而不是Winforms的KeyPress事件 请参阅on Control.KeyPress,特别是短语“按键事件不是由非字符键引发的;但是,非字符键确实会引发KeyDown和keydup事件。”对于WPF,请添加一个KeyDown处理程序: private void Window_KeyDown(object sender, KeyEventArgs e) {
KeyDown
事件,而不是Winforms的KeyPress
事件
请参阅on Control.KeyPress,特别是短语“按键事件不是由非字符键引发的;但是,非字符键确实会引发KeyDown和keydup事件。”对于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中是相同的只需检查特定控件上的按键
或按键
事件处理程序,然后像这样检查WPF:
if (e.Key == Key.Delete)
{
e.Handle = false;
}
对于Windows窗体:
if (e.KeyCode == Keys.Delete)
{
e.Handled = false;
}
将MVVM与WPF结合使用时,可以使用输入绑定捕获XAML中按下的键
<ListView.InputBindings>
<KeyBinding Command="{Binding COMMANDTORUN}"
Key="KEYHERE" />
</ListView.InputBindings>
我尝试了上面提到的所有东西,但没有任何效果,因此我发布了我实际做过和做过的事情,希望能帮助与我有同样问题的其他人: 在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
}
}
}
哪个UI框架?Winforms?WPF。。。?加上在哪种情况下?文本框、表格等@Mehrdad Afshari。在WPF和WinformsThanks中,都需要回复。如何防止删除操作?很高兴知道!如何检查是否按下了CTRL或SHIFT?@Matt-看看
键盘。修饰符
。我想知道为什么这没有得到更多的支持:从概念上讲,这是一种更干净的方法。我同意弗拉德,这是一种非常干净的方法+1在某些组件上,您可以将绑定放在定义中(我不知道这是否很常见,或者是唯一的Telerik事件):@Jeff您会发现这不是太多绑定,而是更多事件处理背后的代码。以下是delete键的工作实现,供将来参考