WaitForMultipleObjects acting strange

Hey everyone, it's been a while since I've written any code, so I'm sorry if it's messy.

I'm trying to write some functions that will type text to the console like it's being typed.

Everything works fine when I run it through Visual Studio 2010 (Debug and Release). I run into a problem when I run the executable outside of the IDE.

The code I have below creates a thread which writes to the screen at a speed that the "parent" function sets, and has control of. The "parent" function then starts to wait for either the thread to exit or a key press. If a key is pressed, it sets the speed to unlimited, so the thread finishes "typing" quickly, and exits. Like I said above, this works perfectly fine when run through the IDE.

When running the standalone executable (both Debug and Release), it not only reacts to key presses, but also to mouse movement inside the window. If the mouse even touches the inside of the console, it acts like the user pressed a key. I don't understand why this happens and I'm not sure how to stop this, which is why I'm asking this here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void _sPresent(void* args)
{
	const char* str = (char*)((unsigned**)args)[0];
	size_t len = strlen(str);
	unsigned* charsPerSecond = ((unsigned**)args)[1];
	putchar(str[0]);
	for(unsigned i = 1; i < len; ++i) {
		if(*charsPerSecond > 0)
			Sleep(1000 / *charsPerSecond);
		putchar(str[i]);
	}
	_endthread();
}

void sPresent(const char* str, unsigned charsPerSecond)
{
	unsigned* args[2] = {(unsigned*)str, &charsPerSecond}; // ugly, I know

	DWORD thread = _beginthread(&_sPresent, 0, (void*)args);

	HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
	DWORD mode = 0;

	HANDLE handles[2] = {in, (HANDLE)thread};
	
	if(!GetConsoleMode(in, &mode))
		return;
	if(!SetConsoleMode(in, mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)))
		return;
	FlushConsoleInputBuffer(in);

	WaitForMultipleObjects(2, handles, FALSE, INFINITE); // wait for key press or thread to return

	FlushConsoleInputBuffer(in);
	if(!SetConsoleMode(in, mode))
		return;
	charsPerSecond = 0; // set speed to unlimited
	WaitForSingleObject((HANDLE)thread, INFINITE); // wait again to make sure thread is done (in case key was pressed) before returning
}
OK, I got it.

I wasn't aware that ENABLE_MOUSE_INPUT was on by default, so turning that off in the console mode did the trick.

I still don't understand why the program acted differently depending on if it was run inside the IDE or not, though.
Topic archived. No new replies allowed.