我想以编程方式检查num-lock的值,并能够切换num-lock。在C#中做这件事最简单的方法是什么?
原因是我想在程序启动时验证num-lock是否为"ON“。
谢谢
发布于 2009-08-28 15:23:57
检查How to programmatically turn on the Numlock Key
using System;
using System.Runtime.InteropServices;
class SetNumlockKeyOn
{
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
internal int type;
internal short wVk;
internal short wScan;
internal int dwFlags;
internal int time;
internal IntPtr dwExtraInfo;
int dummy1;
int dummy2;
internal int type1;
internal short wVk1;
internal short wScan1;
internal int dwFlags1;
internal int time1;
internal IntPtr dwExtraInfo1;
int dummy3;
int dummy4;
}
[DllImport(“user32.dll”)]
static extern int SendInput(uint nInputs, IntPtr pInputs, int cbSize);
public static void SetNumlockOn()
{
const int mouseInpSize = 28;//Hardcoded size of the MOUSEINPUT tag !!!
INPUT input = new INPUT();
input.type = 0x01; //INPUT_KEYBOARD
input.wVk = 0x90; //VK_NUMLOCK
input.wScan = 0;
input.dwFlags = 0; //key-down
input.time = 0;
input.dwExtraInfo = IntPtr.Zero;
input.type1 = 0x01;
input.wVk1 = 0x90;
input.wScan1 = 0;
input.dwFlags1 = 2; //key-up
input.time1 = 0;
input.dwExtraInfo1 = IntPtr.Zero;
IntPtr pI = Marshal.AllocHGlobal(mouseInpSize * 2);
Marshal.StructureToPtr(input, pI, false);
int result = SendInput(2, pI, mouseInpSize); //Hardcoded size of the MOUSEINPUT tag !!!
//if (result == 0 || Marshal.GetLastWin32Error() != 0)
// Console.WriteLine(Marshal.GetLastWin32Error());
Marshal.FreeHGlobal(pI);
}发布于 2009-08-28 15:25:45
您可以通过带有GetKeyboardState和keybd_event的P/Invoke来实现这一点。
keybd_event的MSDN页面确切地展示了如何切换num-lock,以及如何获取它的状态(在C++中)。
在用于keybd_event和GetKeyboardState的pinvoke.net上提供了P/Invoke签名。
发布于 2022-02-02 16:28:50
除了Arsen给出的答案之外:
64位版本中存在堆损坏问题。使用此代码的程序可能在任何时候崩溃。要查看此信息,请启用调试选项"Enable Windows debug heap allocator“。调试器在调用FreeHGlobal时停止。
它有助于计算输入结构的大小,如下所示。
int mouseInpSize = Marshal.SizeOf(input);
IntPtr pI = Marshal.AllocHGlobal(mouseInpSize);
Marshal.StructureToPtr(input, pI, false);
int result = SendInput(2, pI, mouseInpSize);
Marshal.FreeHGlobal(pI);https://stackoverflow.com/questions/1347688
复制相似问题