按下回车键时尝试引发事件

时间:2014-05-12 18:16:55

标签: vb.net events console-application raiseevent

好的,所以这是我的代码到目前为止。

Module Module1
Public Event count()
Sub Main()
    AddHandler count, AddressOf MyFunction
    Console.WriteLine("to start the countdown process type go")
    Console.ReadLine()
    If e.KeyCode = Keys.Enter Then
        RaiseEvent count()
    End If
    Console.ReadKey()
End Sub
Sub MyFunction()
    Dim a As Integer = 16
    Dim b As Integer = 6
    Console.WriteLine("Now we are going to count to a number using only even numbers")
    Do Until b > a
        Console.WriteLine(b)
        b += 2
    Loop
    Console.ReadKey()
End Sub
End Module

我按下回车键时尝试提高事件计数。我做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个

Sub Main()
    AddHandler count, AddressOf MyFunction
    Console.WriteLine("to start the countdown process type go")
    Dim input As String = Console.ReadLine
    If input.ToLower = "go" Then
        RaiseEvent Count()
    Else
        Console.WriteLine("you didn't type 'go'")
        Console.ReadLine()
    End If
End Sub

专门回答你关于你做错了什么的问题。 您正在混合使用两种非常不同的方法来处理用户输入。 e通常在事件处理程序中使用,并包含有关事件的信息。您正在使用控制台应用程序,它不会引发输入事件,您必须专门轮询输入。这就是console.readLine所做的。它返回一个包含用户输入内容的字符串。它仅在用户按下enter后返回,否则等待更多字符。您需要获取用户键入的字符串,并将其与您要查找的字符串进行比较。我使用ToLower强制字符串为全部小写字母,因此无论用户如何键入它都会匹配。

答案 1 :(得分:1)

Module Module1

    Public Event count()
    Sub Main()
        AddHandler count, AddressOf MyFunction
        Console.WriteLine("to start the countdown process type go")
        Dim input As String = Console.ReadLine() 'Already waits for 'enter'
        RaiseEvent count()


        Console.WriteLine("Press any key to exit...")
        Console.ReadKey()
    End Sub
    Sub MyFunction()
        Dim a As Integer = 16
        Dim b As Integer = 6
        Console.WriteLine("Now we are going to count to a number using only even numbers")
        Do Until b > a
            Console.WriteLine(b)
            b += 2
        Loop
        Console.ReadKey()
    End Sub

End Module
相关问题