Отловить нажатие клавиши в консоли - C#
Формулировка задачи:
Здравствуйте!
Необходимо отловить нажатие клавиши пробел или Enter, когда я не нахожусь в консоли, то есть она свернута. Подскажите, как это можно сделать? (нашел некоторые отрывки, но может кто поможет привести эти отрывки в систему)
Решение задачи: «Отловить нажатие клавиши в консоли»
textual
Листинг программы
using System;
using System.Threading;
static class KeyPress
{
[System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true )]
public static extern short GetAsyncKeyState( int vkey );
public enum Key { Enter, Space };
public delegate void keyPress( Key Key );
public static event keyPress OnKeyPressed;
static Thread th = new Thread( x =>
{
while ( true )
{
if ( OnKeyPressed != null )
{
if ( GetAsyncKeyState( 0x0D ) != 0 )
OnKeyPressed( Key.Enter );
if ( GetAsyncKeyState( 0x20 ) != 0 )
OnKeyPressed( Key.Space );
}
Thread.Sleep( 100 );
}
} );
public static void Start()
{
th.Start();
}
public static void Stop()
{
th.Abort();
}
}
class Program
{
static void Main( string[] args )
{
KeyPress.OnKeyPressed += KeyPress_OnKeyPress;
KeyPress.Start();
while ( true )
{
}
}
static void KeyPress_OnKeyPress( KeyPress.Key Key )
{
if ( Key == KeyPress.Key.Enter )
Console.Write( "Enter" );
if ( Key == KeyPress.Key.Space )
Console.Write( "Space" );
}
}