参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P137
学习目标:如何捕捉按下的键。本例通过switch判断按下的键是否为上、下、左、右
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
// 输出测试文本
Console.WriteLine("我爱我的祖国1,");
Console.WriteLine("我爱我的祖国2");
Console.WriteLine("我爱我的祖国3");
Console.WriteLine("我爱我的祖国4");
Console.WriteLine("我爱我的祖国5");
Console.WriteLine("我爱我的祖国6");
Console.WriteLine("我爱我的祖国7");
Console.WriteLine("我爱我的祖国8");
// 在修改缓冲区域大小前先缩小窗口区域
Console.SetWindowSize(1, 1);
// 设置缓冲区域的大小
Console.SetBufferSize(82, 25);
// 再次设置窗口的区域大小
Console.SetWindowSize(30, 8);
// 捕捉键盘输入
ConsoleKeyInfo keyInfo;
do
{
keyInfo = Console.ReadKey(true);
// 判断按下的键
switch (keyInfo.Key)
{
case ConsoleKey.RightArrow: //右
if (Console.WindowLeft < (Console.BufferWidth - Console.WindowWidth))
{
Console.SetWindowPosition(Console.WindowLeft + 1, Console.WindowTop);
}
break;
case ConsoleKey.LeftArrow: //左
if (Console.WindowLeft > 0)
{
Console.SetWindowPosition(Console.WindowLeft - 1, Console.WindowTop);
}
break;
case ConsoleKey.UpArrow: //上
if (Console.WindowTop > 0)
{
Console.SetWindowPosition(Console.WindowLeft, Console.WindowTop - 1);
}
break;
case ConsoleKey.DownArrow: //下
if (Console.WindowTop < (Console.BufferHeight - Console.WindowHeight))
{
Console.SetWindowPosition(Console.WindowLeft, Console.WindowTop + 1);
}
break;
}
} while (keyInfo.Key != ConsoleKey.Escape);
}//Main方法末尾
}//类末尾
}
运行结果如下:
程序操作说明:按下上下左右键时,滚动条会相应移动。