- UID
- 3169
注册时间2005-9-17
阅读权限20
最后登录1970-1-1
以武会友
该用户从未签到
|
楼主 |
发表于 2005-12-22 10:54:16
|
显示全部楼层
回顾GDI绘制文本(五)
case WM_CHAR:
{
// get the character
char ascii_code = wparam;
unsigned int key_state = lparam;
// get a graphics context
hdc = GetDC(hwnd);
// set the foreground color to green
SetTextColor(hdc, RGB(0,255,0));
// set the background color to black
SetBkColor(hdc, RGB(0,0,0));
// set the transparency mode to OPAQUE
SetBkMode(hdc, OPAQUE);
// print the ascii code and key state
sprintf(buffer,"WM_CHAR: Character = %c ",ascii_code);
TextOut(hdc, 0,0, buffer, strlen(buffer));
sprintf(buffer,"Key State = 0X%X ",key_state);
TextOut(hdc, 0,16, buffer, strlen(buffer));
// release the dc back
ReleaseDC(hwnd, hdc);
} break;
---------------------------------------------------------------
上面是一个检测按键消息的测试,使用WM_CHAR方式,wparam包含ascII码,lparam包含状态量
按键又一消息方式为
WM_KEYDOWN和WM_KEYUP
他们所不同的是一个跟踪按下的状态、一个跟踪松开时的状态
他们与WM_CHAR所不同的是wparam包含的不是ascII码而是虚拟键码,lparam包含的也是状态量
例如可以通过;
int virtual_code = (int)wparam;
switch(virtual_code)
{
case VK_RIGHT:
{
//do someting
}break;
……………………
default:break;
}
这样的方式来检测按键所发生的事情.
------------------------------------------------------
还有一种就是用Win32的函数GetAsyncKeyState等这一类的函数检测键盘状态
游戏大师中定义的宏
#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
改函数的好处在于没有和事件循环耦合,可以随意的测试按键
例如:
// enter main event loop, but this time we use PeekMessage()
// instead of GetMessage() to retrieve messages
while(TRUE)
{
// test if there is a message in queue, if so get it
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
// test if this is a quit
if (msg.message == WM_QUIT)
break;
// translate any accelerator keys
TranslateMessage(&msg);
// send the message to the window proc
DispatchMessage(&msg);
} // end if
// main game processing goes here
// get a graphics context
hdc = GetDC(hwnd);
// set the foreground color to green
SetTextColor(hdc, RGB(0,255,0));
// set the background color to black
SetBkColor(hdc, RGB(0,0,0));
// set the transparency mode to OPAQUE
SetBkMode(hdc, OPAQUE);
// print out the state of each arrow key
sprintf(buffer,"Up Arrow: = %d ",KEYDOWN(VK_UP));
TextOut(hdc, 0,0, buffer, strlen(buffer));
sprintf(buffer,"Down Arrow: = %d ",KEYDOWN(VK_DOWN));
TextOut(hdc, 0,16, buffer, strlen(buffer));
sprintf(buffer,"Right Arrow: = %d ",KEYDOWN(VK_RIGHT));
TextOut(hdc, 0,32, buffer, strlen(buffer));
sprintf(buffer,"Left Arrow: = %d ",KEYDOWN(VK_LEFT));
TextOut(hdc, 0,48, buffer, strlen(buffer));
// release the dc back
ReleaseDC(hwnd, hdc);
} // end while
以上是在主循环中利用定义的宏不停的测试按键消息 |
|