【发布时间】:2013-12-10 23:57:33
【问题描述】:
在控制台应用程序中使用 GetKeyState(或 GetAsyncKeyState,就此而言)时,我遇到了奇怪的行为。该应用程序的一个方面是要求用户使用 GetFileOpen 打开文件。在程序结束时,GetKeyState 会监控空格键的状态。每当按下空格键时,GetKeyState(或 GetAsyncKeyState)函数从不设置高位。如果我不调用 GetOpenFile 然后监视 GetKeyState,一切都会按预期工作。
这是两个基本场景。
场景 1:
#include <windows.h>
int main(int argc, char *argv[])
{
char filename[ 512 ] = {0};
OPENFILENAME ofn = {0};
int filenameSize = 512;
char title[1000] = {0};
strcpy(title, "Open File");
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = null;
ofn.lpstrFile = filename;
ofn.nMaxFile = filenameSize;
ofn.lpstrFilter = "All files (*.*)\0*.*\0\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.lpfnHook = NULL;
ofn.lpstrTitle = title;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
GetOpenFileName(&ofn); // filename obtained
WaitForSpaceBar(); // return value's upper bit is never set for
// GetKeyState(VK_SPACE);
return 0;
}
场景 2:
int main(int argc, char *argv[])
{
WaitForSpaceBar(); // returns immediately after spacebar is pressed
return 0;
}
WaitForSpace条形码
void WaitForSpaceBar()
{
#define KEY_PRESSED_FLAG 1
SHORT spacePressed = GetKeyState(VK_SPACE);
printf("\nPress spacebar to continue...\n");
while (!(spacePressed & KEY_PRESSED_FLAG))
{
Sleep(1);
spacePressed = GetKeyState(VK_SPACE);
// for debugging purposes only
printf("spacePressed = 0x%04x\n", spacePressed);
}
}
无论我按多少次空格键,第一个场景都会无限期地输出“spacePressed = 0x0000”。
第二种情况输出“spacePressed = 0x0000”,直到实际按下空格键。按下后,输出为“spacePressed = 0xffffff81”,程序终止。
对正在发生的事情有什么想法吗?
【问题讨论】:
-
您无法在控制台应用程序中可靠地使用 USER32 函数。 USER32 针对 Windows 的 GUI 子系统。
GetKeyState要求应用程序从其消息队列中读取关键消息。消息队列是一个 GUI 应用程序概念。 -
改用
GetAsyncKeyState。GetKeyState返回处理最后一条消息时的状态,而不是现在的状态。 -
我无法重现该问题。在这两种情况下,我都检测到空格键按下。 Windows 7,VS 2010,调试和发布版本,32 位和 64 位。
标签: winapi console-application