程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 用C#程序實現鍵盤和鼠標的模擬

用C#程序實現鍵盤和鼠標的模擬

編輯:.NET實例教程
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
);
}
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved