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

时间:2013-05-11 17:07:52

标签: c# events timer delegates

我正在尝试通过制作一个tetris控制台应用程序来学习c#。我有一个gameBoard类(代码中的“gb”)和一个块类(代码中的“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;
            }
        }

我假设Timer可能是这样做的,但我不知道如何将我的实例传递给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!");
 }

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

谢谢!

3 个答案:

答案 0 :(得分:0)

嗯,这似乎是尝试在UI线程上做多件事的问题。计时器只是解决方案的一种可能性。如果您发现计时器不够健壮,请查看BackgroundWorkerTaskThread,根据您的需要,每个人都有不同的控制级别。

以下是一些参考文献BackgroundWorkerThreadTask-Parallel-Library,以便您了解如何使用这三个提示。

好的,现在解释为什么你的代码没有按预期工作。现在你要求从控制台输入中读取一个键。这将阻止对控制台的所有执行,直到它读取密钥。看看这个,以解释为什么会发生这种情况,ReadKey()

但是,有其他方法可以在不使用ReadKey()的情况下执行此操作,请查看此网站以设置低级键盘挂钩Low-Level Key Hook。此方法允许您在不对控制台进行任何阻止的情况下读取密钥。但是,这并不意味着它会阻止密钥进入控制台。因此,在设计挂钩时请记住这一点。我希望这有助于了解正在发生的事情。

另外,只需了解更多信息,请查看此Console.ReadKey canceling,它将为您提供有关修改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);
}

答案 1 :(得分:0)

似乎最简单的方法是计时器(也可以在更复杂的情况下使用不同的线程) 要将参数传递给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-您也可以使用静态全局变量

答案 2 :(得分:0)

尝试这个简单的例子,看看当你点击左右箭头时会发生什么,然后是escape:

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);
        }

    }

}