Setting random Timer intervals in VB

人走茶凉 提交于 2019-12-12 02:14:59

问题


My goal is to make code that will beep randomly anywhere from 1 to 30 seconds apart. Here is my code so far:

Public Class Form1

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Console.Beep()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Timer1.Stop()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Timer1.Start()
End Sub
End Class

This beeps every one second. Now, I want to change the Timer Interval so that it will beep randomly between 1 and 30 seconds. Maybe later I will add options for the user to define the bounds, but for now, 1 and 30 are good numbers. I just don't know how to apply a random number to my Timer Interval.


回答1:


Change the Interval on every Tick:

Public Class Form1
  Private p_oRandom As Random

  Private Const INTERVAL_MIN_SEC As Integer = 1
  Private Const INTERVAL_MAX_SEC As Integer = 30

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    p_oRandom = New Random
  End Sub

  Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles _
                                                                      Timer1.Tick
    Console.Beep()
    Timer1.Interval = p_oRandom.Next(INTERVAL_MIN_SEC, INTERVAL_MAX_SEC) * 1000
  End Sub

End Class


来源:https://stackoverflow.com/questions/20935427/setting-random-timer-intervals-in-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!