[英]Change the key being pressed with C#
嘿,我正在嘗試用C#編寫一個程序來跟蹤某些鍵的按下(使用鍵盤鈎子),然后發送不同的鍵。
例如,當我按下A鍵時,它將發送Q鍵。
我使用http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx這個用於我的鈎子並試圖使用SendKeys函數,但是我得到一個關於垃圾收集器的例外,它破壞了鈎子類中的一些對象。
首先,您需要連接鍵。
使用此類,您可以注冊一個全局快捷方式,我正在跳過解釋,但您可以在此處閱讀 。
public class KeyboardHook
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public enum Modifiers
{
None = 0x0000,
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Win = 0x0008
}
int modifier;
int key;
IntPtr hWnd;
int id;
public KeyboardHook(int modifiers, Keys key, Form f)
{
this.modifier = modifiers;
this.key = (int)key;
this.hWnd = f.Handle;
id = this.GetHashCode();
}
public override int GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}
public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
}
然后在您的表單上,您必須注冊快捷方式
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
KeyboardHook hook = new KeyboardHook((int)KeyboardHook.Modifiers.None, Keys.A, this);
hook.Register(); // registering globally that A will call a method
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312)
HandleHotkey(); // A, which was registered before, was pressed
base.WndProc(ref m);
}
private void HandleHotkey()
{
// instead of A send Q
KeyboardManager.PressKey(Keys.Q);
}
}
這里是管理Keyboard
按下和釋放事件的類。
public class KeyboardManager
{
public const int INPUT_KEYBOARD = 1;
public const int KEYEVENTF_KEYUP = 0x0002;
public struct KEYDBINPUT
{
public Int16 wVk;
public Int16 wScan;
public Int32 dwFlags;
public Int32 time;
public Int32 dwExtraInfo;
public Int32 __filler1;
public Int32 __filler2;
}
public struct INPUT
{
public Int32 type;
public KEYDBINPUT ki;
}
[DllImport("user32")]
public static extern int SendInput(int cInputs, ref INPUT pInputs, int cbSize);
public static void HoldKey(Keys vk)
{
INPUT input = new INPUT();
input.type = INPUT_KEYBOARD;
input.ki.dwFlags = 0;
input.ki.wVk = (Int16)vk;
SendInput(1, ref input, Marshal.SizeOf(input));
}
public static void ReleaseKey(Keys vk)
{
INPUT input = new INPUT();
input.type = INPUT_KEYBOARD;
input.ki.dwFlags = KEYEVENTF_KEYUP;
input.ki.wVk = (Int16)vk;
SendInput(1, ref input, Marshal.SizeOf(input));
}
public static void PressKey(Keys vk)
{
HoldKey(vk);
ReleaseKey(vk);
}
}
我已經在我正在寫的這個textarea上測試了它,當我按下A
它正在發送Q
我不確定魔獸爭霸III會有什么行為,也許他們已經封鎖了以防止某種機器人或什么......
當你看看你的鈎子類時,問題的根源是什么? 這聽起來像是一個沒有正確管理的資源。
要意識到如果你打算把它當成某種惡作劇,那么這些笑話永遠不會好轉,因為通常無法解決這些問題。 同時也認識到這種看似不道德的話題不太可能得到很多支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.