vc 判断哪个按键 被按下 消息 按键 状态

时间:2022-09-03 10:00:14

测试Numlock 是否是亮的

环境控制台程序;

#include "stdafx.h"

#include <stdio.h>

#include <conio.h>

#include <windows.h>

bool CrnGetNumLockState();

int _tmain(int argc, _TCHAR* argv[])

{

if(CrnGetNumLockState())

   printf("NUM-Lock is light\n");

else

   printf("Num-Lock is light-off\n");

getch();

return 0;

}

bool CrnGetNumLockState()

{

    BYTE btKeyState[256];

    GetKeyboardState((LPBYTE)&btKeyState);

return btKeyState[VK_NUMLOCK] & 1;

}

判断哪个按键被按下

MFC

BOOL CDemoDlg::PreTranslateMessage(MSG* pMsg)

{

// TODO: 在此添加专用代码和/或调用基类

// 假如截获键盘按下消息,就分析按下的哪个键,然后给相应的按钮发送消息

if(pMsg->message==WM_KEYDOWN)

{

   UINT iKey=(UINT)pMsg->wParam;

   switch(iKey)

   {

   case VK_NUMPAD0:

{

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "0");

     CString key = "VK_NUMPAD0";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD1:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "1");

     CString key = "VK_NUMPAD1";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD2:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "2");

     CString key = "VK_NUMPAD2";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD3:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "3");

     CString key = "VK_NUMPAD3";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD4:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "4");

     CString key = "VK_NUMPAD4";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD5:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "5");

     CString key = "VK_NUMPAD5";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD6:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "6");

     CString key = "VK_NUMPAD6";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD7:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "7");

     CString key = "VK_NUMPAD7";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD8:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "8");

     CString key = "VK_NUMPAD8";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

   case VK_NUMPAD9:

    {

     HWND hwnd = ::GetDlgItem(m_hWnd,IDC_EDIT_IN);

::SetWindowText(hwnd, "9");

     CString key = "VK_NUMPAD9";

     KeyRun(key);

     ::SetFocus(m_hWnd);

    }

    break;

default:

    break;

   }

}

return CDialog::PreTranslateMessage(pMsg);

}