Determine closest control to MouseUp event?
"Auric__" wrote in message
Is there an easy, accurate method to determine the closest control to a
MouseUp (or MouseDown, if it's easier) event, if the user clicks on the
UserForm instead of a control? (My form will be used on a touch screen.)
My current best guess is to do it manually (so to speak): look at the
coordinates of the click, and then look at the coordinates of each control
and decide which one is closest. I'm sure it'll work, but it's going to be
a
PITA, and I'm looking for something built-in, or alternately code that's
already been written. (My google-fu has failed me here.)
If I follow your objective try this
Private Sub UserForm_Initialize()
Dim r As Single, c As Single
Dim ctl As MSForms.Control
Const pad As Single = 18
Const ht As Single = 18
Const wd As Single = 90
For c = 0 To 2
For r = 0 To 5
Set ctl = Me.Controls.Add("Forms.CommandButton.1")
With ctl
.Left = 9 + c * (pad + wd)
.Top = 9 + r * (pad + ht)
.Width = wd
.Height = ht
.Caption = .Name
End With
Next
Next
End Sub
Private Sub UserForm_MouseUp(ByVal Button As Integer, _
ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
Dim ctl As MSForms.Control
Dim idx As Long, idxMin As Long
Dim z As Single, zMin As Single
zMin = 1234567
idxMin = -1
For Each ctl In Me.Controls
With ctl
If .Left <= X And .Left + .Width = X Then
If .Top Y Then
z = .Top - Y
Else
z = Y - .Top - .Height
End If
ElseIf .Top <= Y And .Top + .Height = Y Then
If .Left X Then
z = .Left - X
Else
z = X - .Left - .Width
End If
ElseIf .Left X Then
If .Top Y Then
z = ((.Left - X) ^ 2 + (.Top - Y) ^ 2) ^ 0.5
Else
z = ((.Left - X) ^ 2 + (Y - .Top - .Height) ^ 2) ^ 0.5
End If
Else
If .Top Y Then
z = ((X - .Left - .Width) ^ 2 + (.Top - Y) ^ 2) ^ 0.5
Else
z = ((X - .Left - .Width) ^ 2 + (Y - .Top - .Height) ^ 2) ^ 0.5
End If
End If
End With
If z < zMin Then
zMin = z: idxMin = idx
End If
idx = idx + 1
Next
If idxMin = 0 Then
Me.Controls(idxMin).SetFocus
End If
End Sub
** only lightly tested! **
Regards,
Peter T
|