1

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Keith Burke
  • 137
  • 2
  • 12

1 Answers1

3

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;
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    You should send an array of 3 `INPUT` structures, so that no other keystrokes can intervene. And `System::Void` is a terrible way to write `void`. You're also checking the same error three times, instead of checking all 3 calls. But this definitely is the right direction. – Ben Voigt Nov 15 '11 at 16:00