简体   繁体   English

使用计时器检测按键

[英]Detect Keypress using a timer

Code: 码:

    private void sprites_updater_Tick(object sender, EventArgs e)
    {
        s++;
        int x = player.Location.X;
        int y = player.Location.Y;
        if (s == 1)
      if (ModifierKeys.HasFlag(Keys.A))
            {
                player.Location = new Point(x - 5, y);
            }
            s = 0;
            sprites_updater.Start();

        }

So while using timer code, I wrote the same thing above (ModifierKeys.HasFlag(Keys.A)) but it didn´t work. 因此,在使用计时器代码时,我在上面写了相同的内容(ModifierKeys.HasFlag(Keys.A)),但没有用。 Why?! 为什么?! BTW, is there any way to show a 3d camera perspective inside a WinForms Panel WITHOUT USING XNA, WPF or any other stuff (only .NET)?! 顺便说一句,有什么方法可以显示WinForms面板中的3d摄像机透视图,而无需使用XNA,WPF或其他任何内容(仅.NET)?

The best way to get keyboard strokes and processing them later is to catch the Keyboards events in the form using both KeyDown, KeyUp and flags: 获取键盘笔触并在以后进行处理的最佳方法是使用KeyDown,KeyUp和标志来捕获窗体中的Keyboards事件:

bool isAPressed;
...

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    switch(e.KeyCode)
    {
        case Key.A:
            isAPressed = true;
            break;
        case Key.XXXX:
            ...
    }
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    switch(e.KeyCode)
    {
        case Key.A:
            isAPressed = false;
            break;
        case Key.XXXX:
            ...
    }
}

Then you can use this information in your timer : 然后,您可以在计时器中使用以下信息:

private void sprites_updater_Tick(object sender, EventArgs e)
{
    s++;
    int x = player.Location.X;
    int y = player.Location.Y;
    if (s == 1)
    if (isAPressed)
        {
            player.Location = new Point(x - 5, y);
        }
        s = 0;
        sprites_updater.Start();
    }

This is particularily interresting to handle player moves this way (arrows). 特别是这很有趣,以这种方式处理玩家的移动(箭头)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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