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?
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?
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;
If you are working on Windows.Forms, you can use:
Control.IsKeyLocked (Keys.CapsLock);
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;