问题描述
我有问题.我需要编写一个C#程序输入:允许用户输入多行文本,按Ctrl + Enter完成输入输出:通过按增加时间的正确顺序重新排列行来进行标准化.
I have a problem. I need write a C# programInput: Allows the user to enter multiple lines of text, press Ctrl + Enter to finish typingOutput: Standardize by, rearranging lines in the right order of increasing time.
我已经尝试过,但是我不知道如何通过键盘捕捉Ctrl + Enter:
I was tried but I don't know how to catch Ctrl + Enter from keyboard:
我希望输出像示例:
"Created at 28/02/2018 10:15:35 AM by Andy.
Updated at 03/03/2018 02:45:10 PM by Mark
Clear name at 02/03/2018 11:34:05 AM by Andy"
DateTime需要重新排列
DateTime is needed rearranging
推荐答案
您需要创建自己的输入系统以覆盖默认控制台处理程序.
You need to create your own input system to override the default console handler.
您将创建一个ReadKey(true)
循环并处理所有所需的键代码,例如箭头,退格键,删除键,字母,数字和Ctrl + Enter ...
You will create a loop to ReadKey(true)
and process all desired key codes like arrows, backspace, delete, letters, numbers, and the Ctrl+Enter...
因此,对于每个键,您都将要处理的内容重新注入到控制台中,移动插入号,删除char,然后结束该过程.
So for each key, you reinject to the console what you want to process, moving the caret, deleting char, and ending the process.
您还需要管理结果缓冲区.
You need to manage the result buffer as well.
这很有趣.
以下是示例:
void GetConsoleUserInput()
{
Console.WriteLine("Enter something:");
var result = new List<char>();
int index = 0;
while ( true )
{
var input = Console.ReadKey(true);
if ( input.Modifiers.HasFlag(ConsoleModifiers.Control)
&& input.Key.HasFlag(ConsoleKey.Enter) )
break;
if ( char.IsLetterOrDigit(input.KeyChar) )
{
if (index == result.Count)
result.Insert(index++, input.KeyChar);
else
result[index] = input.KeyChar;
Console.Write(input.KeyChar);
}
else
if ( input.Key == ConsoleKey.LeftArrow && index > 0 )
{
index--;
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
// And so on
}
Console.WriteLine();
Console.WriteLine("You entered: ");
Console.WriteLine(String.Concat(result));
Console.WriteLine();
Console.ReadKey();
}
对于多行,结果缓冲区和索引可以是:
For multiline, the result buffer and index can be:
var result = new Dictionary<int, List<char>>();
除了索引,您还可以使用:
And instead of index you can use:
int posX;
int posY;
就是这样:
result[posY][posX];
使用上下箭头时,请不要忘记更新与行长匹配的posX.
Don't forget to update posX matching the line length when using up and down arrows.
复杂的地方是控制台宽度和包装的管理...
Where it gets complicated, it's the management of the width of the console and the wrapping...
做得好!
这篇关于如何在C#中从键盘捕捉键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!