使用C#打开Caps lock键

     在.net winform应用程序中如何打开capslock 键呢?或者在程序启动的时候,capslock键就变亮了呢,今天在国外的一个论谈看到了解决方案,事实上很简单的.我们只要DllImport attribute 去调用系统的函数就可以了.部分代码如下:

        private void Form1_Load(object sender, EventArgs e)
        {
            const int KEYEVENTF_EXTENDEDKEY = 0x1;
            const int KEYEVENTF_KEYUP = 0x2;
            keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
            keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
            (UIntPtr)0);

        }

        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
        UIntPtr dwExtraInfo);

当热行load的时候,Caps Lock的灯就亮了。呵呵。

DllImport..顾名思议.就是导入Dll文件.让C# 可以调用系统的的API.user32.dll是用户界面的一个API.据说SendKeys()这个方法也可以实现类似的功能。但我试过却没有效果。

那么如何等获得caps lock 的状态呢:

// An umanaged function that retrieves the states of each key

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]

public static extern short GetKeyState(int keyCode);

 

bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;

bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;

bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;

 

// Show the status

MessageBox.Show("Caps Lock is on: " + CapsLock.ToString());

MessageBox.Show("Num Lock is on: " + NumLock.ToString());

MessageBox.Show("Scroll Lock is on: " + ScrollLock.ToString());

你可能感兴趣的:(Lock)