PictureBox 从 c# 窗体中消失

本文关键字:消失 窗体 PictureBox | 更新日期: 2023-09-27 18:33:26

我需要在表单内移动一个图片框。图片框是Fantasma1。

当计时器(移动图片框(滴答作响时,这就是我所做的:

private void Move_Tick(object sender, EventArgs e)
    {
        Completamento.Increment(1); 
        while (Fantasma1.Location.X < MAX.X)
              Fantasma1.Location = new System.Drawing.Point(Fantasma1.Location.X + 1, Fantasma1.Location.Y);
        Move.Stop();
        MessageBox.Show("Location: " + Fantasma1.Location.X + ";" + Fantasma1.Location.Y + ", larghezza del form: " + this.Width + ", dimensione della picture: " + Fantasma1.Width);
    }

在我完成的表单的构造函数中:

MAX.X = this.Width - Fantasma1.Size.Width;

我认为这个解决方案是正确的,但我的图片框从表单中消失了。谁能帮我?

PictureBox 从 c# 窗体中消失

首先,你的幻想会跑到最后,你看不到它移动,因为这个:

while (Fantasma1.Location.X < MAX.X)
          Fantasma1.Location = new System.Drawing.Point(Fantasma1.Location.X + 1, Fantasma1.Location.Y);

该循环会立即将您的幽灵移动到最后,没有任何可见的变化,我认为您想要的是Move_Tick调用移动一个像素,如果达到极限,则停止计时器,而您只是在第一个滴答声时停止计时器,另一个错误。

因此,如果您希望幽灵在每个刻度上移动一个像素并且不离开屏幕,那么这应该可以解决问题:

private void Move_Tick(object sender, EventArgs e)
{
    int max = this.Width - Fantasma1.Width;
    if(Fantasma.Left < max)
        Fantasma1.Left++;
    else
        Move.Stop();
}

在您的情况下,测试最大位置的方法是正确的,但我几乎可以肯定您正在尝试在图片框加载图片之前获取大小(并且您设置自动大小以允许图片框根据其内容调整其大小(,因此为了避免错误,我在公式中添加了最大计算, 这是一个减法,它不消耗任何*过程。

*:几乎任何代码行都会消耗 CPU,但减法可以小于一纳秒,只是不明显。