} // func ConvertEvent public IEnumerable <EventArgs> ReadInputEvents(int maxCount = -1) { if (maxCount < 0) { maxCount = NumberOfEvents; } var buffer = new ConsoleInputRecord[1024]; while (maxCount > 0) { var readLength = Math.Max(maxCount, buffer.Length); if (!ReadConsoleInput(DangerousGetHandle, buffer, unchecked ((uint)readLength), out var readed)) { throw new Win32Exception(); } // return events for (var i = 0; i < readed; i++) { if (TryConvertEvent(ref buffer[i], out var ev, out var repeatCount)) { for (var j = 0; j < repeatCount; j++) { yield return(ev); } } } maxCount -= unchecked ((int)readed); } } // proc ReadInputEvents
private static bool TryConvertEvent(ref ConsoleInputRecord r, out EventArgs ev, out int repeatCount) { switch (r.EventType) { case EventType.KeyEvent: { var keyCode = (ConsoleKey)r.KeyEvent.wVirtualKeyCode; var keyModifiers = (ConsoleKeyModifiers)r.KeyEvent.dwControlKeyState; if (r.KeyEvent.bKeyDown) { ev = new ConsoleKeyDownEventArgs(keyCode, keyModifiers, r.KeyEvent.uChar); } else { ev = new ConsoleKeyUpEventArgs(keyCode, keyModifiers, r.KeyEvent.uChar); } repeatCount = r.KeyEvent.wRepeatCount; } return(true); case EventType.MouseEvent: { var buttonState = (ConsoleMouseButtonState)(r.MouseEvent.dwButtonState & 0xFFFF); var keyModifiers = (ConsoleKeyModifiers)r.MouseEvent.dwControlKeyState; switch (r.MouseEvent.dwEventFlags) { case 0x0000: // Click/Released ev = new ConsoleMouseEventArgs(buttonState, keyModifiers, r.MouseEvent.dwMousePosition.X, r.MouseEvent.dwMousePosition.Y); repeatCount = 1; return(true); case 0x0001: // Moved ev = new ConsoleMouseMovedEventArgs(buttonState, keyModifiers, r.MouseEvent.dwMousePosition.X, r.MouseEvent.dwMousePosition.Y); repeatCount = 1; return(true); case 0x0004: // Wheel ev = new ConsoleMouseWheelEventArgs(buttonState, keyModifiers, r.MouseEvent.dwMousePosition.X, r.MouseEvent.dwMousePosition.Y, ConsoleWheelOrientation.Horizontal, unchecked ((int)(r.MouseEvent.dwButtonState >> 16))); repeatCount = 1; return(true); case 0x0008: // HWheel ev = new ConsoleMouseWheelEventArgs(buttonState, keyModifiers, r.MouseEvent.dwMousePosition.X, r.MouseEvent.dwMousePosition.Y, ConsoleWheelOrientation.Horizontal, unchecked ((int)(r.MouseEvent.dwButtonState >> 16))); repeatCount = 1; return(true); default: // Moved ev = EventArgs.Empty; repeatCount = 0; return(false); } } case EventType.MenuEvent: ev = new ConsoleMenuEventArgs(r.MenuEvent.dwCommandId); repeatCount = 1; return(true); case EventType.WindowBufferSizeEvent: ev = new ConsoleBufferSizeEventArgs(r.WindowBufferSizeEvent.dwSize.X, r.WindowBufferSizeEvent.dwSize.Y); repeatCount = 1; return(true); case EventType.FocusEvent: ev = r.FocusEvent.bSetFocus ? (EventArgs)ConsoleSetFocusEventArgs.Default : (EventArgs)ConsoleLostFocusEventArgs.Default; repeatCount = 1; return(true); default: ev = EventArgs.Empty; repeatCount = 0; return(false); } } // func ConvertEvent