简体   繁体   中英

Can you turn NumLock on in XNA?

Can you turn NumLock on in XNA?

(I'm looking for a solution to XNA Number lock affects input .)

You'll have to P/Invoke SendInput . This is somewhat involved:

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();
   }
}

Here are the relevant definitions:

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
}

I don't know if this is that you are looking for, but I found this article .

In order to know whether or not Caps Lock, Num Lock or Scroll Lock keys are on, we need to make use of the Win32 API through a call to an unmanaged function.

Since we'll make a call to an unmanaged function, the following using statement is in order:

using System.Runtime.InteropServices;

The following is the definition for the unmanaged function we'll be using, 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM