[英]How can I check and toggle Num-Lock programmatically in C#?
我想以編程方式檢查 num-lock 的值,並能夠切換。 在 C# 中最簡單的方法是什么?
原因是我想在程序啟動時驗證 num-lock 是否為“ON”。
謝謝
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);
}
您可以通過P / Invoke和GetKeyboardState以及keybd_event來完成此操作。
keybd_event的MSDN頁面顯示了如何切換num-lock以及獲取它的狀態(在C ++中)。
pinvoke.net上有針對keybd_event和GetKeyboardState的 P / Invoke簽名。
除了Arsen給出的答案:
在 64 位構建中存在堆損壞問題。 使用此代碼的程序可能隨時崩潰。 要查看這一點,請啟用調試選項“啟用 Windows 調試堆分配器”。 調試器在調用 FreeHGlobal 時停止。
它有助於計算 INPUT 結構的大小,如下所示。
int mouseInpSize = Marshal.SizeOf(input);
IntPtr pI = Marshal.AllocHGlobal(mouseInpSize);
Marshal.StructureToPtr(input, pI, false);
int result = SendInput(2, pI, mouseInpSize);
Marshal.FreeHGlobal(pI);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.