【问题标题】:Edit text in C# console application? [duplicate]在 C# 控制台应用程序中编辑文本? [复制]
【发布时间】:2011-11-25 19:07:04
【问题描述】:

有没有办法在 C# 控制台应用程序中编辑文本?换句话说,是否可以在命令行中放置预定义的文本,以便用户可以修改文本,然后重新提交给应用程序?

【问题讨论】:

  • 我不相信我的问题与提供的问题重复。我的需要更具体,并且在该问题上给出的答案并没有回答这个问题。据我所知,Console 类没有任何帮助在命令行上放置可编辑文本的功能。
  • 除非您编写一个程序,否则控制台应用程序中没有命令行。这可以通过 Console 类来完成。编辑: cmd 行是外壳,用于启动控制台应用程序。当它正在运行并且您正在向控制台窗口输出内容时,您没有使用 shell 命令,即命令行。您将解释已按下的键并根据键执行特定操作(即按下退格键时将光标移回一个字符)。'
  • @Alex Ford:关于“更具体”-“我如何打印 int”比“我如何打印对象”更具体,没有区别。
  • 我不确定你是否应该在命令行中编辑文本......毕竟它是一个命令行:P

标签: c# .net command-line console console-application


【解决方案1】:

是的。您需要使用 Console 的 SetCursorPosition 方法。示例:

    Console.WriteLine("hello");
    Console.SetCursorPosition(4, 0);
    Console.WriteLine("      ");

它将显示“地狱” 您需要自定义实现 ReadLine 方法,该方法可让您在控制台中编辑 n 符号(默认字符串)并从用户返回字符串。这是我的例子:

static string ReadLine(string Default)
{
    int pos = Console.CursorLeft;
    Console.Write(Default);
    ConsoleKeyInfo info;
    List<char> chars = new List<char> ();
    if (string.IsNullOrEmpty(Default) == false) {
        chars.AddRange(Default.ToCharArray());
    }

    while (true)
    {
        info = Console.ReadKey(true);
        if (info.Key == ConsoleKey.Backspace && Console.CursorLeft > pos)
        {
            chars.RemoveAt(chars.Count - 1);
            Console.CursorLeft -= 1;
            Console.Write(' ');
            Console.CursorLeft -= 1;

        }
        else if (info.Key == ConsoleKey.Enter) { Console.Write(Environment.NewLine); break; }
        //Here you need create own checking of symbols
        else if (char.IsLetterOrDigit(info.KeyChar))
        {
            Console.Write(info.KeyChar);
            chars.Add(info.KeyChar);
        }
    }
    return new string(chars.ToArray ());
}

此方法将显示字符串默认值。希望我能正确理解您的问题(我对此表示怀疑)

【讨论】:

  • 你能澄清一下吗?我不确定我是否理解。我将此代码放在一个新的控制台应用程序中,它确实显示“地狱”,但这如何帮助我在命令行上编辑该文本?
  • +1 因为不必引用 System.Windows.Forms
  • 很好的答案。对于有 SendKeys 问题的人非常有帮助!
【解决方案2】:

我想到的一件事是……模拟击键。 还有一个使用 SendKeys 的简单示例:

static void Main(string[] args)
{
    Console.Write("Your editable text:");
    SendKeys.SendWait("hello"); //hello text will be editable :)
    Console.ReadLine();
}

注意:这仅适用于活动窗口。

【讨论】:

  • 你的方法比我的简单。看来我喜欢发明自行车 :))
  • 您的代码非常好,而且您没有发明自行车,因为在我建议的解决方案中需要使用 System.Windows.Forms 命名空间或 PInvoke SendInput 或类似的东西。 +1 来自我 :)
  • 谢谢。很高兴我们都认为彼此的方法很好。
  • 正如另一个问题中指出的那样,您需要注意您的应用具有焦点。
  • 如上所述,请注意这个答案。 SendKeys doesn't always work...。为避免这些问题,请查看Praetor12's 答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
相关资源
最近更新 更多