Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey All,

I am trying to capture Num lock and Caps Lock keys of keyboard for User Information in MDI Form

So There is a way to identify keys on/off.

This Caps and Num lock Status are also changed as per the Key Pressed and IF there Short way because Key Up and Down keys are put in the MDI Form and it may increase a load of project.


Regards....
Amit Tank
Posted
Updated 28-Dec-10 23:26pm
v3

Try:
C#
using System.Runtime.InteropServices;
...
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
    ...

    // Get they key state and store it as bool
    bool CapsLock = (((ushort) GetKeyState(0x14)) & 0xffff) != 0;
    bool NumLock = (((ushort) GetKeyState(0x90)) & 0xffff) != 0;
    bool ScrollLock = (((ushort) GetKeyState(0x91)) & 0xffff) != 0;
 
Share this answer
 
Here you go:

http://msdn.microsoft.com/en-us/library/ms646314[^]

Code here:

C#
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class CapsLockControl
{
    [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(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
            keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                (UIntPtr) 0);
        }
        else
        {
            Console.WriteLine("Caps Lock key is OFF");
        }
    }
}
 
Share this answer
 
Comments
Toli Cuturicu 17-Dec-10 15:13pm    
While your code works, it does not do what the OP asked for.
He did not want to set or toggle caps lock status.
He simply wanted to retrieve it.
See the correct answer above.
Wild-Programmer 17-Dec-10 15:34pm    
You are right, my answer deviated from the point.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900