Detect status of Caps Lock in c #

3

I have a password field in a Windows Form of C# and I need to show the user an alert if the CapsLock function is enabled.

How can I detect if the CapsLock function is activated?

    
asked by Abraham TS 27.07.2017 в 13:36
source

3 answers

5

As of version 2.0 of the .Net Framework, to detect the status of Block Lock, Number Lock and Scroll Lock, you can use Control.IsKeyLocked (Windows Forms):

Control.IsKeyLocked(Keys.CapsLock);
Control.IsKeyLocked(Keys.NumLock);
Control.IsKeyLocked(Keys.Scroll);

Another option is to use the Windows API, importing the function GetKeyState :

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);

And you can use it in the following way:

bool BloqDesp = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;     
bool BloqMay = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool BloqNum = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
    
answered by 27.07.2017 / 13:54
source
2

If you are working on Windows.Forms, you can use:

Control.IsKeyLocked (Keys.CapsLock);

    
answered by 27.07.2017 в 13:54
2

You have several options.

The .Net Framework option:

Control.IsKeyLocked(Keys.CapsLock);

Or the option for calls to the Windows API:

//Defines la llamada a la función
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);

//Y luego llamas a la función con el code de la tecla en este caso BloqCaps
bool mayusActivado = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
    
answered by 27.07.2017 в 13:56