Delphi笔记-自定义提示窗口

unit pbHint;

interface

uses
  Windows, Controls, Forms, Graphics;

type
  TPBHint=class(THintWindow) //要自定义提示窗口类,必须从THintWindow类继承
  private
    FRegion:THandle;  //保存当前提示窗口的区域句柄,用来设置窗口的形状
    procedure FreeCurrentRegion;  //释当前的区域句柄
    procedure SetRegion(Rect:TRect);
  public
    Destructor Destroy;override;  //复盖析构函数
    procedure ActivateHint(Rect:TRect;const AHint:String);override;  //复盖该方法,在提示窗口弹出前,设置窗口的形状
    procedure CreateParams(var params:TCreateParams);override; //复盖该方法,去掉WS_Border属性
    procedure Paint;override; //复盖该方法,改变画笔的颜色,然后再画出提示内容
  end;

implementation

{ TPBHint }

procedure TPBHint.ActivateHint(Rect: TRect; const AHint: String);
begin
  with Rect do
  begin
    Right:=Right+Canvas.TextWidth('WWWW'); //这一句是为了让提示窗口的宽度增大4个字符
    Bottom:=Bottom+Canvas.TextHeight('WWWWWW');
  end;
  SetRegion(Rect);
  inherited;
end;

procedure TPBHint.CreateParams(var params: TCreateParams);
begin
  inherited;
  params.Style:=params.Style and (not WS_BORDER);
end;

destructor TPBHint.Destroy;
begin
  FreeCurrentRegion;
  inherited;
end;

procedure TPBHint.FreeCurrentRegion;
begin
  if FRegion<>0 then
  begin
    SetWindowRgn(Self.Handle,0,true);
    DeleteObject(FRegion);
    FRegion:=0;
  end;
end;

procedure TPBHint.Paint;
var tempRect:TRect;
begin
  tempRect:=ClientRect;
  Inc(tempRect.top,12);
  Canvas.Font.Color:=clRed;
  Canvas.Brush.Color:=clWhite;
  DrawText(Canvas.Handle,PChar(Caption),Length(Caption),tempRect,DT_NOPREFIX or DT_WORDBREAK or DT_CENTER or DT_VCENTER);
end;

procedure TPBHint.SetRegion(Rect: TRect);
var tempRgn:HRGN;
begin
  BoundsRect:=Rect;
  FreeCurrentRegion;
  with BoundsRect do
  begin
    FRegion:=CreateRoundRectRgn(0,0,Width,Height,15,15);
    tempRgn:=CreateRectRgn(0,0,Width div 2-2,10);
    CombineRgn(FRegion,FRegion,tempRgn,RGN_DIFF);
    tempRgn:=CreateRectRgn(Width div 2+2,0,Width,10);
    CombineRgn(FRegion,FRegion,tempRgn,RGN_DIFF);
  end;
  if FRegion<>0 then
    SetWindowRgn(Self.Handle,FRegion,true);
end;

initialization
  Application.ShowHint:=false;  //先禁止提示窗口
  HintWindowClass:=TPBHint;   //将自定义的提示窗口类赋值给全局变量HintWindowClass,就可以替换掉原来的提示窗口了
  Application.ShowHint:=true; //开启提示窗口
  Application.HintColor:=clBlue; //改变提示窗口的背景颜色
  
end.
原文地址:https://www.cnblogs.com/yzryc/p/6386073.html