Home > OS >  How to create a Window Resize Animation in WPF .NET5
How to create a Window Resize Animation in WPF .NET5

Time:09-16

I have tried to create a resize animation, but it doesn't really work and it's not smooth.

static System.Windows.Forms.Timer _Timer = new System.Windows.Forms.Timer();
private void timer_Tick(object sender, EventArgs e)
{
     double _Width = ScreenSizeHelperPanel.Width;
     double _Height = ScreenSizeHelperPanel.Height;
     if (MainWindow.Width != _Width || MainWindow.Height != _Height)
     {
          MainWindow.Width  = 50;
          MainWindow.Height  = 50;
          CenterWindowOnScreen();
     }
     else
     {
          _Timer.Stop();
     }
}

private void Animate() 
{
     _Timer.Tick  = new EventHandler(timer_Tick);
     _Timer.Interval = (20);
     _Timer.Start();
}

private void CenterWindowOnScreen()
{
    double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
    double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
    double windowWidth = this.Width;
    double windowHeight = this.Height;
    this.Left = (screenWidth / 2) - (windowWidth / 2);
    this.Top = (screenHeight / 2) - (windowHeight / 2);
}

ScreenSizeHelperPanel XAML:

<DockPanel Width="{x:Static SystemParameters.MaximizedPrimaryScreenWidth}" 
Height="{x:Static SystemParameters.MaximizedPrimaryScreenHeight}" 
x:Name="ScreenSizeHelperPanel"/>

Does anyone know how I can do this? I have seen this approach but it's throwing up errors about integers/doubles not existing which Idk how to fix as the automated system breaks the code further instead of fixing.

CodePudding user response:

From your answer to my comment, I can give you a super simple way to make a smooth resize animation, with 3 lines of code.

Essentially what you can do, is change the windows style to being a singleborder or 3dborderwindow and settings it's window state to maximized, since borderless windows do not have resize animations, right after you can set it back to a borderless window, this is not really noticable as it happens in less than 3s.

WindowStyle = WindowStyle.SingleBorderWindow;
WindowState = WindowState.Maximized;
WindowStyle = WindowStyle.None;

If you do however, want custom animations, slower ones etc. You may research on WPF Animations as mentioned in the comments, however if this answer fits your needs, I was glad to help!

  • Related