M
M
Muxto2013-09-27 00:31:46
C++ / C#
Muxto, 2013-09-27 00:31:46

keypress event handler in console

dabbled with the console application, entered numbers.
I think "We need to put the handler on the input and don't sweat it." and realized that I don’t know if it’s possible to make an input handler in the console.
i want something like

if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
    {
        e.Handled = true;
    }

found only b-godly examples like stackoverflow.com/questions/13106493/how-do-i-only-allow-number-input-into-my-c-sharp-console-application

is it possible to check input directly from the Console.In stream ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Muxto, 2013-10-03
@Muxto

he asked himself - he answered.
in general, I wanted the console to create a ready-made argument like KeyEventArgs when a key is pressed, which is then easier to process.
already forgot about this question, accidentally stumbled upon the code in Schildt's book.

// спасибо герберту шилдту за код
// и за наше счастливое детство

using System;
using System.ComponentModel;

// создаем класс для обработчика
class myKeyEventArgs : HandledEventArgs
{
    // нажатая кнопка
    public ConsoleKeyInfo key;

    public myKeyEventArgs (ConsoleKeyInfo _key)
    {
        key = _key;
    }
}

// класс события
class KeyEvent
{
    // событие нажатия
    public event EventHandler<myKeyEventArgs> KeyPress;

    // метод запуска события
    public void OnKeyPress(ConsoleKeyInfo _key)
    {
        KeyPress(this, new myKeyEventArgs (_key));
    }
}

// прога
class KeyEventDemo
{
    static void Main()
    {
    	// объект события
        KeyEvent kevt = new KeyEvent();
        
        // кнопа
        ConsoleKeyInfo key;

        // обработчик
        kevt.KeyPress += (sender, e) =>
        {
        	// отслеживает нажатый альт
            if (e.key .Modifiers == ConsoleModifiers .Alt )
                Console.WriteLine(" ALT! " );

            // и позволяет вводить только цифры и точку
            char ch = e.key .KeyChar  ;
            if (!char.IsDigit(ch)&& ch != '.')
            {
                e.Handled = true;
            }
            else Console.WriteLine(" нажато: " + ch );
        };

        Console.WriteLine("вводи символы, друг");
        // пока точку не нажмешь
        do
        {
        	// нажатая не отображается
            key = Console.ReadKey(true);
            // событие произошло
            kevt.OnKeyPress(key);
        }
        while(key.KeyChar != '.');
    }
}

M
mayorovp, 2013-09-27
@mayorovp

In general, no, since input from Console.In may also be redirected.
Regarding what you need: you can put a window hook on the console window, but personally I would stop at the option just with checking the characters read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question