visual| Create | Control step 5th: Make the control respond to the user
To allow the user to change the color of the lamp, you must detect the user's mouse click action. As experienced visual Basic developers know, there are a number of ways you can accomplish this. We use the simplest method of detecting MouseUp events. Here is the code that detects that the user clicked and changed the Status property to match it:
Private Sub Trafficlight_mouseup (ByVal sender as Object, _
ByVal e as System.Windows.Forms.MouseEventArgs) _
Handles Mybase.mouseup
Dim Nmidpointx as Integer = CInt (Me.Size.Width * 0.5)
Dim Ncircleradius as Integer = Nmidpointx
If Distance (e.x, E.y, Nmidpointx, CInt (ME.SIZE.HEIGHT/6)) _
< Ncircleradius Then
Me.status = trafficlightstatus.statusred
Exit Sub
End If
If Distance (e.x, E.y, Nmidpointx, CInt (ME.SIZE.HEIGHT/2)) _
< Ncircleradius Then
Me.status = Trafficlightstatus.statusyellow
Exit Sub
End If
If Distance (e.x, E.y, Nmidpointx, CInt ((5 * Me.Size.Height)/6)) _
< Ncircleradius Then
Me.status = Trafficlightstatus.statusgreen
End If
End Sub
Private Function Distance (ByVal X1 as Integer, _
ByVal Y1 as Integer, _
ByVal X2 as Integer, _
ByVal y2 As Integer) As Integer
Return CInt (System.Math.Sqrt (x1-x2) ^ 2 + (Y1-y2) ^ 2))
End Function
Event handling is very simple. Check the location of the mouse click and the distance between each center. (Note that the center of the circle is positioned 1/6, 1/2, and 5/6 below the control respectively.) If you do not understand, you can draw on the paper to see. If the calculated distance is less than the radius of the circle, the Status property is changed.
The distance is calculated by using the Distance function that you might have learned in algebra class. Note that the square root function is obtained from the System.Math namespace, and the mathematical functions are usually kept in that namespace.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.