David Lancaster
David Lancaster

Reputation: 41

Value of a String to e.KeyCode in C#

So im in C# Windows Form Application in Visual Studio, Im making a soundboard program that plays sounds to corresponding "Hotkeys" that are set by the user. Im having trouble figuring out how to get the program to recognise the user set hotkeys. That might sound vague, so let me show you.

Ok, this is the code that is set to run from the start "What you edit when you double click the form in the design menu"

    if (e.KeyCode == Keys.D)

    {
     // The Program plays sound
    }

So I know that when I press "d" on my keyboard, the sound plays.

Well, I want the sound to play when I type in a character that I have written in a textbox somewhere else. So like I open my program put "t" into the "set hotkey" text box, then press t and the sound plays.

So I want the program do do something like this

    if (e.KeyCode == Keys.(textBox1.Text)) // textBox1 is my set hotkey box 

    {
     // The Program plays sound
    }

Is there some way I can get textBox.Text to be recognised by e.KeyCode? Do I have to convert textBox1.Text to a key code value? If so, How?

Im new to coding, so try to explain it to me as if I were a dummy :D

I really appriciate your time!

Upvotes: 4

Views: 4124

Answers (3)

Sham
Sham

Reputation: 840

Try to parse the text value as enum.

if (e.KeyCode == (Keys)Enum.Parse(typeof(Keys), textBox1.Text))
{
 // The Program plays sound
}

(Pseudo code, not complied)

Upvotes: 1

chris
chris

Reputation: 57

You could try to create an KeyDown event at your textbox and with an switch staement you can differ between the different keys

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        Switch(e.Key)
             case e.Key == Key.D; PlaysondforD; break;
             case e.Key == Key.E; PlaysondforE; break;
             .........
    }

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

Use Enum.TryParse method

Keys key;
if (Enum.TryParse<Keys>(textBox1.Text, out key))
{
    //Do something with key
    if (e.KeyCode == key)
    {

    }
}

If you're concerned about only 1 character try the following:

Keys key;
if (textBox1.TextLength > 0 && Enum.TryParse<Keys>(textBox1.Text[0].ToString(), out key))
{
    //Do something with key
    if (e.KeyCode == key)
    {

    }
}

Upvotes: 5

Related Questions