SizeChange时防止超出屏幕边界的窗口边界

时间:2016-05-24 09:04:04

标签: c# wpf

如果在C#WPF中窗口大小变化时如何防止窗口边界超出屏幕边界?

(这是屏幕中限制窗口边界)

1 个答案:

答案 0 :(得分:0)

使用Window的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
 }

请注意,使用此窗口时,Window的SizeToContent属性应为手动,

如果没有,

你可以改变它:

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;


}

做两次以确保窗口的原始SizeToContent状态是WidthAndHeight也可以生效,

第一次将其设置为手动,缩小代码将不会生效,

和第二次导致状态为手动,因此缩小代码将生效。