May 102013
 

Few days ago I read a blog post about reading console input. It was quite straight-forward explanation and I wondered how difficult would it be to have this done in C#. Well, not really hard at all.

First step is to setup our console. We enable mouse input and we disable quick edit mode:

var handle = NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE);

int mode = 0;
if (!(NativeMethods.GetConsoleMode(handle, ref mode))) { throw new Win32Exception(); }

mode |= NativeMethods.ENABLE_MOUSE_INPUT;
mode &= ~NativeMethods.ENABLE_QUICK_EDIT_MODE;
mode |= NativeMethods.ENABLE_EXTENDED_FLAGS;

if (!(NativeMethods.SetConsoleMode(handle, mode))) { throw new Win32Exception(); }

All is left to do next is a simple loop that will check for new input:

while (true) {
    if (!(NativeMethods.ReadConsoleInput(handle, ref record, 1, ref recordLen))) { throw new Win32Exception(); }
    switch (record.EventType) {
        case NativeMethods.MOUSE_EVENT:
            //do something
            break;

        case NativeMethods.KEY_EVENT:
            if (record.KeyEvent.wVirtualKeyCode == (int)ConsoleKey.Escape) { return; }
            break;
    }
}

Check out example program.

PS: Expanding program to handle other key events should be relatively easy since all structures are already in place. Check console reference for more details.

PPS: I really hate C unions. :)

  One Response to “Console mouse input in C#”

Comments (1)
  1. Exactly what I needed. As old schooler, i loved any use of that strange new thing called mouse. load mouse.com to use it ofc! :) Thanks, great article.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>