如何在C#中为我的控件添加移动效果?

我有一个Panel在我的C#表单中,我有一个按钮。 当我单击按钮时,隐形面板显示。 而不是我希望Panel移入或滑入。例如,当您单击combobox时,下拉列表不会弹出。我希望我的Panel看起来像那样。 我怎样才能做到这一点 ?

窗口动画是Windows的内置function。 这是一个使用它的类:

using System; using System.ComponentModel; using System.Windows.Forms; using System.Runtime.InteropServices; public static class Util { public enum Effect { Roll, Slide, Center, Blend } public static void Animate(Control ctl, Effect effect, int msec, int angle) { int flags = effmap[(int)effect]; if (ctl.Visible) { flags |= 0x10000; angle += 180; } else { if (ctl.TopLevelControl == ctl) flags |= 0x20000; else if (effect == Effect.Blend) throw new ArgumentException(); } flags |= dirmap[(angle % 360) / 45]; bool ok = AnimateWindow(ctl.Handle, msec, flags); if (!ok) throw new Exception("Animation failed"); ctl.Visible = !ctl.Visible; } private static int[] dirmap = { 1, 5, 4, 6, 2, 10, 8, 9 }; private static int[] effmap = { 0, 0x40000, 0x10, 0x80000 }; [DllImport("user32.dll")] private static extern bool AnimateWindow(IntPtr handle, int msec, int flags); } 

样品用法:

  private void button2_Click(object sender, EventArgs e) { Util.Animate(button1, Util.Effect.Slide, 150, 180); } 

如果您使用的是.NET 4(如果不使用Thread替换任务),则类似于此的函数可能是一个开头:

  private void slideToDestination(Control destination, Control control, int delay, Action onFinish) { new Task(() => { int directionX = destination.Left > control.Left ? 1 : -1; int directionY = destination.Bottom > control.Top ? 1 : -1; while (control.Left != destination.Left || control.Top != destination.Bottom) { try { if (control.Left != destination.Left) { this.Invoke((Action)delegate() { control.Left += directionX; }); } if (control.Top != destination.Bottom) { this.Invoke((Action)delegate() { control.Top += directionY; }); } Thread.Sleep(delay); } catch { // form could be disposed break; } } if (onFinish != null) onFinish(); }).Start(); } 

用法:

 slideToDestination(sender as Control, panel1, 10, () => MessageBox.Show("Done!")); slideToDestination(sender as Control, panel1, 0, null); 

作为动作,您将发送一些布尔变量设置为true,以便您知道动画已完成或某些代码在其后运行。 使用null操作调用时要小心死锁。 你可以在同一个控制器上以相同的速度在两个不同的方向上运行两个动画,并且它将保持在永远的位置,当然两个动画同时可以使控制在某个方向无限地进行,因为while将永远不会完成:)

看看我去年写的图书馆:

WinForm动画库[.Net3.5 +]

一个简单的库,用于在.Net WinForm(.Net 3.5及更高版本)中设置控件/值的动画。 基于关键帧(路径)并可完全自定义。

https://falahati.github.io/WinFormAnimation/

 new Animator2D( new Path2D(new Float2D(-100, -100), c_control.Location.ToFloat2D(), 500)) .Play(c_control, Animator2D.KnownProperties.Location); 

这会将c_control控件从-100,-100移动到500 ms内的第一个位置。

对于WinForms,您可以从Panel位置关闭屏幕开始。

使用计时器,并在Tick事件中,将Panel的位置缓慢移动到视图中,直到它处于预定义的坐标。

很多方法可以给猫皮肤,但这就是我做的方法。