Repository navigation
Расширенный метод обработки нажатия кнопок в консольке. #1801
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| Пока Истина Цикл | ||
|
|
||
| Нажатие = Консоль.ПрочитатьНажатие(); | ||
|
|
||
| Сообщить("Нажатие: " + Строка(Нажатие)); | ||
| Сообщить("Код кнопки: " + Нажатие.КодКнопки); | ||
|
|
||
| Если Нажатие.Control Тогда | ||
| Сообщить("Ctrl + " + Нажатие.Символ); | ||
| ИначеЕсли Нажатие.Shift Тогда | ||
| Сообщить("Shift + " + Нажатие.Символ); | ||
| ИначеЕсли Нажатие.Alt Тогда | ||
| Сообщить("Alt + " + Нажатие.Символ); | ||
| Иначе | ||
| Сообщить(Нажатие.Символ); | ||
| КонецЕсли; | ||
|
|
||
| Если Нажатие.КодКнопки = 27 Тогда // Escape | ||
| Сообщить("Выход"); | ||
| Прервать; | ||
| КонецЕсли; | ||
|
|
||
| КонецЦикла; | ||
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -89,6 +89,40 @@ | |||||||||||
| return (int)kki.Key; | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| /// <summary> | ||||||||||||
| /// Читает нажатие клавиши и возвращает подробное описание нажатия. | ||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. State that the method requires interactive console input. If a script runs with stdin redirected from a file or pipe,
|
||||||||||||
| /// В отличие от <see cref="ReadKey"/>, возвращает не только код клавиши, но и введённый символ | ||||||||||||
| /// (в том числе кириллический), а также состояние модификаторов. | ||||||||||||
| /// Символ не выводится в консоль (чтение выполняется без эха). | ||||||||||||
| /// </summary> | ||||||||||||
| /// <returns> | ||||||||||||
| /// Объект <see cref="ConsoleKeyPress"/> со свойствами: | ||||||||||||
| /// <list type="bullet"> | ||||||||||||
| /// <item><description><c>КодКнопки</c> — код клавиши (значение перечисления <see cref="ConsoleKey"/>), | ||||||||||||
| /// совпадает с результатом <see cref="ReadKey"/>;</description></item> | ||||||||||||
| /// <item><description><c>Символ</c> — введённый символ; пустая строка для служебных клавиш | ||||||||||||
| /// и управляющих сочетаний;</description></item> | ||||||||||||
| /// <item><description><c>Shift</c>, <c>Alt</c>, <c>Control</c> — булевы признаки удержанных | ||||||||||||
| /// модификаторов.</description></item> | ||||||||||||
| /// </list> | ||||||||||||
| /// </returns> | ||||||||||||
| /// <remarks> | ||||||||||||
| /// Возможности платформы различаются: | ||||||||||||
| /// <list type="bullet"> | ||||||||||||
| /// <item><description>в Windows код клавиши и состояние модификаторов определяются | ||||||||||||
| /// для любых нажатий;</description></item> | ||||||||||||
|
Comment on lines
+111
to
+112
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ограничьте описание Windows: модификаторы без клавиши не возвращаются. Пункт о Windows обещает код клавиши и модификаторы «для любых нажатий». Это слишком широко. Предлагаемое изменение описания
Committable suggestion
|
||||||||||||
| /// <item><description>в Unix-подобных системах .NET распознаёт клавиши и модификаторы только для известных | ||||||||||||
| /// символов и управляющих последовательностей. Для символов за пределами ASCII (в том числе кириллицы) | ||||||||||||
| /// <c>КодКнопки</c> может быть равен 0, а <c>Shift</c> для заглавной кириллической буквы может не определиться | ||||||||||||
|
Comment on lines
+114
to
+116
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Document that Unix modifier flags can be inferred, even for ASCII. If Caps Lock produces
|
||||||||||||
| /// (при этом сам символ всегда возвращается в поле <c>Символ</c>).</description></item> | ||||||||||||
| /// </list> | ||||||||||||
| /// </remarks> | ||||||||||||
| [ContextMethod("ПрочитатьНажатие", "ReadKeyPress")] | ||||||||||||
| public ConsoleKeyPress ReadKeyPress() | ||||||||||||
|
Check notice on line 121 in src/OneScript.StandardLibrary/Text/ConsoleContext.cs
|
||||||||||||
| { | ||||||||||||
| return new ConsoleKeyPress(Console.ReadKey(true)); | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| [ContextMethod("Очистить", "Clear")] | ||||||||||||
| public void Clear() | ||||||||||||
| { | ||||||||||||
|
|
||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| /*---------------------------------------------------------- | ||
| This Source Code Form is subject to the terms of the | ||
| Mozilla Public License, v.2.0. If a copy of the MPL | ||
| was not distributed with this file, You can obtain one | ||
| at http://mozilla.org/MPL/2.0/. | ||
| ----------------------------------------------------------*/ | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using OneScript.Contexts; | ||
| using ScriptEngine.Machine.Contexts; | ||
|
|
||
| namespace OneScript.StandardLibrary.Text | ||
| { | ||
| /// <summary> | ||
| /// Описание нажатия клавиши, полученное методом <see cref="ConsoleContext.ReadKeyPress"/>. | ||
| /// Содержит код клавиши, введённый символ и состояние модификаторов. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Свойства объекта доступны только для чтения и имеют два имени — русское и английское. | ||
| /// Как и любой результат чтения консоли, объект нельзя создать оператором <c>Новый</c>: | ||
| /// он возвращается только методом <see cref="ConsoleContext.ReadKeyPress"/>. | ||
| /// </remarks> | ||
| [ContextClass("НажатиеКлавиши", "KeyPress")] | ||
| public class ConsoleKeyPress : AutoContext<ConsoleKeyPress> | ||
| { | ||
| private readonly ConsoleKeyInfo _keyInfo; | ||
|
|
||
| internal ConsoleKeyPress(ConsoleKeyInfo keyInfo) | ||
| { | ||
| _keyInfo = keyInfo; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Код нажатой клавиши. Совпадает со значением, которое возвращает <see cref="ConsoleContext.ReadKey"/>. | ||
| /// </summary> | ||
| [ContextProperty("КодКнопки", "KeyCode", CanWrite = false)] | ||
| public int KeyCode => (int)_keyInfo.Key; | ||
|
|
||
| /// <summary> | ||
| /// Введённый символ, в том числе кириллический. | ||
| /// Для служебных клавиш и управляющих сочетаний содержит пустую строку. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Опишите условие, при котором Геттер проверяет
|
||
| /// </summary> | ||
| [ContextProperty("Символ", "Symbol", CanWrite = false)] | ||
| public string Symbol => char.IsControl(_keyInfo.KeyChar) ? string.Empty : _keyInfo.KeyChar.ToString(); | ||
|
|
||
| /// <summary> | ||
| /// Признак того, что при нажатии была удержана клавиша Shift. | ||
| /// </summary> | ||
| [ContextProperty("Shift", CanWrite = false)] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Добавьте русские имена для свойств Свойства объявлены только с английскими именами. Документ [ContextProperty("<русское имя>", "Shift", CanWrite = false)]Английские имена
|
||
| public bool Shift => (_keyInfo.Modifiers & ConsoleModifiers.Shift) != 0; | ||
|
|
||
| /// <summary> | ||
| /// Признак того, что при нажатии была удержана клавиша Alt. | ||
| /// </summary> | ||
| [ContextProperty("Alt", CanWrite = false)] | ||
| public bool Alt => (_keyInfo.Modifiers & ConsoleModifiers.Alt) != 0; | ||
|
|
||
| /// <summary> | ||
| /// Признак того, что при нажатии была удержана клавиша Control (Ctrl). | ||
| /// </summary> | ||
| [ContextProperty("Control", CanWrite = false)] | ||
| public bool Control => (_keyInfo.Modifiers & ConsoleModifiers.Control) != 0; | ||
|
|
||
| public override string ToString() | ||
| { | ||
| var keyPresentation = Symbol.Length != 0 ? Symbol : _keyInfo.Key.ToString(); | ||
| var modifiersPresentation = GetModifiersPresentation(); | ||
|
|
||
| return modifiersPresentation.Length != 0 | ||
| ? string.Concat(modifiersPresentation, "+", keyPresentation) | ||
| : keyPresentation; | ||
| } | ||
|
|
||
| private string GetModifiersPresentation() | ||
| { | ||
| var modifiers = new List<string>(3); | ||
|
|
||
| if (Shift) | ||
| modifiers.Add("Shift"); | ||
| if (Alt) | ||
| modifiers.Add("Alt"); | ||
| if (Control) | ||
| modifiers.Add("Control"); | ||
|
|
||
| return string.Join("+", modifiers); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| /*---------------------------------------------------------- | ||
| This Source Code Form is subject to the terms of the | ||
| Mozilla Public License, v.2.0. If a copy of the MPL | ||
| was not distributed with this file, You can obtain one | ||
| at http://mozilla.org/MPL/2.0/. | ||
| ----------------------------------------------------------*/ | ||
|
|
||
| using System; | ||
| using System.Reflection; | ||
| using OneScript.Contexts; | ||
| using OneScript.StandardLibrary.Text; | ||
| using OneScript.Values; | ||
| using ScriptEngine.Machine; | ||
| using Xunit; | ||
|
|
||
| namespace OneScript.StandardLibrary.Tests | ||
| { | ||
| public class ConsoleContextTests | ||
| { | ||
| private static ConsoleKeyPress CreateKeyPress(ConsoleKeyInfo keyInfo) => new ConsoleKeyPress(keyInfo); | ||
|
|
||
| private static IValue GetProperty(ConsoleKeyPress keyPress, string name) => | ||
| keyPress.GetPropValue(keyPress.GetPropertyNumber(name)); | ||
|
|
||
| private static int GetKeyCode(ConsoleKeyPress keyPress, string name) => | ||
| (BslNumericValue)GetProperty(keyPress, name); | ||
|
|
||
| private static string GetString(ConsoleKeyPress keyPress, string name) => | ||
| (BslStringValue)GetProperty(keyPress, name); | ||
|
|
||
| private static bool GetBoolean(ConsoleKeyPress keyPress, string name) => | ||
| (bool)(BslBooleanValue)GetProperty(keyPress, name); | ||
|
|
||
| [Fact] | ||
| public void ReadKeyPress_Is_Exposed_With_Bilingual_Name() | ||
| { | ||
| var method = typeof(ConsoleContext).GetMethod(nameof(ConsoleContext.ReadKeyPress)); | ||
|
|
||
| Assert.NotNull(method); | ||
| Assert.Equal(typeof(ConsoleKeyPress), method.ReturnType); | ||
|
|
||
| var attribute = method!.GetCustomAttribute<ContextMethodAttribute>(); | ||
| Assert.NotNull(attribute); | ||
| Assert.Equal("ПрочитатьНажатие", attribute!.Name); | ||
| Assert.Equal("ReadKeyPress", attribute.Alias); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Type_Has_Bilingual_Names() | ||
| { | ||
| var attribute = typeof(ConsoleKeyPress).GetCustomAttribute<ContextClassAttribute>(); | ||
|
|
||
| Assert.NotNull(attribute); | ||
| Assert.Equal("НажатиеКлавиши", attribute!.Name); | ||
| Assert.Equal("KeyPress", attribute.Alias); | ||
|
|
||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); | ||
|
|
||
| Assert.Equal("НажатиеКлавиши", keyPress.SystemType.Name); | ||
| Assert.Equal("KeyPress", keyPress.SystemType.Alias); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Exposes_Expected_Properties() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); | ||
|
|
||
| Assert.Equal(5, keyPress.GetPropCount()); | ||
| Assert.Equal("КодКнопки", keyPress.GetPropName(0)); | ||
| Assert.Equal("Символ", keyPress.GetPropName(1)); | ||
| Assert.Equal("Shift", keyPress.GetPropName(2)); | ||
| Assert.Equal("Alt", keyPress.GetPropName(3)); | ||
| Assert.Equal("Control", keyPress.GetPropName(4)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Properties_Are_ReadOnly() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); | ||
|
|
||
| for (var i = 0; i < keyPress.GetPropCount(); i++) | ||
| { | ||
| Assert.True(keyPress.IsPropReadable(i)); | ||
| Assert.False(keyPress.IsPropWritable(i)); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Properties_Are_Accessible_By_English_Names() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); | ||
|
|
||
| Assert.Equal(keyPress.GetPropertyNumber("КодКнопки"), keyPress.GetPropertyNumber("KeyCode")); | ||
| Assert.Equal(keyPress.GetPropertyNumber("Символ"), keyPress.GetPropertyNumber("Symbol")); | ||
| Assert.Equal(keyPress.GetPropertyNumber("Shift"), keyPress.GetPropertyNumber("Shift")); | ||
| Assert.Equal(keyPress.GetPropertyNumber("Alt"), keyPress.GetPropertyNumber("Alt")); | ||
| Assert.Equal(keyPress.GetPropertyNumber("Control"), keyPress.GetPropertyNumber("Control")); | ||
|
|
||
| Assert.Equal((int)ConsoleKey.A, GetKeyCode(keyPress, "KeyCode")); | ||
| Assert.Equal("a", GetString(keyPress, "Symbol")); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Returns_Cyrillic_Symbol() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('ф', (ConsoleKey)0, false, false, false)); | ||
|
|
||
| Assert.Equal("ф", GetString(keyPress, "Символ")); | ||
| Assert.Equal(0, GetKeyCode(keyPress, "КодКнопки")); | ||
| Assert.Equal("ф", keyPress.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Returns_Upper_Case_Cyrillic_Symbol_With_Shift() | ||
| { | ||
| var keyPress = CreateKeyPress( | ||
| new ConsoleKeyInfo('Ф', (ConsoleKey)0, shift: true, alt: true, control: false)); | ||
|
|
||
| Assert.Equal("Ф", GetString(keyPress, "Символ")); | ||
| Assert.True(GetBoolean(keyPress, "Shift")); | ||
| Assert.True(GetBoolean(keyPress, "Alt")); | ||
| Assert.False(GetBoolean(keyPress, "Control")); | ||
| Assert.Equal("Shift+Alt+Ф", keyPress.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Returns_Empty_Symbol_For_Control_Key_Combination() | ||
| { | ||
| // Ctrl+A: .NET сообщает управляющий символ и код клавиши A | ||
| var keyPress = CreateKeyPress( | ||
| new ConsoleKeyInfo('\u0001', ConsoleKey.A, shift: false, alt: false, control: true)); | ||
|
|
||
| Assert.Equal(string.Empty, GetString(keyPress, "Символ")); | ||
| Assert.Equal((int)ConsoleKey.A, GetKeyCode(keyPress, "КодКнопки")); | ||
| Assert.True(GetBoolean(keyPress, "Control")); | ||
| Assert.False(GetBoolean(keyPress, "Shift")); | ||
| Assert.False(GetBoolean(keyPress, "Alt")); | ||
| Assert.Equal("Control+A", keyPress.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Returns_Empty_Symbol_For_Function_Key() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo('\0', ConsoleKey.F1, false, false, false)); | ||
|
|
||
| Assert.Equal(string.Empty, GetString(keyPress, "Символ")); | ||
| Assert.Equal((int)ConsoleKey.F1, GetKeyCode(keyPress, "КодКнопки")); | ||
| Assert.Equal("F1", keyPress.ToString()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void KeyPress_Keeps_Space_As_Symbol() | ||
| { | ||
| var keyPress = CreateKeyPress(new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false)); | ||
|
|
||
| Assert.Equal(" ", GetString(keyPress, "Символ")); | ||
| Assert.Equal(" ", keyPress.ToString()); | ||
| } | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.