user3288171
user3288171

Reputation: 9

as modifier not working in (e.KeyCode == x as Keys) in C#

I'm having an error with this block of code in C#

    private void frm2_KeyDown(object sender, KeyEventArgs e)
    {
        string x = "w";
        if (e.KeyCode == x as Keys)
        {
            //do whatever
        }
    }

I get this error

The as operator must be used with a reference type or nullable type ('System.Windows.Forms.Keys' is a non-nullable value type)

I need to do something similar to what this user posted about here. I haven't a clue why this isn't working and would appreciate any help. I am relatively new to programming so please go easy on me. I would be willing to supply any other part of the code necessary to troubleshoot the issue.

Upvotes: 0

Views: 135

Answers (2)

Mihai Hantea
Mihai Hantea

Reputation: 1743

What you have to do is a String to Enum conversion

if (e.Modifiers == (Keys)Enum.Parse(typeof(Keys), "keys1", true) && e.KeyCode == (Keys)Enum.Parse(typeof(Keys), "keys2", true))
        {
            string keyPressed = e.KeyCode.ToString();
            MessageBox.Show(keyPressed);
        }

Example:

    private int count = 0;
    private string keysPressed = "NOTE";
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (count < keysPressed.Length)
        {
            if (e.Modifiers == (Keys)Enum.Parse(typeof(Keys), "None", true) &&
                e.KeyCode == (Keys)Enum.Parse(typeof(Keys), keysPressed[count].ToString(), true))
            {
                if (count == keysPressed.Length - 1)
                {
                    MessageBox.Show(keysPressed);
                    //restart
                    count = 0;
                }
                else
                    count++;
            }
            else
                count = 0;
        }
        else
            count = 0;
    }

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

You need to use Enum.Parse method to convert string to Keys but I suggest you to use use Keys.W

if (e.KeyCode == Keys.W)
{
        //do whatever
}

Your attempt doesn't work because x is of type string which can never be of type Keys. You cannot cast string to Keys enum, you can only convert it. Remember cast and convert are two different things.

If at all you need to convert here's how you do

string str = ...;//Get string somehow
Keys myKey = (Keys)Enum.Parse(typeof (Keys), str);


You can use keys to achieve the same with keys enum like this.

Keys neededLetter = Keys.W;
if (e.KeyCode == neededLetter)
{
    if ( neededLetter == Keys.N)
    {
        neededLetter =  Keys.O;
    } else if ( neededLetter == Keys.O ) {
        neededLetter = Keys.T;
    } else if ( neededLetter ==  Keys.T ) {
        neededLetter =  Keys.E;
    } else if ( neededLetter == Keys.E ) {
        // you now have the full sequence typed, show your app
    }
}

Upvotes: 2

Related Questions