900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > C#学习笔记:利用System EventArgs实现委托 响应键盘按键事件

C#学习笔记:利用System EventArgs实现委托 响应键盘按键事件

时间:2019-03-18 10:18:01

相关推荐

C#学习笔记:利用System EventArgs实现委托 响应键盘按键事件

参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P96

学习目的:掌握System,EventArgs实现委托的方法,响应键盘按键事件。捕捉用户的键盘输入,然后触发KeyPressed事件,在事件参数中传递用户按下的键。

代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;//练习目的:捕捉用户的键盘输入,然后触发KeyPressed事件,在事件参数中传递用户//按下的键namespace Example3_P96{class Program{//定义一个类,用了存放事件参数,属性表示用户按下的键public class KeyPressedEventArgs:EventArgs //派生的类{//构造函数public KeyPressedEventArgs(ConsoleKey key){PressedKey = key;}//属性如下:public ConsoleKey PressedKey { get; private set; }}//定义MyApp类public class MyApp{//捕捉按键的事件public event EventHandler<KeyPressedEventArgs> KeyPressed;//通过该方法触发事件protected virtual void OnKeyPressed(KeyPressedEventArgs e){if(this.KeyPressed !=null){this.KeyPressed(this, e);}}public void Start(){while(true){ConsoleKeyInfo keyInfo = Console.ReadKey();//如果按下了Esc键,退出循环if(keyInfo.Key == ConsoleKey.Escape){break;}//按下其它键,引发事件OnKeyPressed(new KeyPressedEventArgs(keyInfo.Key));}}}static void Main(string[] args){//实例化MyApp类,在关联KeyPressed事件的处理方法MyApp app = new MyApp();app.KeyPressed += App_KeyPressed;app.Start();}private static void App_KeyPressed(object sender, KeyPressedEventArgs e){//throw new NotImplementedException();Console.WriteLine("已按下了{0}键", e.PressedKey.ToString());}}}

运行结果如下:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。