我写了一段显示所有按键的代码。我想知道的是,如果我按下组合键,如 Ctrl + A , Alt + O 或 Ctrl + 删除或 Ctrl + Alt + 删除这些键也会显示在控制台上。该方法应该是什么?
刚出现的另一件事是,如果有人拿着钥匙并继续按下其他键,这里可以捕获这种行为吗?
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(Int32 i);
for (Int32 i = 0; i < 255; i++)
{
int keyState = GetAsyncKeyState(i);
if (keyState == 1 || keyState == -32767)
{
Console.WriteLine((Keys)i);
break;
}
}
答案 0 :(得分:1)
我相信您正在寻找GetKeyboardState功能。我将在一次通话中为您提供所有虚拟键的状态。 GetAsyncKeyState函数更适用于检查用户是否按下了某个键。
作为练习,我编写了以下内容来演示GetAsyncKeyState API调用:
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace s26244308
{
class Program
{
static void Main(string[] args)
{
bool keepGoing = true;
while (keepGoing)
{
int wasItPressed = SysWin32.GetAsyncKeyState(SysWin32.VK_ESCAPE);
if (wasItPressed != 0)
{
keepGoing = false; // stop
continue;
}
// for this sample: just loop a few letters
for (int x = 0x41; x <= 0x4A; x++)
{
int letterPressed = SysWin32.GetAsyncKeyState(x);
if (letterPressed != 0)
{
// now check for a few other keys
int shiftAction = SysWin32.GetAsyncKeyState(SysWin32.VK_SHIFT);
int ctrlAction = SysWin32.GetAsyncKeyState(SysWin32.VK_CONTROL);
int altAction = SysWin32.GetAsyncKeyState(SysWin32.VK_MENU);
// format my output
string letter = string.Format("Letter: {0} ({1})", Convert.ToChar(x), KeyAction(letterPressed));
string shift = string.Format("Shift: {0}", KeyAction(shiftAction));
string ctrl = string.Format("Control: {0}", KeyAction(ctrlAction));
string alt = string.Format("Alt: {0}", KeyAction(altAction));
Console.WriteLine("{0,-20}{1,-18}{2,-18}{3,-18}", letter, shift, ctrl, alt);
break;
}
}
Thread.Sleep(10);
}
Console.WriteLine("-- Press Any Key to Continue --");
Console.ReadLine();
}
private static string KeyAction(int pressed)
{
if (pressed == 0)
return "Up";
// check LSB
if (IsBitSet(pressed, 0))
return "Pressed";
// checked MSB
if (IsBitSet(pressed, 15))
return "Down";
return Convert.ToString(pressed, 2);
}
private static bool IsBitSet(int b, int pos)
{
return (b & (1 << pos)) != 0;
}
}
class SysWin32
{
public const int VK_ESCAPE = 0x1B;
public const int VK_SHIFT = 0x10;
public const int VK_CONTROL = 0x11;
public const int VK_MENU = 0x12;
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(Int32 i);
}
}
这是控制台输出:
答案 1 :(得分:0)
我想我明白你在问什么。您想要一种方法来检查用户按下的组合键。我没有使用GetAsyncKeyState()就尝试了你要找的东西。
这是我做的KeyDown事件操作:
prevKey = currentKey;
currentKey = e.KeyCode;
if (prevKey == Keys.ControlKey && currentKey == Keys.Menu)
{
// Some action
}
else
// Some other action
您可以监控用户按下的键组合,并将操作与特定组合相关联。上面的代码显示用户是否按顺序按CTRL + ALT。
KeyDown事件更好的原因是因为你在按下它时正确捕获了键值。