How to programmatically turn on the Numlock Key

7 11 2008

The following code will allow you to turn on the numlock key upon startup. Can’t credit anyone as i’m not sure where it came from but it does work 100%

using System;
using System.Runtime.InteropServices;

class SetNumlockKeyOn
public struct INPUT
internal int type;
internal short wVk;
internal short wScan;
internal int dwFlags;
internal int time;
internal IntPtr dwExtraInfo;
int dummy1;
int dummy2;
internal int type1;
internal short wVk1;
internal short wScan1;
internal int dwFlags1;
internal int time1;
internal IntPtr dwExtraInfo1;
int dummy3;
int dummy4;
static extern int SendInput(uint nInputs, IntPtr pInputs, int cbSize);

public static void SetNumlockOn()
const int mouseInpSize = 28;//Hardcoded size of the MOUSEINPUT tag !!!
INPUT input = new INPUT();
input.type = 0x01; //INPUT_KEYBOARD
input.wVk = 0x90; //VK_NUMLOCK
input.wScan = 0;
input.dwFlags = 0; //key-down
input.time = 0;
input.dwExtraInfo = IntPtr.Zero;

input.type1 = 0x01;
input.wVk1 = 0x90;
input.wScan1 = 0;
input.dwFlags1 = 2; //key-up
input.time1 = 0;
input.dwExtraInfo1 = IntPtr.Zero;

IntPtr pI = Marshal.AllocHGlobal(mouseInpSize * 2);
Marshal.StructureToPtr(input, pI, false);
int result = SendInput(2, pI, mouseInpSize); //Hardcoded size of the MOUSEINPUT tag !!!

//if (result == 0 || Marshal.GetLastWin32Error() != 0)
// Console.WriteLine(Marshal.GetLastWin32Error());




One response

7 11 2008
Simon Steed

Just noticed that this will turn it on if it’s already off and vice versa SOOOOOOOOOO if you want to put a check in there, add the following code:

internal static extern short GetKeyState(int keyCode);

bool NumLock = (GetKeyState((int)System.Windows.Forms.Keys.NumLock)) != 0; // check if key is already down
if (!NumLock) // if already down dont proceed
// do you stuff

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: