mousedoubleclick不适用于动态创建的按钮

时间:2014-05-17 22:09:56

标签: vb.net mouseevent

在Button事件中,当正常将鼠标添加到表单时包含MouseDoubleClick但是当我以编程方式向表单添加按钮时,即使我自己编写程序执行没有任何错误,但MouseDoubleClick也不存在于IDE建议事件中在MouseDoubleClick事件

上没有做任何事情

这是我的代码:

Dim pb As New Button
pb.Text = "Hello"
pb.Size = New Size(150, 110)
frmAddImage.flPanel.Controls.Add(pb)

AddHandler pb.MouseDoubleClick, AddressOf pbButton_MouseDoubleClick

Private Sub pbButton_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    'Do something
End Sub

1 个答案:

答案 0 :(得分:3)

归结为以下几点:按钮通常不会使用双击事件。 但是,按钮类继承自Control,它提供了双击事件。所以它就在那里,但它并没有被全班解雇。

您可以在.Clicks事件中使用MouseEventArgs变量的MouseDown属性:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim pb As New Button
    pb.Text = "Hello"
    pb.Size = New Size(150, 110)
    frmAddImage.flPanel.Controls.Add(pb)
    AddHandler pb.MouseDown, AddressOf pbButton_MouseDown
End Sub

Private Sub pbButton_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    If e.Clicks = 2 Then
        MessageBox.Show("The button was double-clicked.")
    End If
End Sub

取自:http://social.msdn.microsoft.com/Forums/en-US/83ac6fbd-af42-4b9c-897e-142abb0a8199/can-not-use-event-double-click-on-button


解决方法 是为按钮启用StandardClick和StandardDoubleClick ControlStyles。您需要创建自己的按钮类,并在构造函数中将标志设置为true。 然后,您可以处理DoubleClick(非MouseDoubleClick)事件。

Public Class MyButton
    Inherits Button
    Public Sub New()
        MyBase.New()
        SetStyle(ControlStyles.StandardDoubleClick, True)
        SetStyle(ControlStyles.StandardClick, True)
    End Sub
End Class

像以前一样在您的其他课程中加载活动,只需创建MyButton而不是Button

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim pb As New MyButton
    pb.Text = "Hello"
    pb.Size = New Size(150, 110)
    Me.Controls.Add(pb)
    AddHandler pb.DoubleClick, AddressOf pbButton_DoubleClick
End Sub

Private Sub pbButton_DoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    MessageBox.Show("The button was double-clicked.")
End Sub
相关问题