如何在 .Net Console App 中设置默认输入值? [英] How to set default input value in .Net Console App?

查看:20
本文介绍了如何在 .Net Console App 中设置默认输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 .net 控制台应用程序中设置默认输入值?

How can you set a default input value in a .net console app?

这是一些虚构的代码:

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.

推荐答案

我相信您将通过聆听每个按键来手动管理:

I believe that you will have manage this manually by listening to each key press:

快速组合示例:

   // 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 Console App 中设置默认输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆