2016-04-03 84 views
0

我想将一个简单的字符串转换为一个键,我发现了一些解决方案,但其中大部分都是用于winforms,或者他们没有显示完整的代码,所以我没有明白它。将字符串转换为密钥

这是什么basicaly我想要实现

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"); 
      } 
     } 
    } 
} 

回答

0

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

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"); 
    } 
} 
+0

谢谢你这个完美的作品! – Simon

+0

@Simon欢迎:) –