设置TCustomForm.PopupParent触发RecreateWnd致Top/Left等属性重置问题
问题解答
你的写法是正确有效的,核心逻辑是先保存窗体当前的位置与尺寸,在设置PopupParent触发窗口重建后,主动创建句柄并恢复原始参数,确实能解决参数被重置的问题。
更优雅的实现方式
1. 封装到窗体类(推荐)
如果这个窗体是你自定义的,可以重写RecreateWnd方法,在窗口重建前后自动保存和恢复边界参数,避免每次调用都写重复的保存恢复代码:
type TYourForm = class(TForm) private FPrevBounds: TRect; protected procedure RecreateWnd; override; end; procedure TYourForm.RecreateWnd; begin // 重建前保存当前边界(仅当句柄已分配时) if HandleAllocated then FPrevBounds := Self.BoundsRect; inherited RecreateWnd; // 重建后恢复边界(如果之前有保存的有效数据) if not FPrevBounds.IsEmpty then Self.BoundsRect := FPrevBounds; end;
这样无论在何处设置PopupParent,窗口重建后都会自动恢复之前的位置和尺寸,无需额外编写重复代码。
2. 调整设置顺序(适用于动态创建窗体场景)
如果窗体是动态创建的,可以先设置PopupParent,再设置位置尺寸,这样不会触发RecreateWnd(因为此时窗口句柄还未创建):
formForShow := TYourForm.Create(nil); try formForShow.PopupParent := PopUpParentForModal; formForShow.SetBounds(saveLeft, saveTop, saveWidth, saveHeight); Result := formForShow.ShowModal; finally formForShow.Free; end;
内容的提问来源于stack exchange,提问作者Pit
相关产品推荐
相关产品推荐

