Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using System.Collections.Generic;
- class ConsoleKbhit
- {
- public class ConsoleKbhitEventArgs
- {
- public ConsoleKbhitEventArgs()
- {
- isCancel = false;
- Console.CursorVisible = false;
- }
- public bool isCancel
- {
- get { return cancel == 1; }
- set { Interlocked.Exchange(ref cancel, value ? 1 : 0); }
- }
- public ConsoleKeyInfo keyInfo { get; set; }
- volatile int cancel;
- }
- public void StartListening()
- {
- if (ConsoleKbhitEvent == null)
- throw new ArgumentNullException("需先绑定事件:ConsoleKbhitEvent");
- trd = new Thread(new ThreadStart(() =>
- {
- do
- {
- args.keyInfo = Console.ReadKey(true);
- ConsoleKbhitEvent(this, args);
- } while (!args.isCancel);
- }));
- trd.Start();
- }
- public bool isListening
- {
- get { return trd != null && trd.ThreadState == ThreadState.Running; }
- }
- public void MarkStop()
- {
- args.isCancel = true;
- }
- private ConsoleKbhitEventArgs args = new ConsoleKbhitEventArgs();
- private Thread trd;
- public delegate void ConsoleKbhitEventHandler(object sender, ConsoleKbhitEventArgs e);
- public event ConsoleKbhitEventHandler ConsoleKbhitEvent;
- }
- class Program
- {
- const short Width = 10, Height = 20;
- static void GotoAndPut(int X, int Y, char C)
- {
- Console.CursorLeft = X;
- Console.CursorTop = Y;
- Console.Write(C);
- }
- static void Main()
- {
- var kbhit = new ConsoleKbhit();
- kbhit.ConsoleKbhitEvent += new ConsoleKbhit.ConsoleKbhitEventHandler(kbhit_ConsoleKbhitEvent);
- kbhit.StartListening();
- Console.Write('■');
- while (kbhit.isListening)
- {
- Thread.Sleep(500);
- lock(thisLock)
- {
- if (Y < Height - 1)
- MoveTo(delegate { Y++; });
- else
- X = Y = 0;
- }
- }
- }
- static void MoveTo(Action f)
- {
- GotoAndPut(X, Y, ' ');
- f();
- GotoAndPut(X, Y, '■');
- }
- static void kbhit_ConsoleKbhitEvent(object sender, ConsoleKbhit.ConsoleKbhitEventArgs e)
- {
- if (e.keyInfo.Key == ConsoleKey.Escape || e.keyInfo.Key == ConsoleKey.Q)
- {
- e.isCancel = true;
- return;
- }
- lock (thisLock)
- {
- switch (e.keyInfo.Key)
- {
- case ConsoleKey.W: break;
- case ConsoleKey.S: if (Y < Height - 1) MoveTo(delegate { Y++; }); else X = Y = 0; break;
- case ConsoleKey.A: MoveTo(delegate { if (X > 0) X -= 2; }); break;
- case ConsoleKey.D: MoveTo(delegate { if (X < Width * 2 - 2) X += 2; }); break;
- }
- }
- }
- static object thisLock = new object();
- static int X = 0, Y = 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement