1

我正在尝试使用问题中给出的代码平滑移动表单如何以不同的速度平滑地为 Windows 窗体位置设置动画?

但由于某种原因,我的 this.Invalidate() 调用永远不会触发 OnPaint 事件。表格上是否需要一些配置才能实现这一点?

编辑:

涉及线程,因为它在具有自己的消息循环的后台工作程序中运行。这是代码:

public class PopupWorker
{
    public event PopupRelocateEventHandler RelocateEvent;

    private BackgroundWorker worker;
    private MyPopup popupForm;

    public PopupWorker()
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        popupForm = PopupCreator.CreatePopup("Title", "BodyText");
        this.RelocateEvent += popupForm.OnRelocate;
        popupForm.CustomShow();
        Application.Run();
    }

    public void Show()
    {
        worker.RunWorkerAsync();
    }

    public void PopupRelocate(object sender, Point newLocation)
    {
        if (popupForm.InvokeRequired)
            popupForm.Invoke(new PopupRelocateEventHandler(PopupRelocate), new object[] {sender, newLocation});
        else
            RelocateEvent(this, newLocation);
    }
}

形式 :

public void OnRelocate(object sender, Point newLocation)
{
    targetLocation = newLocation;
    this.Invalidate();
}

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    if (Location.Y != targetLocation.Y)
    {
        Location = new Point(Location.X, Location.Y + 10);
        if (Location.Y > targetLocation.Y)
            Location = targetLocation;
        this.Invalidate();
    }
}
4

1 回答 1

3

链接问题中的代码使用 Application.DoEvents,这是让 OnPaint 发生的关键部分。
没有它,您可以使用 Form.Refresh() 而不是 Invalidate。

有关更多详细信息,请参阅此问题

编辑:

您的代码确实显示了一些问题,但它并不完整。让我们从基础开始,为了使表单移动,您只需要启用一个 Timer 即可:

private void timer1_Tick(object sender, EventArgs e)
{            
    this.Location = new Point(this.Location.X + 2, this.Location.Y + 1);
}
于 2009-12-18T17:55:55.640 回答