0

我正在尝试使由主击键表示的表单向左或向右移动由辅助击键表示的多个像素,但到目前为止我还没有做任何事情。据我所知,我在这里应该没有问题。我也将 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;
        }
    }
4

1 回答 1

1

有几件事你应该改变。this.Close首先从 keydown 事件中起飞。从代码中可以清楚地看到休息。

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
    }
}
于 2012-10-27T04:58:13.780 回答