【问题标题】:Deleting characters written by Console.Write method删除 Console.Write 方法写入的字符
【发布时间】:2012-04-02 09:33:35
【问题描述】:
static void f_WriteIpAddresses()
{
    IPHostEntry host;
    string localIP = "?";
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        Console.Write(ip.ToString());
        Console.Write(" - ");
    }
}

static void Main(string[] args)
{
    Console.WriteLine("Your IP Address:")
    WriteIpAddresses();
    Console.Write("[You can delete/modify address]");
    string ip = Console.ReadLine();
}

我想找到所有地址并写在用户可以删除的行上,直到正确的地址或修改行。

c:\>address.exe
Your IP Address:
192.168.1.13 - 10.10.2.15 [You can delete/modify address]

【问题讨论】:

    标签: c# console-application


    【解决方案1】:

    查看这篇文章,它解释了如何清除控制台的某些部分。这样,您还可以将控制台光标设置在您想要的位置,以便让用户覆盖控制台中的某些部分。见c-sharp-console-console-clear-problem

    This post 也可以很方便,很相似的问题。

    【讨论】:

      【解决方案2】:

      你可以做一些事情,比如在最后一个 console.write 的末尾放一个 \r 来让光标在行的开头。

      然后读取您的输入并将新输入与原始输出相结合。由于您的 readline 仅读取新数据,因此您必须在原始数据中添加(覆盖)此新数据。

      但是,这仅在打印的行长度小于控制台宽度时才有效。

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Net;
      
      namespace ConsoleApplication3
      {
          class Program
          {
              static string f_WriteIpAddresses()
              {
                  IPHostEntry host;
                  string localIP = "?";
                  string retVal = "";
                  host = Dns.GetHostEntry(Dns.GetHostName());
                  foreach (IPAddress ip in host.AddressList)
                  {
                      if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                      {
                          Console.Write(ip.ToString());
                          Console.Write(" - ");
                          retVal = ip.ToString() + " - "; 
                      }
                  }
                  return retVal;
              }
      
              static void Main(string[] args)
              {
                  Console.WriteLine("Your IP Address:");
                  string oldip = f_WriteIpAddresses();
                  Console.Write("[You can delete/modify address]\r");
                  string ip = Console.ReadLine();
      
                  string newip = ip + oldip.Substring(ip.Length);
              }
          }
      }
      

      上面应该给出一个新的IP地址,但有一些限制,例如,只适用于单行等。

      【讨论】:

      • 这种方法非常适用于我在控制台输出中称为临时消息的内容,也适用于命令行脚本。只需执行 Console.Write + Msg + \r (或 VBS 的 vbcr)然后您的下一个 console.writeline 将覆盖您最后的临时消息。
      猜你喜欢
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2017-12-17
      相关资源
      最近更新 更多