我已经编写了一个代码,根据按下的时间(mSec),它们会按下一个键。我正在使用此question上的答案来发送关键事件。
这是代码:
www.google.com
这是用于存储键事件的对象:
public void DebugReplayKeys()
{
long startTime = 0;
Thread td = new Thread(() =>
{
int currentIndex = 0;
bool flag = true;
while (flag)
{
long ctime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
long runtime = ctime - startTime;
var rpk = recordedPressedKeys[currentIndex];
if (runtime >= rpk.eventTime)
{
//create timer for simulate key hold time??
//then release key if timer is elapsed??
Console.WriteLine(rpk.key); //gonna be replaced by (keybd_event)
currentIndex++;
}
if(currentIndex > recordedPressedKeys.Count -1)
{
flag = false;
}
}
});
td.SetApartmentState(ApartmentState.STA);
startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
td.Start();
}
现在,如何模拟按下键盘的时间?
我需要使用Timers.Timer吗?
按住class RecordedPressedKeys
{
public long eventTime;
public Keys key;
public long holdTime;
}
的向下键标记按住键,然后在计时器过去后释放键?
答案 0 :(得分:0)
这就是我想要做的。我只需要模拟按键被按下的时间。
我使用了System.Timers.Timer
。计时器过去后,发送新闻事件并发送释放事件。
public void DebugReplayKeys()
{
long startTime = 0;
Thread td = new Thread(() =>
{
int currentIndex = 0;
bool flag = true;
while (flag)
{
long ctime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
long runtime = ctime - startTime;
var rpk = recordedPressedKeys[currentIndex];
if (runtime >= rpk.eventTime)
{
var tmr = new System.Timers.Timer(Convert.ToDouble(rpk.eventTime));
tmr.AutoReset = false;
tmr.Elapsed += delegate
{
ReleaseKey(rpk.key);
};
PressKey(rpk.key);
tmr.Enabled = true;
currentIndex++;
}
if(currentIndex > recordedPressedKeys.Count -1)
{
flag = false;
}
}
});
td.SetApartmentState(ApartmentState.STA);
startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
td.Start();
}
private void PressKey(Keys key)
{
keybd_event((byte)key, 0, KEYEVENTF_EXTENDEDKEY, 0);
}
private void ReleaseKey(Keys key)
{
keybd_event((byte)key, 0, KEYEVENTF_KEYUP, 0);
}
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);