你能在XNA中打开NumLock吗

本文关键字:NumLock XNA | 更新日期: 2023-09-27 18:27:02

你能在XNA中打开NumLock吗?

(我正在寻找XNA数字锁定影响输入的解决方案。)

你能在XNA中打开NumLock吗

您必须p/InvokeSendInput。这在一定程度上涉及到:

void ToggleNumLock() {
    var inputSequence = new INPUT[2]; // one keydown, one keyup = one keypress
    inputSequence[0].type = 1; // type Keyboard
    inputSequence[1].type = 1;
    inputSequence[0].U.wVk = 0x90; // keycode for NumLock
    inputSequence[1].U.wVk = 0x90;
    inputSequence[1].U.dwFlags |= KEYEVENTF.KEYUP;
    var rv = SendInput(2, inputSequence, INPUT.Size);
    if (rv != 2)
    {
        throw new InvalidOperationException("Call to SendInput failed");
    }
}
void EnsureNumLockIsOn() {
   bool numLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
   if (!numLock) {
       ToggleNumLock();
   }
}

以下是相关定义:

using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern uint SendInput(UInt32 nInputs, 
    INPUT[] pInputs,
    int cbSize);
[DllImport("user32.dll")]
static extern short GetKeyState(int keyCode);
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
  internal uint type;
  internal KEYBDINPUT U;
  internal static int Size
  {
   get { return Marshal.SizeOf(typeof(INPUT)); }
  }
}
[StructLayout(LayoutKind.Sequential)]
internal struct KEYBDINPUT
{
    internal short wVk;
    internal short wScan;
    internal KEYEVENTF dwFlags;
    internal int time;
    internal UIntPtr dwExtraInfo;
    uint unused1;
    uint unused2;
}
[Flags]
internal enum KEYEVENTF : uint
{
    EXTENDEDKEY = 0x0001,
    KEYUP = 0x0002,
    SCANCODE = 0x0008,
    UNICODE = 0x0004
}

我不知道这是否是你想要的,但我找到了这篇文章。

为了知道是否大写锁定、数字锁定或滚动锁定键打开时,我们需要通过调用非托管函数。

由于我们将调用一个非托管函数,因此以下使用语句按顺序排列:

using System.Runtime.InteropServices;

以下是我们将要使用的非托管函数的定义使用,GetKeyState():

// An unmanaged function that retrieves the states of each key
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
// Get they key state and store it as bool
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;