【问题标题】:Is there a break a loop once a button is pressed (Visual basic)按下按钮后是否会中断循环(Visual basic)
【发布时间】:2020-12-09 18:33:33
【问题描述】:
            For i = 1 To 10
                Ascii()
                ForegroundColor = random.Next(1, 16)
                DrawSlot("Unknown")
                WriteLine()
                ForegroundColor = random.Next(1, 16)
                DrawSlot("Unknown")
                WriteLine()
                ForegroundColor = random.Next(1, 16)
                DrawSlot("Unknown")
                Thread.Sleep(100)
                Clear()
            Next

我希望这个循环一直持续到用户按下键盘上的按钮,导致循环结束。使用 console.readline 会导致程序暂停并等待输入,所以我想知道是否还有其他方法?

【问题讨论】:

  • 您如何使用控制台应用程序显示图像?请给我们看一些代码...
  • @Idle_Mind 添加了代码。对不起
  • 另外,我不会在循环中清除整个屏幕,而是在循环之前清除它并使用Console.SetCursorPosition() 将光标移动到要绘制的位置。这应该会更快。您可以隐藏使用Console.CursorVisible 移动的光标。不要使用for 循环,也可以使用while 循环。
  • @Idle_Mind 感谢您的帮助:D

标签: vb.net


【解决方案1】:

这是一个使用我在 cmets 中链接的函数的简单示例:

Sub Main(args As String())

    ' ... possibly other code ...

    Console.Clear()
    Console.CursorVisible = False

    Console.WriteLine("Press any key to cancel processing.")
    Console.Write("Processing...")
    Dim top As Integer = Console.CursorTop
    Dim left As Integer = Console.CursorLeft

    Dim progress As String = "/-\|"
    Dim sequence As IEnumerator(Of Char) = progress.GetEnumerator

    ' clear the buffer out
    While Console.KeyAvailable
        Console.ReadKey(True)
    End While

    ' keep "processing" until a key is pressed
    While Not Console.KeyAvailable
        If Not sequence.MoveNext Then
            sequence = progress.GetEnumerator
            sequence.MoveNext()
        End If

        Console.SetCursorPosition(left, top)
        Console.Write(sequence.Current)

        System.Threading.Thread.Sleep(100)
    End While
    ' consume the keypress that cancelled the loop above
    ' without displaying it
    Dim cki As ConsoleKeyInfo = Console.ReadKey(True)

    Console.WriteLine()
    Console.WriteLine("Processing cancelled!")
    Console.WriteLine("Cancelled with: " & cki.KeyChar)

    Console.CursorVisible = True
    Console.WriteLine()
    Console.Write("Press Enter to Quit...")
    Console.ReadKey()
End Sub

输出:

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2023-04-07
    • 2012-04-23
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2015-07-19
    相关资源
    最近更新 更多