欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#控制键盘按键的常用方法

程序员文章站 2022-08-03 21:51:35
本文实例讲述了c#控制键盘按键的常用方法。分享给大家供大家参考。具体实现方法如下: using system; using system.collections...

本文实例讲述了c#控制键盘按键的常用方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
namespace sn设置键盘大小写
{
  public partial class form1 : form
  {
    const uint keyeventf_extendedkey = 0x1;
    const uint keyeventf_keyup = 0x2;
    [dllimport("user32.dll")]
    static extern short getkeystate(int nvirtkey);
    [dllimport("user32.dll")]
    static extern void keybd_event(byte bvk, byte bscan, uint dwflags, uint dwextrainfo);
    public enum virtualkeys : byte
    {
      vk_numlock = 0x90, //数字锁定键
      vk_scroll = 0x91, //滚动锁定
      vk_capital = 0x14, //大小写锁定
      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);
      }
    }
    //开启键盘大写
    private void btnopencapital_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_capital, true);
    }
    //关闭键盘大写
    private void btnclosecapital_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_capital, false);
    }
    //开启键盘滚动锁定
    private void btnopenscroll_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_scroll, true);
    }
    //关闭键盘滚动锁定
    private void btnclosescroll_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_scroll, false);
    }
    //开启键盘数字锁定键
    private void btnopennum_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_numlock, true);
    }
    //关闭键盘数字锁定键
    private void btnclosenum_click(object sender, eventargs e)
    {
      setstate(virtualkeys.vk_numlock, false);
    }
  }
}

希望本文所述对大家的c#程序设计有所帮助。