用于按钮问题的C#可调式热键功能

时间:2019-02-22 02:56:35

标签: c#

我正在创建一个热键功能atm,以便用户在我设置键且它们不可调整之前,可以根据自己的需要调整键绑定。这是我以前使用的。

public void gHook_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.D:
            // stuff
            Salvagebtn.PerformClick();
            break;
        case Keys.F12:
            // stuff
            pausebtn.PerformClick();
            break;
        case Keys.K:
            //stuff
            Geardropbtn.PerformClick();
            break;
        case Keys.F:
            //stuff
            Gamblebtn.PerformClick();
            break;
        case Keys.A:
            //stuff
            LeftClickSpambtn.PerformClick();
            break;
        case Keys.H:
            // stuff
            openGRbtn.PerformClick();
            break;
        case Keys.B:
            //stuff                    
            gemupbtn.PerformClick();
            break;
    }
}

现在我做了一个设置标签,其中ppl可以更改看起来像这样的键绑定。

enter image description here

我将如何处理它而不是“ case Keys.D:”,它将对文本框中的键绑定做出反应?

1 个答案:

答案 0 :(得分:0)

几种方法可以做到。一种可行的方法是将键绑定分配给Dictionary,其中UserActions是一个定义可能动作的枚举:

public enum UserAction
{
    Salvage, Pause, Drop // etc...
}

然后,当用户按下按键时,类似:

public void gHook_KeyDown(object sender, KeyEventArgs e)
{
    string k = e.KeyCode.ToString();
    if (KeyBindings.Contains(k)) //KeyBindings is your field or variable which is a Dictionary<string, UserAction>
    {
      var action = KeyBindings[k]
      switch (action)
      {
        case UserAction.Salvage:
          // stuff
          Salvagebtn.PerformClick();
          break;
        case UserAction.Pause:
          // stuff
          pausebtn.PerformClick();
          break;
         // and so on...

将值分配给字典:

var KeyBindings = new Dictionary<string, UserAction>;
KeyBindings["D"] = UserAction.Salvage;
KeyBindings["A"] = UserAction.Pause;

如果需要从用户输入中获取键,则可以使用Enum.TryParse(input):

Keys key;
if (Enum.TryParse<Keys>(textBoxSalvage.Text, out key))
{
    KeyBinding[textBoxSalvage.Text] = UserAction.Salvage; // note that 'UserAction.something' comes from the context
}