Live Chat Icon For mobile
Live Chat Icon

How do I check the state of the virtual keys, Caps lock for example?

Platform: WinForms| Category: Keyboard Handling

If the Control.ModifierKeys doesn’t address your issue, then use Platform Invoke and call GetKeyState directly.

Declare this class first:


[
ComVisibleAttribute(false),
SuppressUnmanagedCodeSecurityAttribute()
]
internal class NativeMethods
{
	[DllImport('user32.dll', CharSet=CharSet.Auto, ExactSpelling=true, CallingConvention=CallingConvention.Winapi)] 
	public static extern short GetKeyState(int keyCode); 

	public static int HIWORD(int n)
	{
		return ((n >> 16) & 0xffff/*=~0x0000*/);
	} 

	public static int LOWORD(int n)
	{
		return (n & 0xffff/*=~0x0000*/);
	} 
}

Then when you want to check if Caps is down or ON, call:


short state = NativeMethods.GetKeyState(0x14 /*VK_CAPTIAL*/);

bool capsKeyDown = NativeMethods.HIWORD(state);
bool capsKeyON = NativeMethods.LOWORD(state);

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.