Mega Code Archive

 
Categories / Delphi / Examples
 

Transparent forms in delphi 5 and 6

How to make a transparent form under Windows 2000 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: const WS_EX_LAYERED = $80000; LWA_COLORKEY = 1; LWA_ALPHA = 2; type TSetLayeredWindowAttributes = function ( hwnd : HWND; // handle to the layered window crKey : TColor; // specifies the color key bAlpha : byte; // value for the blend function dwFlags : DWORD // action ): BOOL; stdcall; procedure SetTransparentForm(AHandle : THandle; AValue : byte = 0); var Info: TOSVersionInfo; SetLayeredWindowAttributes: TSetLayeredWindowAttributes; begin //Check Windows version Info.dwOSVersionInfoSize := SizeOf(Info); GetVersionEx(Info); if (Info.dwPlatformId = VER_PLATFORM_WIN32_NT) and (Info.dwMajorVersion >= 5) then begin SetLayeredWindowAttributes := GetProcAddress(GetModulehandle(user32), 'SetLayeredWindowAttributes'); if Assigned(SetLayeredWindowAttributes) then begin SetWindowLong(AHandle, GWL_EXSTYLE, GetWindowLong(AHandle, GWL_EXSTYLE) or WS_EX_LAYERED); //Make form transparent SetLayeredWindowAttributes(AHandle, 0, AValue, LWA_ALPHA); end; end; end; Now you can create OnCreate event handler and put next code: procedure TForm1.FormCreate(Sender: TObject); begin SetTransparentForm(Handle, 100); 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. procedure TForm1.Button1Click(Sender: TObject); var I : integer; begin for i := 100 downto 0 do begin SetTransparentForm(Handle,i); Application.ProcessMessages; end; Close; 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. procedure TForm1.FontDialogShow(Sender: TObject); begin SetTransparentForm(FontDialog.Handle, 100); end; You can use an examples from this article in Delphi 5 as well as in Delphi 6.