Domanda

I fill a combobox like this:

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

Later, the user can select a MIDI Note and a key. The key should be simulated when the selected note is played. I tried it with 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());


                }
            }
        }
    }

But for example, if I select the "Space" key in the combobox and play the required note, it doesnt make a space it just writes "Space". And I know this is probably because I wrote selectedKey.ToString(), so what is the right approach?

È stato utile?

Soluzione

The inputs expected by SendKeys (.SendWait or .Send) do not always match the name of the key being pressed. You can find a list with all the "special keys" in this link. You have to create a way to convert the names in comboKey into the format expected by SendKeys. An easy and effective solution is relying on a Dictionary. Sample code:

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.

You need to convert SendKeys.SendWait(selectedKey.ToString()); into:

SendKeys.SendWait(dict[selectedKey.ToString()]);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top