I'm trying to make a form move left or right denoted by a primary keystroke by a number of pixels denoted by a secondary keystroke but so far I've not been able to do anything. As far as I can tell I should have no problem here. I have set KeyPreview to true as well.
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
this.Close();
int movement = 0;
if (e.KeyCode == Keys.R)
lastEntered = 'r';
else if (e.KeyCode == Keys.L)
lastEntered = 'l';
else
{
if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
{
movement = (int)(e.KeyCode - Keys.NumPad0);
Console.WriteLine(movement);
this.Left += movement;
}
if (lastEntered == 'r')
this.Left += movement;
else if (lastEntered == 'l')
this.Left -= movement;
}
}
There are a few things you should change. Take off
this.Close
from the keydown event first of all. Rest will be clear from the code.This is when I assume that the last pressed R or L should be remembered always and any other key down doesn't overwrite the
lastEntered
key which I believe is not what you would be looking into. Modify your code like this to make sense: