How to call a keyboard key press programmatically?

流过昼夜 提交于 2019-12-01 20:52:08

问题


Problem: Calling a keyboard key to be pressed, from a piece of C# code but here's the catch: the key-press should not be limited to the process/application but received by the entire operating system, so also when the program is in the background and a different form/program has focus

Goal: make a program that locks the state of CapsLock and NumLock

Background: I have a laptop, and these 2 keys frustrate me to much, I want to make a application that runs in the background, and that disables CapsLock as soon as it gets accidentally enabled, and for NumLock to never be disabled, also, I want to extend my knowledge about coding, I have tried to find solutions, but none of them solve the (entire) problem.


回答1:


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");
        }
    }
}



回答2:


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




回答3:


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




回答4:


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

Its called Windows Input Simulator and it can be found Here



来源:https://stackoverflow.com/questions/15089513/how-to-call-a-keyboard-key-press-programmatically

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