Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading;
- namespace AssociationTask2
- {
- class Program
- {
- static void Main(string[] args)
- {
- bool found;
- Input input = new Input();
- input.AddListener(ConsoleKey.W, () =>
- {
- Console.WriteLine("W press");
- });
- Console.WriteLine("Для выхода из цикла нажмите клавишу - Escape!");
- Thread thread = new Thread(() =>
- {
- while (true) input.Update();
- });
- thread.Start();
- while (input.Session)
- {
- //
- }
- }
- static void CallBack(WaitForButton waitFor)
- {
- waitFor(Console.ReadKey().Key);
- }
- }
- delegate void WaitForButton(ConsoleKey key);
- delegate Action SomeReaction(ConsoleKey key, out bool value);
- class Input
- {
- private Dictionary<ConsoleKey, Action> _dictionary;
- private SomeReaction _someReaction;
- private WaitForButton _makeSubscribe;
- private bool _session;
- public Input()
- {
- Session = true;
- Dictionary = new Dictionary<ConsoleKey, Action>();
- Dictionary.Add(ConsoleKey.Escape, () => Session = false);
- SomeReaction = GetReaction;
- MakeSubscribe = SubscriptionOnKey;
- }
- public Dictionary<ConsoleKey, Action> Dictionary { get => _dictionary; set => _dictionary = value; }
- public SomeReaction SomeReaction { get => _someReaction; set => _someReaction = value; }
- public WaitForButton MakeSubscribe { get => _makeSubscribe; set => _makeSubscribe = value; }
- public bool Session { get => _session; set => _session = value; }
- public void AddListener(ConsoleKey key, Action onPress)
- {
- if (_dictionary.ContainsKey(key))
- {
- _dictionary[key] += onPress;
- }
- else
- {
- _dictionary.Add(key, onPress);
- }
- }
- private void SubscriptionOnKey(ConsoleKey consoleKey)
- {
- Console.WriteLine($"Введите реакцию на клавишу - {consoleKey}:");
- string reaction = Console.ReadLine();
- Dictionary.Add(consoleKey, () =>
- {
- Console.WriteLine("\n" + reaction);
- });
- }
- private bool LookForReaction(ConsoleKey consoleKey, out Action action)
- {
- return Dictionary.TryGetValue(consoleKey, out action);
- }
- public void Update()
- {
- ConsoleKeyInfo key = Console.ReadKey(false);
- if (_dictionary.ContainsKey(key.Key))
- {
- _dictionary[key.Key].Invoke();
- }
- }
- private Action GetReaction(ConsoleKey consoleKey, out bool found)
- {
- Action action;
- found = LookForReaction(consoleKey, out action);
- if (found)
- return action;
- return () => Console.WriteLine($"\nНа клавишу - {consoleKey.ToString().ToLower()} нет подписки!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement