Advertisement
keybode

Input.cpp

Jan 22nd, 2015 (edited)
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include "Input.h"
  2.  
  3. CInput* g_pInput = new CInput();
  4.  
  5. CInput::CInput() {
  6.  
  7. }
  8.  
  9. CInput::~CInput() {
  10.     RemoveHook();
  11. }
  12.  
  13. HWND hGameWnd = NULL;
  14.  
  15. BOOL WINAPI EnumWnd(HWND hWnd, LPARAM lParam) {
  16.     DWORD dwProcessId = NULL;
  17.  
  18.     GetWindowThreadProcessId(hWnd, &dwProcessId);
  19.  
  20.     if (dwProcessId == lParam) {
  21.         hGameWnd = hWnd;
  22.         return FALSE;
  23.     }
  24.  
  25.     return TRUE;
  26. }
  27.  
  28. void CInput::SetupHook() {
  29.     EnumWindows(EnumWnd, GetCurrentProcessId());
  30.  
  31.     if (!(m_WndOriginal = (WndProcFn)SetWindowLongPtr(hGameWnd, -4, (LONG_PTR)this->WndHook))) {
  32.         DbgPrint(PREFIX"Failed to install keyboard hook!");
  33.     }
  34. }
  35.  
  36. void CInput::RemoveHook() {
  37.     SetWindowLongPtr(hGameWnd, -4, (LONG_PTR)this->m_WndOriginal);
  38. }
  39.  
  40. LRESULT WINAPI CInput::WndHook(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
  41.     BOOL bUpdate = FALSE;
  42.     BOOL bIsDown = FALSE;
  43.  
  44.     if (message == WM_KEYDOWN) {
  45.         bUpdate = TRUE;
  46.         bIsDown = TRUE;
  47.     } else if (message == WM_KEYUP) {
  48.         bUpdate = TRUE;
  49.         bIsDown = FALSE;
  50.     }
  51.  
  52.     WORD wVk = LOWORD(wParam);
  53.    
  54.     g_pInput->UpdateAsyncKeyState(wVk, bIsDown);
  55.  
  56.     return g_pInput->m_WndOriginal(hWnd, message, wParam, lParam);
  57. }
  58.  
  59. WORD CInput::GetKeyState(int Key) {
  60.     WORD wRet = 0;
  61.  
  62.     if (Key >= 0x100) {
  63.         return 0;
  64.     }
  65.  
  66.     if (IS_KEY_DOWN(m_AsyncKeyState, Key)) {
  67.         wRet |= 0x8000;
  68.     }
  69.     if (m_AsyncKeyStateRecentDown[Key / 8] & (1 << (Key % 8))) {
  70.         wRet |= 0x1;
  71.     }
  72.  
  73.     m_AsyncKeyStateRecentDown[Key / 8] &= ~(1 << (Key % 8));
  74.  
  75.     return wRet;
  76. }
  77.  
  78. void CInput::UpdateAsyncKeyState(WORD wVk, BOOL bIsDown) {
  79.     if (bIsDown) {
  80.         if (!IS_KEY_DOWN(m_AsyncKeyState, wVk)) {
  81.             SET_KEY_LOCKED(m_AsyncKeyState, wVk, !IS_KEY_LOCKED(m_AsyncKeyState, wVk));
  82.         }
  83.  
  84.         SET_KEY_DOWN(m_AsyncKeyState, wVk, TRUE);
  85.  
  86.         m_AsyncKeyStateRecentDown[wVk / 8] |= (1 << (wVk % 8));
  87.     } else {
  88.         SET_KEY_DOWN(m_AsyncKeyState, wVk, FALSE);
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement