我曾经按照 fduenas 的建议异或绘制一个矩形,它工作得很好,但这在 Windows Vista 和 7 上运行不顺畅。此外,如果你在变化的区域(以及如果你之后删除它,矩形将保留)。
相反,我现在使用一个带有矩形孔的矩形窗口。您所要做的就是重新定位窗口。您可以在 MouseDown 中创建和显示它,在 MouseMove 中重新定位它并在 MouseUp 中销毁它。
设置TDragRectangleForm的BorderStyle为bsNone。
unit FrmDragRectangle;
// TDragRectangleForm is a rectangular window with a rectangular hole.
// Only its dotted border is visible.
interface
uses
Windows, Forms, Graphics, Classes;
type
TDragRectangleForm = class( TForm )
procedure FormResize( Sender : TObject );
public
procedure Show;
end;
implementation
{$R *.dfm}
procedure TDragRectangleForm.Show;
begin
// Show the window without stealing the focus from another window:
ShowWindow( Handle , SW_SHOWNOACTIVATE );
Visible := True;
end;
procedure TDragRectangleForm.FormResize( Sender : TObject );
const
nBorderWidth = 1;
var
hrgnRect1 , hrgnRect2 : HRGN;
begin
// Make a rectangular hole in the window:
hrgnRect1 := CreateRectRgn( 0 , 0 , Width , Height );
hrgnRect2 := CreateRectRgn( nBorderWidth , nBorderWidth , Width - nBorderWidth , Height - nBorderWidth );
CombineRgn( hrgnRect1 , hrgnRect1 , hrgnRect2 , RGN_DIFF );
SetWindowRgn( Handle , hrgnRect1 , True );
DeleteObject( hrgnRect2 );
Canvas.Pen.Style := psDot;
Canvas.Pen.Color := clWhite;
Canvas.Brush.Color := clBlack;
Canvas.Rectangle( 0 , 0 , Width , Height );
end;
end.