how to make ReadConsoleInput notice MOUSE_EVENT's when program is running from *.bat/*.cmd file or console?

StackOverflow https://stackoverflow.com/questions/23666035

Question

This code when compiled and run directly by clicking on the exe file works ok. But when run by *.cmd file or by typing it's name in console the events won't display. Is there way around that ?

#include <windows.h>
#include <stdio.h>
#include <iostream>

int main() {
  HANDLE input_handle = GetStdHandle(STD_INPUT_HANDLE);
  INPUT_RECORD input_record;
  DWORD input_size = 1;
  DWORD events = 0;
  do {
    FlushConsoleInputBuffer(input_handle);
    ReadConsoleInput(input_handle, &input_record, input_size, &events);
    if (input_record.EventType == MOUSE_EVENT) {
      std::cout << " X:" << input_record.Event.MouseEvent.dwMousePosition.X
                << " Y:" << input_record.Event.MouseEvent.dwMousePosition.Y
                << std::endl;
    }
    else if (input_record.EventType == KEY_EVENT) {
      std::cout << input_record.Event.KeyEvent.wVirtualKeyCode << std::endl;
    }
  } while(input_record.Event.KeyEvent.wVirtualKeyCode != VK_ESCAPE);
  return 0;
}

but key events work in both cases, only mouse events are filtered out

Was it helpful?

Solution

The documentation of dwMode parameter of SetConsoleMode function specify:

ENABLE_QUICK_EDIT_MODE  0x0040 
This flag enables the user to use the mouse to select and edit text. 

To enable this mode, use ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS.
To disable this mode, use ENABLE_EXTENDED_FLAGS without this flag.

When this mode is enabled (the default) the mouse is used by cmd.exe to allows the user to select text from the command-line window screen. Besides, it seems that in certain windows versions (like Vista and/or 7) the mouse input in cmd.exe is not enabled by default.

If you want that your program get mouse events, you must enable mouse input and disable quick edit mode this way:

GetConsoleMode ( input_handle, &dwOldMode );
SetConsoleMode ( input_handle, ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS );

Perhaps you may want to preserve other mode flags from dwOldMode and just modify the previous ones. Anyway, you must recover the original mode before the program ends this way:

SetConsoleMode ( input_handle, dwOldMode );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top