SoFunction
Updated on 2025-03-06

Common methods for controlling keyboard keys in C#

This article describes the common methods of C# controlling keyboard keys. Share it for your reference. The specific implementation method is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace snSet keyboard case
{
  public partial class Form1 : Form
  {
    const uint KEYEVENTF_EXTENDEDKEY = 0x1;
    const uint KEYEVENTF_KEYUP = 0x2;
    [DllImport("")]
    static extern short GetKeyState(int nVirtKey);
    [DllImport("")]
    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
    public enum VirtualKeys : byte
    {
      VK_NUMLOCK = 0x90, //Number lock key      VK_SCROLL = 0x91, //Scroll lock      VK_CAPITAL = 0x14, //Case lock      VK_A = 62
    }
    public Form1()
    {
      InitializeComponent();
    }
    public static bool GetState(VirtualKeys Key)
    {
      return (GetKeyState((int)Key)==1);
    }
    public static void SetState(VirtualKeys Key, bool State)
    {
      if (State != GetState(Key))
      {
        keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
        keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
      }
    }
    //Open the keyboard capitalization    private void btnOpenCAPITAL_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_CAPITAL, true);
    }
    //Close the keyboard capitalization    private void btnCloseCAPITAL_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_CAPITAL, false);
    }
    //Open keyboard scroll lock    private void btnOpenScroll_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_SCROLL, true);
    }
    //Close keyboard scroll lock    private void btnCloseScroll_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_SCROLL, false);
    }
    //Open the keyboard number lock key    private void btnOpenNum_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_NUMLOCK, true);
    }
    //Close the keyboard number lock key    private void btnCloseNum_Click(object sender, EventArgs e)
    {
      SetState(VirtualKeys.VK_NUMLOCK, false);
    }
  }
}

I hope this article will be helpful to everyone's C# programming.