EmPlusPlus
EmPlusPlus

Reputation: 181

mousedoubleclick doesnt work for dynamically created button

In Button events MouseDoubleClick is included when normally add it to the form but when I programmatically add buttons to the form MouseDoubleClick doesn't exist in IDE suggestion events even if I write by myself the program execute without any error but it doesn't do anything on MouseDoubleClick event

here is my code:

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

Upvotes: 1

Views: 2518

Answers (1)

Jens
Jens

Reputation: 6375

What it boils down to is the following: Buttons don't normally use the double-click event. The button class however inherits from Control which provides the double-click event. So it is there but it's not fired by the class.

You can use the .Clicks property of the MouseEventArgs variable in the MouseDown event though:

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

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


A workaround is to enable the StandardClick and StandardDoubleClick ControlStyles for the button. You need to create your own button class and set the flags to true in the constructor. Then you can handle the DoubleClick (NOT MouseDoubleClick) event.

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

Wire the event up in your other class as before, just create a MyButton and not a 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

Upvotes: 4

Related Questions