【问题标题】:Is it possible to call a specific method every time a button is pressed, even when the console is not expecting user input?每次按下按钮时是否可以调用特定方法,即使控制台不期望用户输入?
【发布时间】:2019-03-26 07:33:35
【问题描述】:

我正在编写一个用于区分函数的程序,并希望在按下“esc”后立即调用特定方法。

到目前为止,我已尝试通过 Google 找到答案,但似乎找不到任何可行的方法。有谁知道这在 C# 控制台应用程序中是否可行?

【问题讨论】:

标签: c# console console-application


【解决方案1】:

没有监听按键的事件。只有Console.ReadKey。但是您可以使用Tasks 将其转换为回调。像这样:

public static void RegisterKeyHandler(Action<ConsoleKeyInfo> handler)
{
    Task.Run(() =>
    {
        while (true)
        {
            var key = Console.ReadKey();
            handler(key);
        }
    });
}

这只会在控制台窗口获得焦点时接收键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2015-03-25
    • 2018-10-23
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多