编辑2017 07 30 13:49 这与其他问题的主要区别在于: 如何同时检测2个按键?
例如:仅当同时按下键A和B时,屏幕上显示“2”的程序。释放A或B或两者时,显示“1”
以下程序不起作用,因为ReadKey需要等待。
if(Console.KeyAvailable){}也不起作用,因为它只允许读取一个键,而不是同时按下多个键。
简而言之,我希望有人可以告诉我一个函数,当使用时,立即输出一个布尔值取决于是否按下某个键而不让程序等待
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
int number = 2;
while (true)
{
Console.Clear();
if (Console.ReadKey(true).Key == ConsoleKey.B & Console.ReadKey(true).Key == ConsoleKey.A)
{
Console.Write(2);
}
else
{
Console.Write(1);
}
}
}
}
}
我现在是C#的新手我想知道是否有办法检查按键是否按下,并相应地实时更改变量。
我有一个程序,在按下一个键后输出一个数字,但是,它的更新速率太慢,它一次只能检查一个键。 (如果我同时按下AB,它只能识别A或B.)
是否存在一个输出布尔值并且不会像Console.ReadKey()那样阻止代码的函数? (或类似的东西)例如,如果在使用此功能时按下A,则“function(A)”将输出“true”。如果没有,它就会出现“假”,程序会进入下一行。
总之,您能告诉我如何编程控制台,以便它有一个反映实时按键的变量列表吗?
(使用while(true)循环,在任何时候我按下键A.程序写入变量KeyA = true,在任何时候没有按下,KeyA = false)
尝试过活动,但无法让它发挥作用。 (编译期间“不存在”错误)
这是我正在使用的程序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
int number = 2;
while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey();
Console.Write((int)key.KeyChar);
}
}
}
}
}
答案 0 :(得分:0)
请参阅此代码:
class Program
{
[System.Runtime.InteropServices.DllImport("User32.dll")]
public static extern short GetAsyncKeyState(int vKey);
static void Main(string[] args)
{
while (GetAsyncKeyState('Q') == 0)
{
short result = GetAsyncKeyState('A');
if (result < 0 && (result & 0x01) == 0x01)
Console.WriteLine("A pressed and up");
}
}
}
按Q退出或按A查看已按下的消息。您还可以使用GetKeyboardState API一次性检索所有键的信息。请务必阅读文档以正确理解返回值和用法。