Bondca
Bondca

Reputation: 39

I can't seem to move the location of a Picture box in c#

I'm trying to make it so that when I press the up arrow, it moves the picture box up, the down arrow moves down, ect. But I can't seem to get it to work. It is giving me the error:

Can't modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable

This is my code:

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {

        if(e.KeyCode == Keys.Up)
        {
            ImgGuy.Location.Y--;
        }
        else if (e.KeyCode == Keys.Down)
        {
            ImgGuy.Location.Y++;
        }
        else if (e.KeyCode == Keys.Left)
        {
            ImgGuy.Location.X--;
        }
        else if (e.KeyCode == Keys.Right)
        {
            ImgGuy.Location.X++;
        }

Any help is greatly appreciated.

Upvotes: 0

Views: 1669

Answers (3)

Thomas Andreè Wang
Thomas Andreè Wang

Reputation: 3429

You need to produce a new point

In this case X is increased aka move left

Pic.Location = new Point(Pic.Location.X + 1, Pic.Location.Y);

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109547

Try this:

ImgGuy.Location = new Point(ImgGuy.Location.X+1, ImgGuy.Location.Y+1) // etc

The problem is that Location returns a copy of the location.

Alternatively, set Control.Left and Control.Top instead.

Upvotes: 0

gzaxx
gzaxx

Reputation: 17590

You have to recreate new Location:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{
        Point l;

        if(e.KeyCode == Keys.Up)
        {
            l = new Point(ImgGuy.Location.X, ImgGuy.Location.Y - 1);
        }
        else if (e.KeyCode == Keys.Down)
        {
            l = new Point(ImgGuy.Location.X, ImgGuy.Location.Y + 1);
        }
        else if (e.KeyCode == Keys.Left)
        {
            l = new Point(ImgGuy.Location.X - 1, ImgGuy.Location.Y);
        }
        else if (e.KeyCode == Keys.Right)
        {
            l = new Point(ImgGuy.Location.X + 1, ImgGuy.Location.Y);
        }

        ImgGuy.Location = l;
}

Upvotes: 1

Related Questions