c# - 使用 For 循环滑动对象 (C#)

标签 c# .net winforms animation

我做了很多搜索,但没有找到任何有帮助的东西。

是否可以使用 C# 来“滑动”或“移动”对象,使用简单的 For 循环将对象从一个位置移动到另一个位置?

谢谢

最佳答案

我建议你宁愿使用 Timer 。还有其他选项,但如果您想避免线程问题等,这将是最简单的。

使用直接 for 循环将要求您使用 Application.DoEvents() 泵送消息队列,以确保 Windows 有机会实际呈现更新的控件,否则 for 循环将运行完成如果不更新 UI,控件就会出现从源位置跳转到目标位置的情况。

这是一个 QAD 示例,用于在单击时在 Y 方向上为按钮设置动画。此代码假设您在名为 animationTimer 的窗体上放置了一个计时器控件。

private void button1_Click(object sender, EventArgs e)
{
  if (!animationTimer.Enabled)
  {
    animationTimer.Interval = 10;
    animationTimer.Start();
  }
}

private int _animateDirection = 1;
private void animationTimer_Tick(object sender, EventArgs e)
{
  button1.Location = new Point(button1.Location.X, button1.Location.Y + _animateDirection);

  if (button1.Location.Y == 0 || button1.Location.Y == 100)
  {
    animationTimer.Stop();
    _animateDirection *= -1; // reverse the direction
  }
}

关于c# - 使用 For 循环滑动对象 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3078898/

相关文章:

c# - ASP.NET Core Razor Pages 强制 Anchor Tag Helper (asp-page) 使用小写路由

.net - FileInfo.OpenText() 无法读取特殊字符üò°

c# - Windows Mobile - 如何检查是否有 WIFI 连接?

c# - 如何替换文本中的字符颜色?

c# - 在 C# 中将时间拆分为两个变量

c# - 并发读写 NamePipeClientStream

c# - 如何将10个类似的事件方法转换为一个方法来处理上述10个事件?

c# - C#简单错误/崩溃/卡住日志

c# - 使用 while(true) 定期执行任务

c# - 这段 C# 代码的作用是什么?