我左边有一个带有TTreeview的表单,右边有一个TGroupbox。通过拖动右边缘调整窗体大小时,我希望Groupbox相应地增大或缩小。当表单在左侧拖动时,我希望Treeview调整大小。我尝试了下面的代码,正确调整大小的工作正常。但是左侧调整大小会导致树视图长得比它应该长。实现这一目标的正确方法是什么?
procedure TForm1.FormResize(Sender: TObject);
var
p: TPoint;
begin
P:= ScreenToClient(Mouse.CursorPos);
if(P.X<0) then begin
Treeview1.Anchors:= [akLeft,akTop,akRight,akBottom];
Groupbox1.Anchors:= [akTop,akBottom];
end
else begin
Treeview1.Anchors:= [akLeft,akTop,akBottom];
Groupbox1.Anchors:= [akLeft,akTop,akRight,akBottom];
end;
end;
答案 0 :(得分:2)
我认为当您调整左侧窗口的大小时,您忘记在Groupbox右侧锚定。
procedure TForm1.FormResize(Sender: TObject);
var
p: TPoint;
begin
if GetAsyncKeyState(VK_LBUTTON) and $8000 <> 0 then exit;
P:= ScreenToClient(Mouse.CursorPos);
if(P.X<0) then begin
Treeview1.Anchors:= [akLeft, akTop, akRight, akBottom];
Groupbox1.Anchors:= [akTop, akRight, akBottom];
end
else begin
Treeview1.Anchors:= [akLeft, akTop, akBottom];
Groupbox1.Anchors:= [akLeft, akTop, akRight, akBottom];
end;
end;
我尝试了它,似乎做了你想做的事情
编辑:
您还可以使用 Align 属性(请注意订单,最后使用'alClient'值的组件):
procedure TForm1.FormResize(Sender: TObject);
var
p: TPoint;
begin
if GetAsyncKeyState(VK_LBUTTON) and $8000 <> 0 then exit;
P:= ScreenToClient(Mouse.CursorPos);
if(P.X<0) then begin
Groupbox1.Align:= alRight;
Treeview1.Align:= alClient;
end
else begin
Treeview1.Align:= alLeft;
Groupbox1.Align:= alClient;
end;
end;
编辑2:检查鼠标左键的状态
您可以使用Winapi的GetAsyncKeyState(vKey)函数检查按钮或键的状态。 如果按下按钮,它将返回SmallInt中按钮的状态,位15 0/1。
答案 1 :(得分:2)
而不是处理OnResize
事件,而是取而代之的是拦截WM_SIZING
消息
发送到用户正在调整大小的窗口。 通过处理此消息,应用程序可以监控拖动矩形的大小和位置,并根据需要更改其大小或位置。
它的wParam
值可以准确地告诉您正在调整窗口的哪个边缘。您可以使用它来相应地调整Anchors
,例如:
type
TForm1 = class(TForm)
TreeView1: TTreeView;
GroupBox1: TGroupBox;
private
{ Private declarations }
procedure WMSizing(var Message: TMessage); message WM_SIZING;
public
{ Public declarations }
end;
...
procedure TForm1.WMSizing(var Message: TMessage);
var
TreeViewAnchors: TAnchors;
GroupBoxAnchors: TAnchors;
begin
inherited;
TreeViewAnchors := [akTop, akBottom];
GroupBoxAnchors := [akTop, akBottom];
case Message.WParam of
WMSZ_LEFT, WMSZ_BOTTOMLEFT, WMSZ_TOPLEFT: begin
TreeViewAnchors := TreeViewAnchors + [akLeft, akRight];
GroupBoxAnchors := GroupBoxAnchors + [akRight];
end;
WMSZ_RIGHT, WMSZ_BOTTOMRIGHT, WMSZ_TOPRIGHT: begin
TreeViewAnchors := TreeViewAnchors + [akLeft];
GroupBoxAnchors := GroupBoxAnchors + [akLeft, akRight];
end;
end;
TreeView1.Anchors := TreeViewAnchors;
GroupBox1.Anchors := GroupBoxAnchors;
end;