65.9K
CodeProject 正在变化。 阅读更多。
Home

VB.NET 2.0 中的控制台行编辑器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.22/5 (8投票s)

2006年3月12日

公共领域

2分钟阅读

viewsIcon

74975

downloadIcon

556

使用新的 .NET 2.0 控制台特性,以及这款旧式的行编辑器。

Sample Image - LineEditor.gif

引言

在 .NET 1.x 中,控制台应用程序受到了极大的限制。键盘处理非常有限,对颜色和光标位置的控制也很有限。.NET 2.0 扩展了 Console 类,可以控制键盘、文本定位和颜色。这些新的 Console 属性和方法几乎给了我与 QuickBasic 时代一样的控制能力;语法比 QuickBasic 的语法更合乎逻辑。

只是为了好玩,我决定编写一个行编辑器,作为一个简单的实验室来练习 Console 的新特性。该程序模仿了 DOS 的 Edlin 的一些功能,并具有一定的面向对象特性。

背景

在 .NET 1.x 中,我们只能使用 Console.ReadLine,在用户按下 Enter 之前,我们什么都看不到。

按键处理

在此示例中,我使用 Console.ReadKey 来读取单个按键,并使用 ConsoleKey 枚举来命名键盘上的键。我还使用 Console.TreatControlCAsInput 来关闭对 Ctl+C 的检查,以便我的程序可以像 Edlin 一样运行。

光标位置

在 .NET 1.x 中,我们对光标位置的唯一控制就是是否在写入一行后发送换行符(如果要换行,请使用 Console.WriteLine,如果不要换行,请使用 Console.Write)。

使用代码

在此程序中,唯一可重用的代码是 EditLine 的 edit 方法,我只会将其用作起点。

关注点

加载的文本文件中的每一行都由一个 EditLine 对象表示,整个文件是 EditLineList 对象中 EditLine 对象的集合。

EditLine 类中,高级按键处理位于 Edit 方法中。在这里,我使用 Console.ReadKey 读取按键。我使用 ConsoleKey 枚举在我的 Select Case 结构中命名不同的键,我在其中进行按键处理。这是 Edit 模式

' Turn off Control+C tracking, we use the key 
' sequence to end editing for 
Console.TreatControlCAsInput = True

' This loop is the keyboard reading loop. Here we
' read all of the key strokes and process it
Do
    theKey = Console.ReadKey(True)
    Select Case theKey.Key
        Case ConsoleKey.Enter
            ' ...
        Case ConsoleKey.Escape
            ' ... ETC.
        Case ConsoleKey.UpArrow, _
          ConsoleKey.DownArrow, _
          ConsoleKey.F1 To ConsoleKey.F12
            ' Ignore theses keys. To make a real 
            ' app, we need to ignore more keys.
            ' There are probably some dangerous
            ' keys that can get to Case Else
        Case Else
            ' Everything else is echoed and added 
            ' to the buffer
            If Not (theKey.Key = ConsoleKey.C And _
              theKey.Modifiers = _
              ConsoleModifiers.Control) Then
                Console.Write(theKey.KeyChar)
                ' Other processing here
            End If
    End Select
   ' Control+c breaks us out of the loop
   ' We don't handle this in the Select Case
Loop Until theKey.Key = ConsoleKey.C And _
  theKey.Modifiers = ConsoleModifiers.Control
' Turn Control+C tracking back on.
Console.TreatControlCAsInput = False

此程序和 Edlin 之间的差异

编写此程序是为了练习 Console 对象,并且在我开始让它完成 Edlin 所做的所有事情之前,我就感到厌烦了(此外,有什么意义呢)。该程序无法完成的事情

  • 实现 Append、Copy、Move、Replace 和 Transfer 命令。
  • 处理超过 70 个字符的行。
  • 充分地错误检查所有键盘输入。
  • 支持通过在命令之间放置分号,在命令行上放置多个命令。

另一方面,我可能拥有比原始程序更面向对象的设计。

参考文献

历史

  • 03/14/2006 - 修复了命令行错误;程序无法处理命令行中的文件名。
© . All rights reserved.