Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I check the state of virtual keys such as Caps Lock?

If the Control.ModifierKeys doesn't address your issue, then use P/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; } // 0xffff =~0x0000

  public static int LOWORD(int n) 
  { return n & 0xffff; } // 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 ); 

Contributed from George Shepherd's Windows Forms FAQ