发送在组合框中选择的密钥

本文关键字:选择 密钥 组合 | 更新日期: 2023-09-27 18:31:54

我像这样填写一个组合框:

foreach (Keys key in Enum.GetValues(typeof(Keys)))
{
    comboKey.Items.Add(key);
}

稍后,用户可以选择 MIDI 音符和键。演奏所选音符时应模拟琴键。我试过了SendKeys.Wait

public void NoteOn(NoteOnMessage msg) //Is fired when a MIDI note us catched 
    {
        AppendTextBox(msg.Note.ToString());
        if (chkActive.Checked == true)
        {
            if (comboKey != null && comboNote != null)
            {
                Note selectedNote = Note.A0;
                this.Invoke((MethodInvoker)delegate()
                {
                    selectedNote = (Note)comboNote.SelectedItem;
                });
                if (msg.Note == selectedNote)
                {
                    Keys selectedKey = Keys.A; //this is just so I can use the variable
                    this.Invoke((MethodInvoker)delegate()
                    {
                        selectedKey = (Keys)comboKey.SelectedItem;
                    });
                    SendKeys.SendWait(selectedKey.ToString());

                }
            }
        }
    }

但是,例如,如果我在组合框中选择"空格"键并播放所需的音符,它不会形成空格,它只是写"空格"。我知道这可能是因为我写了selectedKey.ToString(),那么正确的方法是什么?

发送在组合框中选择的密钥

SendKeys

.SendWait.Send)预期的输入并不总是与正在按下的键的名称匹配。您可以在此链接中找到包含所有"特殊键"的列表。您必须创建一种方法将comboKey中的名称转换为SendKeys所需的格式。一个简单有效的解决方案是依靠 Dictionary .示例代码:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("a", "a");
dict.Add("backspace", "{BACKSPACE}"); 
dict.Add("break", "{BREAK}");
//replace the keys (e.g., "backspace" or "break") with the exact name (in lower caps) you are using in comboKey
//etc.

您需要将SendKeys.SendWait(selectedKey.ToString());转换为:

SendKeys.SendWait(dict[selectedKey.ToString()]);