user9769106
user9769106

Reputation: 21

Key Binding in c#

I have combo box in my windows form application which contains, string values such as "Tab", "Space", etc. What I need is, when a user selects one of these options in the combo box, it will set it as the key bind to perform some instructions. E.g.

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

Thanks in advance for the help.

Upvotes: 1

Views: 5341

Answers (2)

Attersson
Attersson

Reputation: 4866

You can

  • directly use an array of Keys instead of strings.Keys[] KeyBinds = new Keys[] {Keys.Space,Keys.Enter,...}; or rather a List.

  • use a Dictionary<string,Keys> to map the two, then if (KeyBinds["Space"] == Keys.Space) etc etc

Example due to OP request and clarification inside comments:

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"])

It is also worth looking into KeysConverter which might help. Or you could use ints instead of strings.

Upvotes: 1

Plexis Plexis
Plexis Plexis

Reputation: 302

I cannot comment, so I will add the answer.

as I understood, you need to get the key of the selected value of the combo box. If true than do the following:

declare a class that holds your objects:

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"

When the user selects a an item you can retrieve it:

combobox1.SelectedValue;

Upvotes: 1

Related Questions