Search code examples
c#virtual-keyboard

How to fix a simple variable problem in C#?


I am trying to fix a line of code in my project in C # using String as a variable but it gives me an error, I have tried several ways to fix it, but I can't reach the solution? What do you recommend to fix my problem?

//The problem.

            string Key1;
            string KeyHelper;
            KeyHelper = "VirtualKeyCode.VK_"; 
            Key1 = KeyHelper+"W";

         while(true)
            {
               sim.Keyboard.KeyDown(Key1);               
            }

//The Result I want to reach.

sim.Keyboard.KeyDown(VirtualKeyCode.VK_W);

This is the error that visual studio gives me:

Argument 1: cannot convert from 'string' to 'WindowsInput.Native.VirtualKeyCode'

Solution

  • You are starting with a string and attempting to pass that to a method which accepts an enum. So you need to use Enum.Parse(). Keep in mind that Enum.Parse() returns object, so you need to cast the result to the correct enum type.

    Change this:

    sim.Keyboard.KeyDown(Key1);
    

    To this:

    sim.Keyboard.KeyDown((VirtualKeyCode)Enum.Parse(typeof(VirtualKeyCode), Key1));