Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 != '.');
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question