如何在控制台应用程序中处理按键事件 [英] How to handle key press event in console application

查看:151
本文介绍了如何在控制台应用程序中处理按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个控制台应用程序,它将显示在控制台屏幕上按下的键,我将此代码提交到目前为止:

I want to create a console application that will display the key that is pressed on the console screen, I made this code so far:

    static void Main(string[] args)
    {
        // this is absolutely wrong, but I hope you get what I mean
        PreviewKeyDownEventArgs += new PreviewKeyDownEventArgs(keylogger);
    }

    private void keylogger(KeyEventArgs e)
    {
        Console.Write(e.KeyCode);
    }

我想知道,我应该输入主要内容,所以我可以称之为事件?

I want to know, what should I type in main so I can call that event?

推荐答案

对于控制台应用程序,您可以执行此操作, do while 循环运行,直到你按 x

For console application you can do this, the do while loop runs untill you press x

public class Program
{
    public static void Main()
    {

        ConsoleKeyInfo keyinfo;
        do
        {
            keyinfo = Console.ReadKey();
            Console.WriteLine(keyinfo.Key + " was pressed");
        }
        while (keyinfo.Key != ConsoleKey.X);
    }
}

只有在您的控制台应用程序有焦点。如果您想收集系统范围的按键新闻事件,可以使用 windows hooks

This will only work if your console application has focus. If you want to gather system wide key press events you can use windows hooks

这篇关于如何在控制台应用程序中处理按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆