從頭創建 Visual Basic .NET 控件 (六)
2024-07-10 13:04:02
供稿:網友
菜鳥學堂:
第 5 步:使控件響應用戶
要允許用戶更改燈的顏色,必須檢測到用戶的鼠標單擊操作。有經驗的 visual basic 開發人員都知道,可以使用多種方法實現這一目的。我們使用最簡單的一種方法,即檢測 mouseup 事件。下面是檢測用戶單擊并更改 status 屬性以與之匹配的代碼:
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
事件處理非常簡單。檢查鼠標單擊的位置和每個圓心之間的距離。(請注意,圓心分別位于控件下方 1/6、1/2 和 5/6 的位置。如果不太明白,可以在紙上畫出來看看。)如果計算出的距離小于圓的半徑,則更改 status 屬性。
距離由 distance 函數使用您可能在代數課中學過的公式計算。請注意,平方根函數是從 system.math 命名空間中獲得的,數學函數通常都保存在該命名空間中。