[英]How to capture delete key press in C#?
我希望捕獲刪除鍵按下,並在按下鍵時不執行任何操作。 如何在WPF和Windows窗體中執行此操作?
將MVVM與WPF一起使用時,您可以使用輸入綁定捕獲XAML中的按鍵。
<ListView.InputBindings>
<KeyBinding Command="{Binding COMMANDTORUN}"
Key="KEYHERE" />
</ListView.InputBindings>
對於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,但嘗試KeyDown
事件而不是Winforms的KeyPress
事件。
請參閱有關Control.KeyPress的MSDN文章 ,特別是短語“KeyPress事件不是由非字符鍵引發的;但是,非字符鍵確實會引發KeyDown和KeyUp事件。”
只需檢查特定控件上的key_press
或Key_Down
事件處理程序,然后檢查WPF:
if (e.Key == Key.Delete)
{
e.Handle = false;
}
對於Windows窗體:
if (e.KeyCode == Keys.Delete)
{
e.Handled = false;
}
我嘗試了上面提到的所有內容,但沒有任何對我有用,所以我發布了我實際做過和工作的內容,希望能幫助其他人解決與我相同的問題:
在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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.