Thursday, March 28, 2013

Ok ok... Its C++

I had to use C++ with this project because of the low level approach. I was using C# fine to capture hotkeys on screen, however in some applications (usually applications that are full screen, like a game window) the hotkeys were not registering. Well that's where C++ comes in to handle keyboard strokes at the lowest level.

This program assigns numpad 1 / numpad 4 / numpad 7 to specific window titles, in this case a game window. Which allows for fast window switching via hotkeys.


#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <winuser.h>

void SetForegroundWindowInternal(HWND hWnd)
{
if(!::IsWindow(hWnd)) return;

BYTE keyState[256] = {0};
//to unlock SetForegroundWindow we need to imitate Alt pressing
if(::GetKeyboardState((LPBYTE)&keyState))
{
if(!(keyState[VK_MENU] & 0x80))
{
::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
}
}

::SetForegroundWindow(hWnd);

if(::GetKeyboardState((LPBYTE)&keyState))
{
if(!(keyState[VK_MENU] & 0x80))
{
::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
}

int main()
{      
enum{ONE_KEYID = 1, TWO_KEYID = 2, THREE_KEYID = 3};
RegisterHotKey(0, ONE_KEYID, 0, 0x61); // register NumPad1 key as hotkey
RegisterHotKey(0, TWO_KEYID, 0, 0x64); // register NumPad4 key as hotkey
RegisterHotKey(0, THREE_KEYID, 0, 0x67); // register NumPad4 key as hotkey
MSG msg;
        HWND eqWindowSK = FindWindow(NULL, "THF Dabs SK");//Change window title name here
        HWND eqWindowMag = FindWindow(NULL, "THF Globb MAG");//example: "Untitled - Notepad"
        HWND eqWindowClr = FindWindow(NULL, "THF Errl CLR");
   
   
while(GetMessage(&msg, 0, 0, 0))
{
PeekMessage(&msg, 0, 0, 0, 0x0001);
switch(msg.message)
{
case WM_HOTKEY:
if(msg.wParam == ONE_KEYID)
{
SetForegroundWindowInternal(eqWindowSK);
printf("Activated Window 1\n");
}
if(msg.wParam == TWO_KEYID)
{
SetForegroundWindowInternal(eqWindowMag);
printf("Activated Window 2\n");
}
if(msg.wParam == THREE_KEYID)
{
SetForegroundWindowInternal(eqWindowClr);
printf("Activated Window 3\n");
            }
}
}
return 0;
}

No comments:

Post a Comment