将字符串转换为键

时间:2016-04-03 06:45:55

标签: c# wpf input

我正在尝试将一个简单的字符串转换为一个键,我发现了一些解决方案,但大多数是针对winforms的,或者他们没有显示完整的代码,所以我不理解它。

这基本上是我想要实现的目标

namespace KeyDown
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string CustomKey = "B";
        public MainWindow()
        {
            InitializeComponent();
            activeArea.Focus();
        }

        private void activeArea_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.CustomKey)
            {
                MessageBox.Show("Key Pressed");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在WPF中使用System.Windows.Input.Key枚举:

using System.Windows.Input;

...

public Key CustomKey = Key.B;

// or this if you really want to convert the string representation
public Key CustomKey = (Key)Enum.Parse(typeof(Key), "B");


private void activeArea_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == CustomKey)
    {
        MessageBox.Show("Key Pressed");
    }
}