user4954249
user4954249

Reputation:

Do While Loop Going Until Button State Has Changed

I want in a MouseDown event in a Winforms to be able to do some code until either a certain amount of seconds or MouseUp event has been fired off

I want something like this

Dim counter As Integer = 0
Do Until Button.Key IsNot MouseDown
    counter += 1
    If counter > 3
        Exit Do Loop
    End If
    Application.DoEvents()
Loop

Right now I have it like

seconds = 0
m_mouseButtonIsNotDown = False
Do Until m_mouseButtonIsNotDown
   If e.Button = Windows.Forms.MouseButtons.Left Then
       seconds += 1
       If seconds > 5 Then
            m_mouseButtonIsNotDown = True
       End If
   End If
   Application.DoEvents()
Loop

The desired behavior I am looking for is if they let go of the button within a certain amount of loops to handle the code that would be if it was just a simple mouseclick event. If the mousedown has been held for more then 3 or 5 seconds switch to drag and drop mode so they can move the desired row to another datagridview. I have tried to use Timer and StopWatch classes and it doesn't work how I would have expected it too. It doesn't work if I have a mouseclick event and the mousedown event since the mousedown executes over the basic click event. Any ideas? Keep in mind that it can't be dependent on a mouseUp event since the drag and drop can't have it.

Upvotes: 0

Views: 465

Answers (1)

Hans Passant
Hans Passant

Reputation: 941267

Never, never use DoEvents() to solve a problem. A Timer can be made to work. But it is not the correct way to go about it. You want to start a drag when the user moved the mouse enough while holding down the left button. Like this:

Private downPos As Point

Private Sub DataGridView1_MouseDown(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseDown
    downPos = e.Location
End Sub

Private Sub DataGridView1_MouseMove(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseMove
    If e.Button = MouseButtons.Left Then
        If Math.Abs(downPos.X - e.X) >= SystemInformation.DoubleClickSize.Width Or
           Math.Abs(downPos.Y - e.Y) >= SystemInformation.DoubleClickSize.Height Then
            Dim hit = DataGridView1.HitTest(downPos.X, downPos.Y)
            If hit.RowIndex >= 0 Then
                '' Start dragging row
                ''...
            End If
        End If
    End If
End Sub

Upvotes: 1

Related Questions