user5892486
user5892486

Reputation:

PictureBox goes out from the form c#

I need to move a picturebox inside the form. The picturebox is Fantasma1.

This is what I do when a timer (which moves the picturebox) ticks:

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);
    }

In the constructor of the form I have done:

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

I think this solution is correct, but my picturebox goes out from the form. Can anyone help me?

Upvotes: 0

Views: 697

Answers (1)

Gusman
Gusman

Reputation: 15151

First of all, your Fantasma will run to the end without you seeing it move because of this:

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

That loop will move immediately your ghost to the end without any visible change, I think what you want is to move one pixel by Move_Tick call and if it gets to the limit then stop the timer, and you just stoped the timer at the first tick, another error.

So, if you want a ghost moving a pixel on each tick and don't get out of the screen then this should do the trick:

private void Move_Tick(object sender, EventArgs e)
{
    int max = this.Width - Fantasma1.Width;

    if(Fantasma.Left < max)
        Fantasma1.Left++;
    else
        Move.Stop();
}

In your case the way of testing the max position was right, but I'm nearly sure you are trying to get the size before the picturebox loads the picture (and you set autosize in order to allow the picturebox to adjust it's size to it's content) so to avoid errors I added the max calculation on the formula, it's a subtraction, it does not consume any* process.

*: nearly any, any line of code costs cpu but a subtract can be less than a nanosecond, just not noticeable.

Upvotes: 1

Related Questions