|Transparent Button||Lab Report|
The purpose of this project was to create simulated transparent buttons that could be placed over an image.
Materials and Equipment
Delphi 3/4 (to recompile)
A TBevel and a TLabel are placed on top of a TImage to simulate a transparent button over an image.
Place the TBevel and TLabel on top of the TImage. If the TBevels or TLabels are already on the form, you can cut and paste them back onto the form to change the "z order" to be on top of the TImage. Otherwise, consider using the BringToFront method.
The TLabel object still receives OnMouse events, but the TBevel object doesn't receive any events. In fact the TBevel "absorbs" the mouse events unless Bevel.Enabled is set to FALSE in the FormCreate method.
Position the TLabel inside the TBevel and set the Font, Alignment and AutoSize properties as desired. You'll probably want to set the Transparent property of the TLabel to TRUE.
The OnMouse Events from the TImage are inspected for activity over the TBevel objects, including OnMouseDown for "clicks" and OnMouseMove for "hover button" behavior.
To simplify determining whether the (X,Y) mouse event over the TImage correspond to one of the TBevels, a rectangle based on the image coordinates, Bevel1RectInImageCoordinates below, is computed in the FormCreate:
|VAR BasePoint: TPoint;
// Do this once to improve efficiency of PtInRect calculations
BasePoint := Image.ScreenToClient( ClientToScreen( Point(Bevel1.Left, Bevel1.Top)) );
BasePoint.X + Bevel1.Width,
BasePoint.Y + Bevel1.Height);
Then in the ImageMouseDown and ImageMouseMove methods, an IF statement determines if the mouse event corresponds to a specific TBevel:
The ImageMouseMove was used to create a "hover button" effect, while the ImageMouseDown was used as a Bevel OnClick.
The FocusControl keyboard shortcut of the TLabels cannot be used, but the TForm's OnKeyDown can be used to trigger Alt-Key keyboard shortcuts.
This is an extension of an idea shown in How to Program Delphi 3 by Frank Engo, pp. 290-291. In the original article, mouse events were only tied to the TLabel of the TLabel-TBevel pair.
A better approach would be to capture CM_MouseEnter and CM_MouseExit events. In Chapter 13 of Mastering Delphi 5 (pp. 608-609), Marco Cantý shows how to create an "active" TMdActiveButton component.
A transparent label over an image can add a nice effect to an application.
I only needed two transparent buttons, just like shown here, in a rather large project, so I used the technique shown here. If you want many transparent buttons in a variety of projects, you may want to consider making a visual component.
Transparent button, Hover button, TBevel, TLabel, ClientToScreen, ScreenToClient, MouseMove, MouseDown, keyboard shortcut
Delphi 3/4 Source Code (95 KB): TransparentButton.ZIP
Updated 26 Feb 2005
since 20 Feb 1998