如何以编程方式调用键盘按键?

2023-12-15

Problem: 从一段 C# 代码中调用要按下的键盘按键 但这里有一个问题:按键不应仅限于进程/应用程序 但由整个操作系统接收,当程序位于后台并且不同的表单/程序具有焦点时也是如此

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.


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");
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以编程方式调用键盘按键? 的相关文章

随机推荐