c#在接受用户输入时使用定时器影响实例

本文关键字:定时器 影响 实例 输入 用户 | 更新日期: 2023-09-27 18:13:12

我试图通过制作俄罗斯方块控制台应用程序来学习c#。我有一个gameBoard类(代码中的"gb")和一个block类(代码中的"bl")。下面的代码是我到目前为止左右移动一个块的代码,但我不知道如何在接受用户输入的同时让块掉落。

while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Escape)
        {
            switch (keyInfo.Key)
            {
                case ConsoleKey.LeftArrow:
                    currCol = bl.getCol();
                    if (currCol - 1 >= 0)
                    {
                        gb.removeBlock(bl.getCol(), bl.getRow());
                        bl.setCol(currCol - 1);
                        gb.putBlock(bl.getCol(), bl.getRow());
                        Console.Clear();
                        Console.WriteLine(gb.makeGrid());
                    }
                    break;
                case ConsoleKey.RightArrow:
                    currCol = bl.getCol();
                    if (currCol + 1 <= 9)
                    {
                        gb.removeBlock(bl.getCol(), bl.getRow());
                        bl.setCol(currCol + 1);
                        gb.putBlock(bl.getCol(), bl.getRow());
                        Console.Clear();
                        Console.WriteLine(gb.makeGrid());
                    }
                    break;
            }
        }

我假设一个定时器可能是这样做的方式,但我不知道如何我可以传递我的实例到ElapsedEventHandler的OnTimedEvent函数

public static void Main()
 {
     System.Timers.Timer aTimer = new System.Timers.Timer();
     aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
     // Set the Interval to 5 seconds.
     aTimer.Interval=5000;
     aTimer.Enabled=true;
     Console.WriteLine("Press ''q'' to quit the sample.");
     while(Console.Read()!='q');
 }
 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

是计时器的方式去,还是我应该使用其他东西?如果计时器是我应该使用的,我应该从哪里开始学习如何使用它们?

谢谢!

c#在接受用户输入时使用定时器影响实例

试试这个简单的例子,看看当您按下左箭头和右箭头,然后加上转义时发生了什么:

class Program
{
    static void Main(string[] args)
    {
        const int delay = 100;
        DateTime nextMove = DateTime.Now.AddMilliseconds(delay);
        bool quit = false;
        bool gameOver = false;
        while (!quit && !gameOver)
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true); // read key without displaying it
                switch (key.Key)
                {
                    case ConsoleKey.LeftArrow:
                        Console.Write("L");
                        break;
                    case ConsoleKey.RightArrow:
                        Console.Write("R");
                        break;
                    case ConsoleKey.Escape:
                        quit = true;
                        break;
                }
            }
            if (!quit && !gameOver && DateTime.Now > nextMove)
            {
                // ... move the pieces ...
                Console.Write(".");
                nextMove = DateTime.Now.AddMilliseconds(delay);
            }
            System.Threading.Thread.Sleep(50);
        }
    }
}

嗯,这似乎是一个试图在UI线程上做多件事的问题。计时器只是一种可能的解决方案。如果你发现定时器不够健壮,看看BackgroundWorkerTaskThread,每个都有不同的控制水平,这取决于你需要什么。

这里有一些参考资料BackgroundWorker, Thread, Task-Parallel-Library只是为了让你对如何使用这三个概念有一些了解。

好了,现在来解释一下为什么你的代码没有像预期的那样工作。现在您正在请求从控制台输入读取一个键。这将阻止控制台的所有执行,直到它读取一个键。请查看ReadKey(),了解发生这种情况的原因。

然而,有其他的方法,你可以做到这一点,而不使用ReadKey()看看这个网站设置低级键盘钩子低级键钩子。此方法将允许您在不阻塞控制台的情况下读取密钥。然而,这并不意味着它会阻止键进入控制台。所以在设计钩子时要记住这一点。我希望这能帮助你了解到底发生了什么。

也只是为了了解更多的信息,看看这个控制台。ReadKey取消,这将为您提供更多关于修改ReadKey()行为的其他方法的信息。

以防那个关于低级键盘钩子的网站被关闭这里显示的代码是:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
    _hookID = SetHook(_proc);
    Application.Run();
    UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
    using (Process curProcess = Process.GetCurrentProcess())
    using (ProcessModule curModule = curProcess.MainModule)
    {
        return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
            GetModuleHandle(curModule.ModuleName), 0);
    }
}
private delegate IntPtr LowLevelKeyboardProc(
    int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
    int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
    LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
    IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}

似乎最简单的方法是定时器(也在更复杂的情况下,你可以使用不同的线程)对于将参数传递给OnTimedEvent函数,有不同的解决方案。

1-你可以在你的类中使用定时器,OnTimedEvent是你的类的一个函数,所以你可以很容易地使用你的类字段。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            GameManager gameManager = new GameManager();
            gameManager.StartGame();
        }

        public class GameManager
        {
            System.Timers.Timer aTimer;
            int Parameter
            {
                get;
                set;
            }
            public GameManager()
            {
            }
            public void StartGame()
            {
               aTimer = new System.Timers.Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                // Set the Interval to 5 seconds.
                aTimer.Interval = 1000;
                aTimer.Enabled = true;
                Console.WriteLine("Press ''q'' to quit the sample.");
                Parameter = 200;
                while (Console.Read() != 'q') 
                {
                    Parameter =+ 10;
                }
            }
            private void OnTimedEvent(object source, ElapsedEventArgs e)
            {
                Parameter++;
                Console.WriteLine("Hello World!" + Parameter.ToString());
            }
        }
    }
}

2-使用委托

public static void Main()
        {
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += delegate(object source, ElapsedEventArgs e) {
                OnTimedEvent(source, e, "Say Hello");
            };
            // Set the Interval to 5 seconds.
            aTimer.Interval = 1000;
            aTimer.Enabled = true;
            Console.WriteLine("Press ''q'' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
        // Specify what you want to happen when the Elapsed event is raised.
        private static void OnTimedEvent(object source, ElapsedEventArgs e, string parameter)
        {
            Console.WriteLine("parameter");
        }

3-也可以使用静态全局变量