简体   繁体   中英

Simulate arrows key press in C# WPF

I want to simulate the LEFT and RIGHT Arrows key press when an IF condition gets true. Uptill now I have tried this so far, but it does not works. I am also controlling mouse using win32.dll import method. If I use the SendKeys.Send("LEFT"); method, my mouse movement does not get controlled. I feel like the code does not run after this call.

I have included system.windows.forms at top, what am I doing wrong?

How can I simulate arrows keys in a simple way?

     if (shoulderLeft.Position.Z > shoulderRight.Position.Z)
                            {
                                status.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkBlue);
                               SendKeys.Send("LEFT");
                               // System.Windows.Forms.MessageBox.Show("Left ROTATION");


                            }
                                //right rotate
                            else if ((shoulderLeft.Position.Z < shoulderRight.Position.Z))
                            {
                                SendKeys.Send("RIGHT");
                                status.Fill = new SolidColorBrush(System.Windows.Media.Colors.Red);

                            }

You should add brackets around LEFT and RIGHT in your code :

SendKeys.Send("{LEFT}");

Here is the complete code list .

SendKeys.Send("{LEFT}");
SendKeys.Send("{RIGHT}");

Simulating input events is usually not a good practice, instead wrap the code that runs in your event handler in a parameterized method, and then call that function when you want to simulate the event. For example (slightly contrived):

void myForm_MouseMoved(object sender, MouseEventArgs e)
{
    MoveCharacter(e.X, e.Y);
}

void myForm_SomethingElseHappened(object sender, EventArgs e)
{
    if(IsCharacterTooLow()) 
    {            
        MoveCharacter(_currentPos.X, _currentPos.Y+20)
    }
}

Hope this is useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM