如何在C#中为我的控件添加运动效果?我的C#窗体中有一个面板,并且有一个按钮。当我点击按钮时,不可见的面板就会显示出来。相反,我希望面板移入或滑入。例如,当您单击组合框时,不会弹出下拉列表。我希望我的面板看起来像那样。我怎样才能做到这一点?窗口动画是Windows的内置功能。这是一个使用它的类:usingSystem;使用System.ComponentModel;使用System.Windows.Forms;使用System.Runtime.InteropServices;publicstaticclassUtil{publicenumEffect{Roll,Slide,Center,Blend}publicstaticvoidAnimate(Controlctl,Effecteffect,intmsec,intangle){intflags=effmap[(int)effect];如果(ctl.Visible){标志|=0x10000;角度+=180;}else{if(ctl.TopLevelControl==ctl)标志|=0x20000;elseif(effect==Effect.Blend)thrownewArgumentException();}flags|=dirmap[(angle%360)/45];boolok=AnimateWindow(ctl.Handle,msec,flags);if(!ok)thrownewException("动画失败");ctl.Visible=!ctl.Visible;}privatestaticint[]dirmap={1,5,4,6,2,10,8,9};私人静态int[]effmap={0,0x40000,0x10,0x80000};[DllImport("user32.dll")]privatestaticexternboolAnimateWindow(IntPtrhandle,intmsec,intflags);}产品使用方法:privatevoidbutton2_Click(objectsender,EventArgse){Util.Animate(button1,Util.Effect.Slide,150,180);如果您使用的是.NET4(如果您没有使用Thread来替换任务),那么这样的函数可能是一个开始:privatevoidslideToDestination(Controldestination,Controlcontrol,intdelay,ActiononFinish){newTask(()=>{intdirectionX=destination.Left>control.Left?1:-1;intdirectionY=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{//表单可以被处理break;}}如果(onFinish!=null)onFinish();}).Start();}用法:slideToDestination(senderasControl,panel1,10,()=>MessageBox.Show("Done!"));slideToDestination(发件人作为控件,panel1,0,null);作为一个动作,您将发送一些设置为true的布尔变量,以便您知道动画已完成或在它使用null动作后要运行的一些代码调用时谨防死锁。你可以在同一个控制器上以相同的速度在两个不同的方向运行两个动画,它会永远停留在同一个位置,当然两个动画同时播放可以让控件在某个方向无限走,因为while会neverfinish:)看看我去年写的库:WinFormAnimationLibrary[.Net3.5+]Asimplelibraryforsettingcontrolsin.NetWinForm(.Net3.5andabove)/valueanimation。基于关键帧(路径)且完全可定制。https://falahati.github.io/WinFormAnimation/newAnimator2D(newPath2D(newFloat2D(-100,-100),c_control.Location.ToFloat2D(),500)).Play(c_control,Animator2D.KnownProperties.Location);这将在500毫秒内将c_control控件从-100、-100移动到第一个位置。对于WinForms,您可以从面板位置关闭屏幕开始。使用计时器,并在Tick事件中,缓慢地将面板的位置移动到视图中,直到它位于预定义的坐标处。给猫剥皮的方法有很多种,但我就是这样做的。以上是C#学习教程:如何在C#中为我的控件添加移动效果?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
