How to call a keyboard key press programmatically?

蓝咒 提交于 2019-12-01 19:11:12
using System;
using System.Runtime.InteropServices;

public class CapsLockControl
{

    public const byte VK_NUMLOCK = 0x90;
    public const byte VK_CAPSLOCK = 0x14;

    [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(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
            keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                (UIntPtr) 0);
        }
        else
        {
            Console.WriteLine("Caps Lock key is OFF");
        }
    }
}

You'll have to hook the keyboard by using user32.dll. This codeProject sample should get you started

Evelie

If you want to disable capslock from actually being pressed at all you can do that with

SetWindowsHookEx

There is plenty of information here about how to use it. For example

Global Hook Keylogger problem

Global keyboard hook that doesn't disable user input outside of form

And ofcourse msdn

http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx

You can try a CodePlex project that simulates both Keyboard and Mouse clicks.

Its called Windows Input Simulator and it can be found Here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!