using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApplication8{
class Class1{
[STAThread]
static void Main(string[] args){
// Display current status of keys.
Console.WriteLine(
"**BEFORE**\r\nCAP: {0}\r\nSCR: {1}\r\nNUM: {2}",
Keyboard.GetState(VirtualKeys.VK_CAPITAL)?"ON":"OFF",
Keyboard.GetState(VirtualKeys.VK_SCROLL)?"ON":"OFF",
Keyboard.GetState(VirtualKeys.VK_NUMLOCK)?"ON":"OFF"
);
// Toggle all the keys:
Keyboard.SetState(
VirtualKeys.VK_CAPITAL,
!Keyboard.GetState(VirtualKeys.VK_CAPITAL)
);
Keyboard.SetState(
VirtualKeys.VK_SCROLL,
!Keyboard.GetState(VirtualKeys.VK_SCROLL)
);
Keyboard.SetState(
VirtualKeys.VK_NUMLOCK,
!Keyboard.GetState(VirtualKeys.VK_NUMLOCK)
);
// Display new status of keys.
Console.WriteLine(
"\r\n**AFTER**\r\nCAP: {0}\r\nSCR: {1}\r\nNUM: {2}",
Keyboard.GetState(VirtualKeys.VK_CAPITAL)?"ON":"OFF",
Keyboard.GetState(VirtualKeys.VK_SCROLL)?"ON":"OFF",
Keyboard.GetState(VirtualKeys.VK_NUMLOCK)?"ON":"OFF"
);
Console.ReadLine();
}
}
public enum VirtualKeys: byte{
VK_NUMLOCK = 0x90,
VK_SCROLL = 0x91,
VK_CAPITAL = 0x14
}
class Keyboard{
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 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
);
}
}
}
}
本文地址:http://com.8s8s.com/it/it43985.htm