Many commercial applications (mostly games) uses (semi) transparent forms to
attract the users. Under Windows 2000 or better you can make your Delphi forms
transparent by calling SetLayeredWindowAttributes with the desired constant alpha
value and/or the color-key.
Note that the third parameter of SetLayeredWindowAttributes is a value that ranges
from 0 to 255, with 0 making the window completely transparent and 255 making it
completely opaque.
For using this function you have to add following code to your Delphi application:
1 const
2 WS_EX_LAYERED = $80000;
3 LWA_COLORKEY = 1;
4 LWA_ALPHA = 2;
5
6 type
7 TSetLayeredWindowAttributes = function (
8 hwnd : HWND; // handle to the layered window
9 crKey : TColor; // specifies the color key
10 bAlpha : byte; // value for the blend function
11 dwFlags : DWORD // action
12 ): BOOL; stdcall;
13
14 procedure SetTransparentForm(AHandle : THandle; AValue : byte = 0);
15 var
16 Info: TOSVersionInfo;
17 SetLayeredWindowAttributes: TSetLayeredWindowAttributes;
18 begin
19 //Check Windows version
20 Info.dwOSVersionInfoSize := SizeOf(Info);
21 GetVersionEx(Info);
22 if (Info.dwPlatformId = VER_PLATFORM_WIN32_NT) and
23 (Info.dwMajorVersion >= 5) then
24 begin
25 SetLayeredWindowAttributes := GetProcAddress(GetModulehandle(user32),
26 'SetLayeredWindowAttributes');
27 if Assigned(SetLayeredWindowAttributes) then
28 begin
29 SetWindowLong(AHandle, GWL_EXSTYLE, GetWindowLong(AHandle, GWL_EXSTYLE) or
30 WS_EX_LAYERED);
31 //Make form transparent
32 SetLayeredWindowAttributes(AHandle, 0, AValue, LWA_ALPHA);
33 end;
34 end;
35 end;
36
37 //Now you can create OnCreate event handler and put next code:
38
39 procedure TForm1.FormCreate(Sender: TObject);
40 begin
41 SetTransparentForm(Handle, 100);
42 end;
Run the application. Just remember, that SetLayeredWindowAttributes
function not available for Windows 98 or Windows NT 4.0
If you want to setup transparency in percents you can use following formula: (255 *
Percents) / 100.
You don't need to write a lot of code to fade a window in or out.
The following example shows how to create fade out effect.
First you form become slowly transparent and after disappear from screen completely.
43 procedure TForm1.Button1Click(Sender: TObject);
44 var I : integer;
45 begin
46 for i := 100 downto 0 do
47 begin
48 SetTransparentForm(Handle,i);
49 Application.ProcessMessages;
50 end;
51 Close;
52 end;
It is also possible to make a transparent standard Windows dialog like TFontDialog.
To have a dialog box come up as a translucent window,
first create the dialog as usual. Then, create OnShow event handler and make your
dialog transparent in the same way as a form.
53 procedure TForm1.FontDialogShow(Sender: TObject);
54 begin
55 SetTransparentForm(FontDialog.Handle, 100);
56 end;
|