simulate Alt Tab keyboard press in C++ to launch Fast Switch window

4.8k Views Asked by At

I have an idea for a project which needs to be run on a touch screen device. The idea is to have a button on screen which when pressed switches between open projects. So exactly how the ALT + TAB keyboard shortcut works. I know the SendKeys::Send() event in C++ can simulate key presses but it doesn't seem to work for me when I try sending ALT + TAB. So is there a way that I can have the window displaying all open programs (just like when ALT TAB is pressed) through C++ ?

PS The project is a Windows application! Windows 7 to begin but hopefully it can be compatible with more Windows systems later.

1

There are 1 best solutions below

1
On

Assuming C++/CLI since you mentioned SendKeys. SendKeys cannot work reliably because it releases the keys, making the Alt-Tab window disappear. You want to use SendInput() instead and send a keydown for the Alt key and a keydown + up for the Tab key. This code worked well:

#include <windows.h>
#pragma comment(lib, "user32.lib")

...
    System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        INPUT input = {INPUT_KEYBOARD};
        input.ki.wVk = (WORD)Keys::Menu;
        UINT cnt = SendInput(1, &input, sizeof(input));
        input.ki.wVk = (WORD)Keys::Tab;
        if (cnt == 1) cnt = SendInput(1, &input, sizeof(input));
        input.ki.dwFlags = KEYEVENTF_KEYUP;
        if (cnt == 1) cnt = SendInput(1, &input, sizeof(input));
        if (cnt != 1) throw gcnew System::ComponentModel::Win32Exception;
    }