Simulate keystroke in command prompt

Hi,

I have a problem with simulation keystokes for the command prompt. I have tried SendInput (http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx) and the keybd_event function - Both with the same result.

The goal:
-Open a batch file (works fine)
-Type in text (my problem!)

The problem:
Command prompt does not enter text before i manually press the enter button.

Here is the program code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <Windows.h>

using namespace std;

int main ()
{
	system("Test.bat");
	Sleep(2000); 
	
	keybd_event(VkKeyScan('T'), 0,0 , 0); // 'T' Press    
    keybd_event(VkKeyScan('T'), 0, KEYEVENTF_KEYUP, 0); // 'T' Release
	keybd_event(VkKeyScan('E'), 0,0 , 0); // Press    
    keybd_event(VkKeyScan('E'), 0, KEYEVENTF_KEYUP, 0); // Release 
	keybd_event(VkKeyScan('S'), 0,0 , 0); // Press    
    keybd_event(VkKeyScan('S'), 0, KEYEVENTF_KEYUP, 0); // Release 
	keybd_event(VkKeyScan('T'), 0,0 , 0); // Press    
    keybd_event(VkKeyScan('T'), 0, KEYEVENTF_KEYUP, 0); // Release 
	
	cin.ignore();
	
	return 0;
}


Here is the batch file:
1
2
3
4
5
6
7
8
9
10
11
12
@echo off
echo.
echo Enter your username
set /p "username= > "
if %username%==test goto CORRECT
goto ERROR

:ERROR
exit

:CORRECT
pause


I have spent hours on this problem so i hope someone can guide me in the right direction!

Best regards
Could you please clarify what you mean by

Command prompt does not enter text before i manually press the enter button.


Do you mean the string "test" only appears after you hit enter?

Or??

Andy
Exactly, the batch file open and nothing happens. But if i press enter myself, the string "test" appears in the command prompt on the next line.

This error does not occur if i try the same thing with a txt-file, instead of using the command prompt. Then the txt-file opens and the string "test" will appear correctly.

There must be a way to enter strings into a command prompt!
The problem appears to be the (evil) system() call.

I see the same problem if I use your code as-is. But when I swap the system call with one to CreateProcess, it works fine.

At the end of the day you should be stweering clear of system() anyway. Here, I can see the problem is that while system() does make a call to CreateProcess itself, it then waits on the process handle. If you just use CreateProcess, without a wait, then all is OK.

Be sure to read the comments about batch files in the entry for CreateProcess if this call is still kind of new to you!

Andy

PS While you're at it, I would swap back to using SendInput.
Last edited on
Hi Andy,

Thanks a lot!! It works perfect with CreateProcess and the small /c detail for batch files.

I really appreciate you help!
Topic archived. No new replies allowed.