在桌面中心定位表格时出现异常

Exception while positioning form at desktop center

我的主窗体启动时 WindowState 为 wsMaximized,Position 为 poDefault。当我点击 maximize/minimize 切换按钮时,我希望将缩小的表格放置在桌面中心。所以在 OnResize 中我放置了以下内容:

if WindowState = wsMaximized then
    Position := poDefault
 else if WindowState = wsNormal then
    Position := poScreenCenter;

当我的程序启动时,我得到这个异常:'Cannot change visible in OnShow or OnHide'。

我应该怎么做才能使我的表单最大化或正常居中?

FormResize 方法在您的表单首次显示时发生。第一次创建或展示时一定要检查表格的当前状态,不要尝试调整表格大小

procedure TForm1.FormResize(Sender: TObject);
begin
    if not(fsVisible in Self.FormState) then
      Exit;

    if WindowState = wsMaximized then
      Position := poDefault
    else
      if WindowState = wsNormal then
        Position := poScreenCenter;
end;

http://docwiki.embarcadero.com/Libraries/en/Vcl.Forms.TFormState

阅读更多内容

以下 table 列出了可以包含在表单状态中的值:

Value Meaning

fsCreating -- The form's constructor is currently executing.

fsVisible -- The form's window is visible. This state is used to update the Visible property.

fsShowing -- The form's WindowState property is changing. This state is used to prevent WindowState changes from interfering with a transition that is in progress.

fsModal -- The form was created as a modal window.

fsActivated -- The form has received focus or the application became active but has not yet called the Activate method to generate an OnActivate event.