【问题标题】:Read keyboard inputs without always having my console application focused?读取键盘输入而不总是让我的控制台应用程序专注?
【发布时间】:2020-10-04 09:59:56
【问题描述】:

是否可以在不总是让我的控制台应用程序专注的情况下读取键盘输入? 我想用一个按钮做一些事情,而不是总是去控制台。

这不是对事件起作用吗?不幸的是,我只发现了使用 Forms 的难看的解决方案。

@Siarhei Kuchuk 的这个解决方案也没有帮助我: Global keyboard capture in C# application

OnKeyPressed 事件被激活但未被触发。

有人知道吗?

【问题讨论】:

    标签: c# console hook global keyboard-hook


    【解决方案1】:

    这是可能的。你可以用谷歌搜索“键盘记录器”并找到很多例子,但我会给你一个非常粗略的裸露的例子。 但首先您必须添加对 System.Windows.Forms.dll 的引用才能使其正常工作

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Threading;
    
    namespace ConsoleApp1
    {
        class Program
        {
            [DllImport("User32.dll")]
            private static extern short GetAsyncKeyState(System.Int32 vKey);
            static void Main(string[] args)
            {
                while (true)
                {
                    Thread.Sleep(500);
                    for (int i = 0; i < 255; i++)
                    {
                        int state = GetAsyncKeyState(i);
                        if (state != 0)
                        {
                            string pressedKey= ((System.Windows.Forms.Keys)i).ToString();
                            switch (pressedKey)
                            {
    
                                default:
                                    Console.WriteLine("You have pressed: " + pressedKey);
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 2013-09-27
      • 2014-05-18
      • 2020-01-21
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 2017-01-06
      相关资源
      最近更新 更多