11

削除キーの押下をキャプチャし、キーが押されたときに何もしません。WPFおよびWindowsフォームでこれを行うにはどうすればよいですか?

4

5 に答える 5

31

WPFでMVVMを使用する場合、入力バインディングを使用してXAMLでキーが押された状態をキャプチャできます。

            <ListView.InputBindings>
                <KeyBinding Command="{Binding COMMANDTORUN}"
                            Key="KEYHERE" />
            </ListView.InputBindings>
于 2012-09-10T05:18:15.460 に答える
18

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でも同じ

于 2010-05-23T21:49:10.363 に答える
3

WPFについてはわかりませんが、 WinformsのイベントKeyDownではなく、イベントを試してみてくださいKeyPress

Control.KeyPress に関するMSDN の記事、具体的には「文字以外のキーでは KeyPress イベントは発生しませんが、文字以外のキーでは KeyDown イベントと KeyUp イベントが発生します」というフレーズを参照してください。

于 2010-05-23T21:35:36.673 に答える
2

key_press特定のコントロールのorKey_Downイベント ハンドラーを確認し、WPF のように確認するだけです。

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

Windows フォームの場合:

if (e.KeyCode == Keys.Delete)
{
   e.Handled = false;
}
于 2010-05-24T07:23:51.447 に答える
1

上記のすべてのことを試しましたが、何もうまくいきませんでしたので、私と同じ問題を抱えている他の人を助けることを期待して、私が実際に行ったことと働いたことを投稿します:

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
            }
        }
    }
于 2019-07-15T09:04:31.710 に答える