如何捕获控件的按钮单击 [英] how to capture the button’s click of a control
本文介绍了如何捕获控件的按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我制作了一个包含按钮数组的控件.单击后,所选按钮将显示为彩色.
我不知道如何知道在调用表单中按下了哪个按钮.
特此使用所使用的代码.
I made a control filled with a button array. On click the selected button is colored.
I cannot figure out how to know which button was pressed in the calling form.
Hereby the used code.
Public Class ButtonsTemplate
Private _buttons() As Windows.Forms.Button
Private _selectedButton As Integer
Public Sub New()
InitializeComponent()
End Sub
Public ReadOnly Property SelectedButton As Integer
Get
Return _selectedButton
End Get
End Property
Public Sub Buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim btn As Button = CType(sender, Button)
Dim name As String = btn.Name
Dim index As Integer = CInt(name.Substring(6))
ColorButtons(index)
_selectedButton = index
End Sub
Public Sub CreateNew(ByVal number As Integer)
ReDim _buttons(number - 1)
Me.Height = 100
Me.Width = 100
For i As Integer = 0 To number - 1
_buttons(i) = New Windows.Forms.Button
_buttons(i).Width = Me.Width
_buttons(i).Height = Me.Height * 1 / number
_buttons(i).Name = "Button" + CStr(i)
Me.Controls.Add(_buttons(i))
AddHandler _buttons(i).Click, AddressOf Buttons_Click
Next
For i As Integer = 1 To number - 1
_buttons(i).Top = _buttons(i - 1).Bottom
Next
ColorButtons()
End Sub
Private Overloads Sub ColorButtons()
For i As Integer = 0 To UBound(_buttons)
_buttons(i).BackColor = Color.White
Next
End Sub
Private Overloads Sub ColorButtons(ByVal index As Integer)
ColorButtons()
_buttons(index).BackColor = Color.Red
End Sub
End Class
Public Class Form1
Private obj As New ButtonsTemplate.ButtonsTemplate
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.Controls.Add(obj)
obj.CreateNew(4)
AddHandler obj.Click, AddressOf Object_Click
End Sub
Private Sub Object_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
''this event is never fired
''except when I change line "_buttons(i).Height = Me.Height * 1 / number"
''into "... * 0.5..." and when I click on the pane itself
''but that is not what I want...
Dim buttonNumber As Integer
buttonNumber = obj.SelectedButton
MessageBox.Show("Selected button = " + CStr(buttonNumber))
End Sub
End Class
推荐答案
由于您要将sender
事件处理程序参数转换为按钮,并且由于该按钮将是启动事件的按钮,所以为什么不不是直接使用它,而不是带着子串和相关垃圾四处走动吗?
Since you are converting thesender
event handler parameter to a button, and since that button will be the button that initiated the event, why don''t you just use it directly instead of going round the houses with substring and related rubbish?
Public Sub Buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim btn As Button = CType(sender, Button)
btn.BackColor = Color.Red
End Sub
这篇关于如何捕获控件的按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文