在onresize里面写form1.postion:=poScreenCenter;报错?
在onresize里面写form1.postion:=poScreenCenter;报错?
出现 'can't change visible in OnShow and Onhide ‘错误!
写在Oncreate里面肯定是可以的,但为什么写onresize里面不行?
form1.width和form1.heght都可以控制,form1.postion:=poScreenCenter;却报错?
[解决办法]
- Delphi(Pascal) code
procedure TCustomForm.SetWindowToMonitor;var AppMon, WinMon: HMONITOR; I, J: Integer; ALeft, ATop: Integer; LRect: TRect;begin if (FDefaultMonitor <> dmDesktop) and (Application.MainForm <> nil) then begin AppMon := 0; if FDefaultMonitor = dmMainForm then AppMon := Application.MainForm.Monitor.Handle else if (FDefaultMonitor = dmActiveForm) and (Screen.ActiveCustomForm <> nil) then AppMon := Screen.ActiveCustomForm.Monitor.Handle else if FDefaultMonitor = dmPrimary then AppMon := Screen.PrimaryMonitor.Handle; WinMon := Monitor.Handle; for I := 0 to Screen.MonitorCount - 1 do if (Screen.Monitors[I].Handle = AppMon) then if (AppMon <> WinMon) then begin for J := 0 to Screen.MonitorCount - 1 do begin if (Screen.Monitors[J].Handle = WinMon) then begin if FPosition = poScreenCenter then begin LRect := Screen.Monitors[I].WorkareaRect; SetBounds(LRect.Left + ((RectWidth(LRect) - Width) div 2), LRect.Top + ((RectHeight(LRect) - Height) div 2), Width, Height); end else if FPosition = poMainFormCenter then begin SetBounds(Screen.Monitors[I].Left + ((Screen.Monitors[I].Width - Width) div 2), Screen.Monitors[I].Top + ((Screen.Monitors[I].Height - Height) div 2), Width, Height) end else begin ALeft := Screen.Monitors[I].Left + Left - Screen.Monitors[J].Left; if ALeft + Width > Screen.Monitors[I].Left + Screen.Monitors[I].Width then ALeft := Screen.Monitors[I].Left + Screen.Monitors[I].Width - Width; ATop := Screen.Monitors[I].Top + Top - Screen.Monitors[J].Top; if ATop + Height > Screen.Monitors[I].Top + Screen.Monitors[I].Height then ATop := Screen.Monitors[I].Top + Screen.Monitors[I].Height - Height; SetBounds(ALeft, ATop, Width, Height); end; end; end; end else begin if FPosition = poScreenCenter then begin LRect := Screen.Monitors[I].WorkareaRect; SetBounds(LRect.Left + ((RectWidth(LRect) - Width) div 2), LRect.Top + ((RectHeight(LRect) - Height) div 2), Width, Height); end; end; end;end;
[解决办法]
procedure TCustomForm.SetWindowToMonitor;
...
if FPosition = poScreenCenter then SetBounds(...)
因为 form1.postion:=poScreenCenter 会改变 form1 的尺寸和位置,在 onResize 中
执行到 form1.postion:=poScreenCenter 时会重新激活 onResize 事件,造成死循环。