Ctrl-Clicking to select controls at runtime
I have several textboxes and buttons in my form i want to select some textbox by using control key and click.
any ideas.
Also when i select a control i want to display focus ring.
Thanks
Dear mameenkhn,
Use a boolean variable flag to declare that control is still pressed on both of KeyUp and KeyDown events.
Use KeyPreview=True to make your form handles all key strokes done on all of its contained controls.
ControlPaint.DrawFocusRectangle() is used to draw the focus rect.
Place two textboxes in your form then set the KeyPreview Property = True
then paste the following code:
Private mclnSelectedControls As New Collection 'stores all selected items
Private mblnControlPressed As Boolean 'will be set to true if control is pressedPrivate Sub Form_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
mblnControlPressed = e.Control End Sub
Private Sub Form_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
mblnControlPressed = e.Control If Not mblnControlPressed Then
Call mclnSelectedControls.Clear() 'No controls are no longer selected Me.Refresh() 'remove all focus rects End If
End Sub Private Sub TextBox_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox2.MouseUp, TextBox1.MouseUp
Dim intControlCounter As Integer On Error Resume Next If Not mblnControlPressed Then Exit Sub
Call mclnSelectedControls.Add(sender, sender.name) 'Attempt to add the sender to selected items with its name as a key
If Err.Number <> 0 Then
'Already exists, Toggle disselect the control Call mclnSelectedControls.Remove(sender.name) End If Call Me.Refresh() 'Clear all focus rects
For intControlCounter = 1 To mclnSelectedControls.Count
With mclnSelectedControls.Item(intControlCounter)
'Show focus rect on this selected control ControlPaint.DrawFocusRectangle(Graphics.FromHwnd(.Handle), .DisplayRectangle) End With Next End Sub
Then add this code to create event handlers for the text boxes on the whole form at runtime
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intControlIndex As Integer
For intControlIndex = 0 To Me.Controls.Count - 1
With Me.Controls.Item(intControlIndex)
If .GetType().ToString() = "System.Windows.Forms.TextBox" Then
AddHandler Me.Controls.Item(intControlIndex).MouseUp, AddressOf TextBox_MouseUp
End If
End With
Next
End Sub