如果您想要模拟Windows消息的处理方式,那么您可能需要了解按键重复速率有多快。可以在注册表路径HKEY_CURRENT_USER\Control Panel\Keyboard\KeyboardSpeed中找到该值。还有一个名为KeyboardDelay的数值。
Windows会在按键初始按下时发送WM_KEYDOWN和WM_CHAR消息。然后,如果在KeyboardDelay时间段之后仍然按住该键,则每隔KeyboardSpeed时间间隔就会重复发送WM_KEYDOWN和WM_CHAR消息,直到松开该键,此时将发送WM_KEYUP消息。
建议使用计时器以特定频率发送消息。
更新:
例如:
int keyboardDelay, keyboardSpeed;
using (var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Keyboard"))
{
Debug.Assert(key != null);
keyboardDelay = 1;
int.TryParse((String)key.GetValue("KeyboardDelay", "1"), out keyboardDelay);
keyboardSpeed = 31;
int.TryParse((String)key.GetValue("KeyboardSpeed", "31"), out keyboardSpeed);
}
maxRepeatedCharacters = 30;
var startTimer = new System.Windows.Forms.Timer {Interval = keyboardSpeed};
startTimer.Tick += startTimer_Tick;
startTimer.Start();
var repeatTimer = new System.Windows.Forms.Timer();
repeatTimer.Interval += keyboardDelay;
repeatTimer.Tick += repeatTimer_Tick;
private static void repeatTimer_Tick(object sender, EventArgs e)
{
PostMessage(MemoryHandler.GetMainWindowHandle(),
(int)KeyCodes.WMessages.WM_KEYDOWN,
(int)KeyCodes.VKeys.VK_TAB, 0);
PostMessage(MemoryHandler.GetMainWindowHandle(),
(int)KeyCodes.WMessages.WM_CHAR,
(int)KeyCodes.VKeys.VK_TAB, 0);
counter++;
if (counter > maxRepeatedCharacters)
{
Timer timer = sender as Timer;
timer.Stop();
}
}
private static void startTimer_Tick(object sender, EventArgs eventArgs)
{
Timer timer = sender as Timer;
timer.Stop();
PostMessage(MemoryHandler.GetMainWindowHandle(),
(int)KeyCodes.WMessages.WM_KEYDOWN,
(int)KeyCodes.VKeys.VK_TAB, 0);
PostMessage(MemoryHandler.GetMainWindowHandle(),
(int)KeyCodes.WMessages.WM_CHAR,
(int)KeyCodes.VKeys.VK_TAB, 0);
}
PostMessage
,所以我不太确定可能会有什么副作用。 - keyboardPSystemInformation.KeyboardRepeat
,我们不应该使用任意时间周期进行自动重复,否则这不是真正的模拟。 - King King