24 April 2010

Replace a Toolbar's button image

Back in 2000 a bug report was posted describing how GFA-BASIC 32 failed to properly remove a Toolbar Ocx button. I say properly, because the button was removed, but the button count remained the same. Now in 2010 another bug was reported. The button's image couldn't be easily replaced, because the button's property .Image isn't implemented. So, the Ocx Toolbar has some flaws ....

To address the new bug, we need to find a work-around. This is easy, we must invoke Toolbar.Remove index to remove the button and than Add it again with the new image index. But for this to work properly we also need to know why Toolbar.Remove index failed in the first place. Well, the cause for the failure was quickly found; the .Remove method failed because the button wasn't assigned a key. The Toolbar's Add method takes the following (optional) arguments. Each argument is a Variant, GFA-BASIC converts the argument to a proper data-type internally.

ToolBar.Add index, key, caption, style, image

index - defines the position of the button.
key – specifies a character string used to store and retrieve the button by name.
caption – defines the string to display next to the button.
style – specifies the type of button.
image – is a key specifying the image to use from the ImageList control.

ToolBar.Remove index requires the index (== position) of the button to remove. Subsequently, most of us don't specify a key for the button, we don't need it later, do we?
Well, as a matter of fact, GFA-BASIC 32 uses the key to remove the button from the underlying Buttons collection, if it isn't specified it cannot be removed. Despite the fact that Remove requires the index (or position) only, it requires the accompanying key to actually remove. So, add a key argument to ToolBar.Add and you are good.

Now we know how to remove a button we can insert a new one. To accomplish this we must use the index argument of Add to insert a new button with a new image. The sample code looks like this:

' Add button #1
tb.Add 1, "but1" , , 0, 1
' Replace button #1
Tb.Remove 1
Tb.Add 1, "but1" , , 0, 2