我正在尝试通过主键击向左或向右移动表示由次要击键表示的多个像素,但到目前为止我还没有做任何事情。据我所知,我在这里应该没问题。我也将KeyPreview设置为true。
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;
}
}
答案 0 :(得分:1)
你应该改变一些事情。首先从keydown活动中取消this.Close
。从代码中可以清楚地看到休息。
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.R)
lastEntered = 'r'; //move to an enum preferably
else if (e.KeyCode == Keys.L)
lastEntered = 'l'; //move to an enum preferably
else
{
if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
{
int movement = (int)(e.KeyCode - Keys.NumPad0);
if (lastEntered == 'r')
this.Left += movement;
else if (lastEntered == 'l')
this.Left -= movement;
}
}
}
这是我假设应该始终记住最后按下的R或L而任何其他按键不会覆盖我认为不是您要查看的lastEntered
键。像这样修改你的代码是有意义的:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.R)
lastEntered = 'r'; //move to an enum preferably
else if (e.KeyCode == Keys.L)
lastEntered = 'l'; //move to an enum preferably
else
{
lastEntered = 'u'; //u for unwanted - only if even num keys should overwrite
if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
{
int movement = (int)(e.KeyCode - Keys.NumPad0);
if (lastEntered == 'r')
this.Left += movement;
else if (lastEntered == 'l')
this.Left -= movement;
}
//else //so that num keys dont overwrite and hence you
// lastEntered = 'u'; //could keep pressing num keys to move the form
}
}