Problem: Calling a keyboard key to be pressed, from a piece of C# code but here's the catch: the key-press should not be limited to the process/application but received by the entire operating system, so also when the program is in the background and a different form/program has focus
Goal: make a program that locks the state of CapsLock and NumLock
Background: I have a laptop, and these 2 keys frustrate me to much, I want to make a application that runs in the background, and that disables CapsLock as soon as it gets accidentally enabled, and for NumLock to never be disabled, also, I want to extend my knowledge about coding, I have tried to find solutions, but none of them solve the (entire) problem.
using System;
using System.Runtime.InteropServices;
public class CapsLockControl
{
public const byte VK_NUMLOCK = 0x90;
public const byte VK_CAPSLOCK = 0x14;
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
public static void Main()
{
if (Control.IsKeyLocked(Keys.CapsLock))
{
Console.WriteLine("Caps Lock key is ON. We'll turn it off");
keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
(UIntPtr) 0);
}
else
{
Console.WriteLine("Caps Lock key is OFF");
}
}
}
You'll have to hook the keyboard by using user32.dll. This codeProject sample should get you started
If you want to disable capslock from actually being pressed at all you can do that with
SetWindowsHookEx
There is plenty of information here about how to use it. For example
Global keyboard hook that doesn't disable user input outside of form
And ofcourse msdn
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
You can try a CodePlex project that simulates both Keyboard and Mouse clicks.
Its called Windows Input Simulator and it can be found Here
来源:https://stackoverflow.com/questions/15089513/how-to-call-a-keyboard-key-press-programmatically