|
|
Title | Make buttons jump randomly around the screen in Visual Basic .NET |
Description | This example shows how to make buttons jump randomly around the screen in Visual Basic .NET. |
Keywords | button, jump, random, game, VB.NET |
Categories | VB.NET, Miscellany, Puzzles and Games |
|
|
The form's BackColor and TransparencyKey properties were set to red at design time so the form itself is invisible. It is displayed maximized so its contents can be anywhere on the screen.
The form's Load event handler shown in the following code creates 20 buttons and gives each a Click event handler. That event handler closes the form.
When the form's Timer fires, its event handler moves the next button in sequence to a new random location. (To make the program more annoying, only assign the event handler to one of the buttons.
|
|
Private m_Buttons(19) As Button
Private rand As New Random
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To m_Buttons.Length - 1
Dim btn As New Button
m_Buttons(i) = btn
btn.Text = "Click Me"
btn.Size = New Size(75, 23)
btn.BackColor = Color.Cyan
AddHandler btn.Click, AddressOf btnClickMe_Click
Me.Controls.Add(btn)
Next i
End Sub
Private Sub btnClickMe_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Me.Close()
End Sub
Private Sub tmrMove_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles tmrMove.Tick
Static i As Integer = 0
i = (i + 1) Mod m_Buttons.Length
Dim x As Integer = rand.Next(0, Me.ClientSize.Width - _
m_Buttons(i).Width)
Dim y As Integer = rand.Next(0, Me.ClientSize.Height - _
m_Buttons(i).Height)
m_Buttons(i).Location = New Point(x, y)
'For Each btn As Button In m_Buttons
' Dim x As Integer = rand.Next(0,
' Me.ClientSize.Width - btn.Width)
' Dim y As Integer = rand.Next(0,
' Me.ClientSize.Height - btn.Height)
' btn.Location = New Point(x, y)
'Next btn
End Sub
|
|
|
|
|
|