问题描述
您如何设置在.NET控制台应用程序默认的输入值?
How can you set a default input value in a .net console app?
下面是一些虚幻的code:
Here is some make-believe code:
Console.Write("Enter weekly cost: ");
string input = Console.ReadLine("135"); // 135 is the default. The user can change or press enter to accept
decimal weeklyCost = decimal.Parse(input);
当然,我不希望它是这么简单。我打赌有做一些低层次,非托管的东西;我只是不知道怎么办。
Of course, I don't expect it to be this simple. I am betting on having to do some low-level, unmanaged stuff; I just don't know how.
我知道我可以代替任何输入的默认值。这不是我问。我想了解什么是参与实现我所描述的行为:为用户提供一个可编辑的默认。我也并不担心输入验证;我的问题没有任何关系这一点。
I know I can replace no input with the default. That's not what I am asking about. I am trying to LEARN what's involved in achieving the behavior I described: giving the user an editable default. I'm also not worried about input validation; my question has nothing to do with that.
推荐答案
我相信,你将不得不通过听每个按键preSS手动管理这样的:
I believe that you will have manage this manually by listening to each key press:
快速thown一起例如:
Quickly thown together example:
// write the initial buffer
char[] buffer = "Initial text".ToCharArray();
Console.WriteLine(buffer);
// ensure the cursor starts off on the line of the text by moving it up one line
Console.SetCursorPosition(Console.CursorLeft + buffer.Length, Console.CursorTop - 1);
// process the key presses in a loop until the user presses enter
// (this might need to be a bit more sophisticated - what about escape?)
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
switch (keyInfo.Key)
{
case ConsoleKey.LeftArrow:
...
// process the left key by moving the cursor position
// need to keep track of the position in the buffer
// if the user presses another key then update the text in our buffer
// and draw the character on the screen
// there are lots of cases that would need to be processed (backspace, delete etc)
}
keyInfo = Console.ReadKey(true);
}
这是相当复杂 - 你必须继续确保光标不出去的范围和手动更新缓存
This is quite involved - you'll have to keep ensure the cursor doesn't go out of range and manually update your buffer.
这篇关于如何设置默认输入值的.Net控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!