Change Current Control

I have a toolbar with the Cut, Copy, Paste, Delete icons on it, and I need to know when the current control changes so I can enable or disable an toolbaritem depending on the type of the current control. What is the best way of doing this?

[246 byte] By [GrantMcElroy] at [2007-12-22]
# 1

Well you have events - so that depending upon you design you may want to look at the lostfocus / gotfocus event for the controls. Which means that as you tab around the form selecting controls a different control will get the focus.

Only one control will have the focus at any one time.

spotty at 2007-8-30 > top of Msdn Tech,Visual Basic,Visual Basic Language...
# 2
You may want to look at the Form.ActiveControl property
JonathanAneja-MSFT at 2007-8-30 > top of Msdn Tech,Visual Basic,Visual Basic Language...
# 3

So, tying it all together, you might handle the GotFocus event of each control and then test to see if, based on the type of the current control, the menu items should be enabled.

You'll probably want a helper function that will attach all of the event handlers for you. This can be done very easily with a little recursive subroutine. Just call this sub at form load. Bear in mind that if you add any new controls during runtime you'll want to attach their handlers when they are created (I wouldn't call this sub more than once).

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Make a call to the handle attaching sub

Me.AttachFocusHandler(Me.Controls)

End Sub

'Create the recursive sub to add GotFocus handlers

'Be sure to fully qualify the ControlCollection; this

'is one place where imported namespaces will trip you up

Private Sub AttachFocusHandler(ByVal ctrls As System.Windows.Forms.Control.ControlCollection)

'Loop through each control in the collection

For Each ctrl As Control In ctrls

'Add the handler for the GotFocus event

AddHandler ctrl.GotFocus, AddressOf ControlGotFocus

'Call the sub again with this control's

'control collection (recursion)

Me.AttachFocusHandler(ctrl.Controls)

Next

End Sub

'Handle the GotFocus even for each control

Private Sub ControlGotFocus(ByVal sender As Object, ByVal e As System.EventArgs)

'Declare a variable to hold the value that

'the MenuItems' Enabled property will be set to

Dim en As Boolean = False

'Check to see of the Control that got

'focus is a TextBox

If sender.GetType Is GetType(TextBox) Then

'If so, enable the menu items

en = True

End If

'Set the menu items' enabled property

'to the determined value

Me.CopyToolStripMenuItem.Enabled = en

Me.CutToolStripMenuItem.Enabled = en

Me.PasteToolStripMenuItem.Enabled = en

End Sub

End Class

That should get you started. Good luck!

rkimble at 2007-8-30 > top of Msdn Tech,Visual Basic,Visual Basic Language...