如何以编程方式调用键盘按键? [英] How to call a keyboard key press programmatically?
问题描述
问题: 从一段C#代码中调用要按下的键盘键 但要注意的是:按键不应该局限于流程/应用程序 但会被整个操作系统接收,因此当程序在后台运行且具有不同的窗体/程序具有焦点时也是如此
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
目标: 制作一个程序来锁定 CapsLock 和 NumLock
Goal: make a program that locks the state of CapsLock and NumLock
背景: 我有一台笔记本电脑,这两个键让我非常沮丧,我想制作一个在后台运行的应用程序,并在意外启用后立即禁用 CapsLock ,并且对于 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");
}
}
}
这篇关于如何以编程方式调用键盘按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!