Hello everybody,
First off I know I should invest in some good c++ books...well technically alot of books for alot of different languages. However this month I am dabbling in c++ again.

I am currently working in Visual C++ and trying to make a "keybind" for my program, so that when that key (lets pretend its "A") is pressed then it executes some code (which I will fill in down the road).

I've been reading through tutorial after tutorial and nothing has worked so far for me, I am guessing that this code is going to go into the .h file for the main window I have made (which is where I want it executed from).

Thank you in advance.

You need some sort of use of windows API to catch keystrokes directly (including mod-states, like ctrl and shift). With win32 API, you need to make a WindowProc function and handle the WM_KEYDOWN (Windows Message - Key-down event). Then, it is just a matter of writing a big switch-case statement for the different key shortcuts. But you do need to create a window first.

Without creating a window, you might be able to use conio.h (or curses.h for Linux).

Thanks guys for the response, I tried doing the second one and forgive me for asking this and I know it seems silly but this goes into my app.h versus going into my app.cpp right?

So what I would be writing in the end would also be:
SHORT WINAPI GetAsyncKeyState(0x41);{
// my code
}

0x41 for the A key

would that be then correct?

Sorry if these seem like really silly questions, I'm self teaching and I think I'm catching on pretty good, but just like with PHP its not so much the statements or functions that gets me its usually the structure and the order in which items need to be placed if that makes sense.....I guess the programming grammar of it all you could say.

Oh and one final question, would this second method that Mr. Roshi mentioned, will that work if my program is running in the background of another program? Ie. lets say for example I want my A key to pick up colors from a website (yes I know there are browser addons for this - but humor me). So if I had a browser open ontop and say my browser didnt have any keyboard shortcuts using the A key on the browser would this technically be able to activate the color picker in the app? If that makes sense. Or would Mike's response be a better way to go?

I use a really nice free color-grabber utility on Windows, so haven't bothered coding my own. I'd recommend searching for "keyboard focus" ... since you want your program to keep grabbing keyboard events even while other applications are in the foreground.

Thanks for the reply raptr - found some stuff on MSDN but cannot find any examples of how it should look like. This is what MSDN says it should be:

public:
static IInputElement^ Focus(
IInputElement^ element
)

So I'm guessing that the code structure in the app.h should look like:

public:
static IInputElement^ Focus(mykey)
{
     //My code for what the button will actually do
}

I could be really wrong though so I'll look up on it more tomorrow.

will that work if my program is running in the background of another program?

Absolutely. GetAsyncKeyState is perfect for implementing global hotkeys. And keyloggers :D

Here's a minimal example:

#include <windows.h>
#include <iostream>

bool IsPressed(int virtual_key)
{
    return GetAsyncKeyState(virtual_key) >> 15;
}

int main()
{
    bool key_state[256] = { 0 };

    while (true)
    {
        // hit esc to quit
        if (IsPressed(VK_ESCAPE)) break;

        for (int i = 0; i < 256; ++i)
        {
            if (IsPressed((i)))
            {
                if (key_state[i] == false)
                {
                    key_state[i] = true;
                    std::cout << i << " was pressed!" << std::endl;
                }
            }
            else
            {
                if (key_state[i] == true)
                {
                    key_state[i] = false;
                    std::cout << i << " was released!" << std::endl;
                }
            }
        }
    }

    return 0;
}

Edited 5 Years Ago by m4ster_r0shi: n/a

Comments
Excellent answer to the issue I was having

This is what I went with the compiler is giving me the following errors:
line 12 - warning 4800 - 'int': forcing value to bool 'true' or 'false'
error LNK2028: unresolved token
error LNK2019: unresolved external symbol

and line 12 is:
return GetAsyncKeyState(virtual_key) >> 15;

I can post more of the warnings/errors if need be.

#include "stdafx.h"
#include "mainwindow.h"
#include <Windows.h>
#include <iostream>

using namespace Untouchable10;

bool IsPressed(int virtual_key)
  {
      return GetAsyncKeyState(virtual_key) >> 15;
  }

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 

    // Create the main window and run it
    Application::Run(gcnew mainwindow());

    bool key_state[256] = { 0 };
      while (true)

      {
          // hit esc to quit

          if (IsPressed(VK_ESCAPE)) break;

   

          for (int i = 0; i < 256; ++i)
          {

              if (IsPressed((i)))
              {
                  if (key_state[i] == false)
                  {
                      key_state[i] = true;
                      std::cout << i << " was pressed!" << std::endl;
                  }

              }

              else
              {
                  if (key_state[i] == true)
                  {
                      key_state[i] = false;
                      std::cout << i << " was released!" << std::endl;
                  }
              }
         }
     }
    return 0;

}

Why do you use managed C++ for this? Try creating an new, empty project, then add a main.cpp file and paste the code there.

This article has been dead for over six months. Start a new discussion instead.