c#中的键绑定

时间:2018-05-30 12:27:12

标签: c# winforms

我的Windows窗体应用程序中有一个组合框,其中包含字符串值,如“Tab”,“Space”等。我需要的是,当用户在组合框中选择其中一个选项时,它将设置它作为执行某些指令的键绑定。例如。

string[] KeyBinds = new string[] {"Tab", "Caps Lock", "Shift", "Ctrl", "Alt", "Space", "Enter", "Backspace"};
VelocityKeyBindComboBox.Items.AddRange(KeyBinds);
if (e.KeyCode == Keys.Space) //I thought of something like e.keycode == Keys.KeyBind
{
    Timer.Stop();
}

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你可以

  • 直接使用Keys数组而不是字符串。Keys[] KeyBinds = new Keys[] {Keys.Space,Keys.Enter,...};或更确切地说是List。

  • 使用Dictionary<string,Keys>映射两者,然后if (KeyBinds["Space"] == Keys.Space)等等

由于OP请求和注释内部澄清的示例:

var keyBindings = new Dictionary<string,Keys>();
//assign or reassign all your keys like this:
keyBindings["Close Window"] = Keys.Escape;
keyBindings["Enter"] = Keys.Enter;

//usage:
if (e.KeyCode == keyBindings["Enter"])

//but when you reassign it to:
keyBindings["Enter"] = Keys.F;

//now keyBindings["Enter"] is actually key F
if (e.KeyCode == keyBindings["Enter"])

值得研究KeysConverter可能有所帮助。或者您可以使用ints而不是字符串。

答案 1 :(得分:1)

我无法评论,所以我会添加答案。

据我所知,您需要获取组合框所选值的键。 如果为真,则执行以下操作:

声明一个包含对象的类:

public class MyObj
{
  public string ID;
  public string Name;
}
List<MyObj> mylist = new List<MyObj> ();
// Fill the list with data
// Fill goes here
// Bind the list to the combobox
    combobox1.DatasSource = mylist;
// Set what to show to the user, and which property to be your key
    combobox1.DisplayMember = "Name";
    combobox1.ValueMember = "ID"

当用户选择一个项目时,您可以检索它:

combobox1.SelectedValue;