以编程方式检测按键的更好方法? [英] Better Way to programmatically detect a key press?

查看:67
本文介绍了以编程方式检测按键的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用此

while (1)
    {
        if (GetAsyncKeyState(VK_F1))
        {
        //do something
        }
    }

检测用户是否按下某个键,在这种情况下为F1.我发现这会消耗很多CPU使用率,我的问题是,有没有更好的方法来检测按键按下情况?

to detect if a user presses a certain key, in this case F1. I've found that this eats up cpu usage by quite a bit, my question is, is there a better way to detect key presses?

推荐答案

更好的方法是使用WndProc().因此,请使用标准的WM_KEYDOWN/WM_KEYUP消息来处理键盘输入.这是一个示例:

The better way of doing this is using your WndProc(). So use standard WM_KEYDOWN/WM_KEYUP messages to handle keyboard input. Here is an example:

LRESULT CALLBACK WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
  switch ( uMsg )
  {
    case WM_CLOSE:
        DestroyWindow(hwnd);
    break;
    case WM_DESTROY:
        PostQuitMessage(0);
    break;
      case WM_KEYDOWN:
      if ( wParam == VK_F1 )
      {
        // Do something here
        return 0L;
      }
      break;
  }

  return DefWindowProc( hwnd, uMsg, wParam, lParam );
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    //Step 1: Registering the Window Class
    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    // lots of other attrs ...
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

    if(!RegisterClassEx(&wc))
        return 0;

    // Step 2: Creating the Window
    hwnd = CreateWindowEx(
        ...
        g_szClassName,
        ...);

    if(hwnd == NULL)
         return 0;

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    // Step 3: The Message Loop
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

这篇关于以编程方式检测按键的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆