当 C# WPF 中的窗口大小更改时,如何防止窗口边界超过屏幕边界?
(即限制屏幕中的窗口边界)
使用窗口的 OnSizeChanged 事件,
并像这样做:
//get Screen's Width, Height
private double screenHeight = SystemParameters.FullPrimaryScreenHeight;
private double screenWidth = SystemParameters.FullPrimaryScreenWidth;
private void MultiToolWindow_OnSizeChanged(object sender, SizeChangedEventArgs e)
{
//when window RightBoundary over screen
if (this.Left + this.Width > screenWidth)
this.Width = screenWidth-this.Left; //shrink the width
//when window DownBoundary over screen
if (this.Top + this.Height > screenHeight)
this.Height = screenHeight-this.Top; //shrink the height
}
请注意,使用此功能时,窗口的大小到内容属性应为手动,
如果没有,
您可以像这样更改它:
public void SomeMethod(){
//set to manual, this will invoke OnSizeChangedEvent at the same time but the shrink code won't work
this.SizeToContent = SizeToContent.Manual;
//this will invoke OnSizeChangedEvent and because now is manual the shrink code works
this.SizeToContent = SizeToContent.Manual;
}
执行两次以确保当窗口的原始大小到内容状态为宽度和高度时也可以生效,
第一次会将其设置为手动,收缩代码不会生效,
第二次导致状态为手动,因此收缩代码将生效。