SamKr
12/4/2014 - 12:29 PM

Manage NumLock

Manage NumLock

[StructLayout(LayoutKind.Sequential)]
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;
}

[DllImport("user32.dll")]
static extern int SendInput(uint nInputs, IntPtr pInputs, int cbSize);


private void CheckLoop()
{
	while (true)
	{
		try
		{
			if (!NumlockActive()) 
			{
				const int mouseInpSize = 28;
				INPUT input = new INPUT();
				input.type = 0x01;
				input.wVk = 0x90;
				input.wScan = 0;
				input.dwFlags = 0;
				input.time = 0;
				input.dwExtraInfo = IntPtr.Zero;

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

				IntPtr pI = Marshal.AllocHGlobal(mouseInpSize * 2);
				Marshal.StructureToPtr(input, pI, false);
				int result = SendInput(2, pI, mouseInpSize);

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

				Marshal.FreeHGlobal(pI);
			}
		}
		catch { }

		Thread.Sleep(500);
	}
}

private bool NumlockActive()
{
	return Control.IsKeyLocked(Keys.NumLock);
}