首页 > 解决方案 > C# 表单处理多个事物

问题描述

我在列表中有一些图片框。我希望他们更新他们的位置,并且仍然能够在更新其他对象的同时拖动对象。

我正在做和不定式 while 循环不断更新他们的位置:

while (true)
{
    Random rnd = new Random();

    pictures[0].Location = new Point(pictures[0].Location.X - rnd.Next(-2, 3), pictures[0].Location.Y + rnd.Next(0, 2));
    pictures[1].Location = new Point(pictures[1].Location.X, pictures[1].Location.Y + 1);
    this.Update();
}

问题是我使这些元素可拖动,但没有调用 MouseDown 事件。因为我猜是无限循环,但我该如何解决呢?

标签: c#winforms

解决方案


您应该使用计时器。将其设置为触发,但您想经常更新位置。这让主线程可以处理其他事件,同时根据需要经常更新您的动画。

如何创建计时器:

   myTimer = new System.Windows.Forms.Timer();
   myTimer.Tick += TimerEventProcessor;

   // Sets the timer interval to 0.5 seconds.
   myTimer.Interval = 500;
   myTimer.Start();

private void TimerEventProcessor(Object myObject,
                                        EventArgs myEventArgs) {
// Your update code here
}

推荐阅读