function SetLayeredWindowAttributes(Handle: HWND;
COLORKEY: COLORREF; Alpha: BYTE; Flags: DWord): Boolean; stdcall; external 'USER32.DLL';
Const
WS_EX_LAYERED = $80000;
LWA_ALPHA = 2;
我們調用GetWindowLong函數獲取當前窗口的擴展屬性,並調用SetWindowLong函數將新的WS_EX_LAYERED窗口擴展屬性添加進去。
procedure TForm1.FormCreate(Sender: TObject);
begin
SetWindowLong(Handle,GWL_EXSTYLE,GetWindowLong(Handle,GWL_EXSTYLE) or WS_EX_LAYERED);
end;
現在我們的窗口已經可以調用SetLayeredWindowAttributes函數,通過設置該函數的Alpha參數,我們就可以看到窗口的效果的變化。
procedure TForm1.Button1Click(Sender: TObject);
begin
SetLayeredWindowAttributes(Form1.Handle, 0, 180, LWA_ALPHA);
end;
以下的VCL控件代碼封裝了SetLayeredWindowAttributes函數,編程時動態改變AlphaValue值,您就可以看到窗口的透明效果了。控件屏蔽了設計期的顯示效果,如果讀者願意可以改為設計期效果可見,不過那樣的話,一不小心,您可能就會找不著你要設計的窗體了 8-)
unit TranForm; {DragonPC 2001.2.21 }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms ;
type
TTranForm = class(TComponent)
private
FAlphaValue : integer ;
FParentFormHandle : HWND ;
procedure SetFAlphaValue(Alpha:integer) ;
protected
procedure UpdateDisplay ;
public
constructor Create(AOwner: TComponent); override;
published
property AlphaValue : integer read FAlphaValue write SetFAlphaValue ;
end;
procedure Register;
function SetLayeredWindowAttributes(Handle: HWND; COLORKEY: COLORREF;
Alpha: BYTE; Flags: DWord): Boolean; stdcall; external 'USER32.DLL';
implementation
procedure Register;
begin
RegisterComponents('Standard', [TTranForm]);
end;
procedure TTranForm.SetFAlphaValue(Alpha: integer);
begin
if (Alpha >= 0) and (Alpha < 256) then begin
FAlphaValue := Alpha ;
UpdateDisplay() ;
end;
end;
procedure TTranForm.UpdateDisplay;
begin
if (csDesigning in ComponentState) then Exit ;
SetLayeredWindowAttributes(FParentFormHandle, 0, FAlphaValue, 2);
end;
constructor TTranForm.Create(AOwner: TComponent);
begin
inherited;
if (csDesigning in ComponentState) then Exit;
FAlphaValue := 255 ;
FParentFormHandle := TForm(AOwner).Handle ;
SetWindowLong(FParentFormHandle,
GWL_EXSTYLE,
GetWindowLong(FParentFormHandle, GWL_EXSTYLE) or WS_EX_LAYERED);
end;
end.
謝謝您的莫大耐心得以看完此文,此文純粹本著賺取china-pub"假幣"目的所寫,萬一各位看官有任何的疑問,歡迎信至[email protected],謝謝。