pure841
pure841

Reputation: 11

Sending Keyboard Commands

How would I send a keyboard command, so that they press "Y", then hit enter. Thanks

Upvotes: 1

Views: 7062

Answers (3)

cplusplusguy
cplusplusguy

Reputation: 1

use something like this:

int main()
{
char ans;
cout << "question";
cin >> ans;
cin.get();
if(ans==y)
{
do something;
}
cin.get();
return0;
}

this will set the variable 'ans' to your input using the cin >> function.

Upvotes: 0

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

Here's a CodeProject Article on the matter: http://www.codeproject.com/KB/cpp/sendkeys_cpp_Article.aspx

And an msdn article describing how to do it: http://msdn.microsoft.com/en-us/library/ms171548.aspx

And Another CodeProject Article describing how to use keybd_event(): http://www.codeproject.com/KB/system/keyboard.aspx

Not sure how this works (I'm not a C++ developer), but it's supposed to send the letter "a" to notepad (you'll need to have a file open called "test.txt"): From Expert's Exchange (I added in the corrections, but I didn't try running it): http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_21119534.html

#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <iostream>

using namespace std;

void main()
{
char end;
HWND windowHandle = FindWindow(0, "test.txt - Notepad");
INPUT *key;
if(windowHandle == NULL)
 cout << "not found";
SetForegroundWindow(windowHandle);
Sleep(1000);

key = new INPUT;
key->type = INPUT_KEYBOARD;
key->ki.wVk = 41;
key->ki.dwFlags = 0;
key->ki.time = 0;
key->ki.wScan = 0;
key->ki.dwExtraInfo = 0;

SendInput(1,key,sizeof(INPUT));

key->ki.dwExtraInfo = KEYEVENTF_KEYUP;

SendInput(1,key,sizeof(INPUT));
cout << "key inputted";
cin >> end;
}

Upvotes: 2

Dean Harding
Dean Harding

Reputation: 72658

im making a simple hang man, and when they get down to the last letter, it types it for them if they have been perfect so far

You're making this way too complicated if you're trying to simulate a keyboard press just to implement this.

Presumably, in your code you have something like:

void OnKeyPress(char key)
{
    // handle the key: is it correct, etc?
}

All you need to do is call that method directly when they get to the last letter and are perfect so far. You do not need to "simulate" a keyboard event at all.

Upvotes: 1

Related Questions