Domanda

OK so here's my code so far.

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

I'm trying to raise the event count when the enter key is pressed. What am I doing wrong?

È stato utile?

Soluzione

Try this

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

To specifically answer your question about what you are doing wrong. You are mixing up two very different methods for working with user input. e is usually used inside an event handler and contains information about the event. You are working in a console application though, which doesn't raise event for input, you have to specifically poll for input. This is what console.readLine does. It returns a string that contains what the user typed. It only returns after the user pressed enter, otherwise it waits for more character. You need to get the string that the user typed and compare it to the string you are looking for. I used ToLower to force the string to all lowercase letters in so it would match no matter how the user typed it.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top