Question

I am looking to move a button around a form in this motion

|<----------
|           ^
|           |
|           |
|           |
|           |
V---------->|

one step at a time (every time it's clicked)

Here is my code so far (doesn't move correctly):

if (btnClicker.Location.X > this.ClientSize.Width - btnClicker.Width)
      btnClicker.Location = new Point(btnClicker.Location.X, btnClicker.Location.Y + 1);
else if (btnClicker.Location.X < btnClicker.Width)
      btnClicker.Location = new Point(btnClicker.Location.X+1, btnClicker.Location.Y);
else if (btnClicker.Location.Y > this.ClientSize.Height - btnClicker.Height)
      btnClicker.Location = new Point(btnClicker.Location.X, btnClicker.Location.Y - 1);
else if (btnClicker.Location.Y < this.ClientSize.Height - btnClicker.Height)
      btnClicker.Location = new Point(btnClicker.Location.X - 1, btnClicker.Location.Y);
Was it helpful?

Solution

I have written this code for you. Check it out. I have tested it partially from my side and it looks good but test it thoroughly at your end. Tweak it as per your requirement.

bool _isFirst = true;
bool _reachedBottomRight = false;
bool _reachedTopRight = false;
int _increDecreValue = 1;
int StartXPos = 5;
int StartYPos = 5;

private void btnClicker_Click(object sender, EventArgs e)
{

    if (_isFirst)
    {
        //Set the start location of the button. This can be any position you want
        btnClicker.Location = new Point(StartXPos, StartYPos);
        _isFirst = false;
    }

    if (btnClicker.Location.Y < this.ClientSize.Height - btnClicker.Height && !_reachedBottomRight)
        btnClicker.Location = new Point(btnClicker.Location.X, btnClicker.Location.Y + _increDecreValue);
    else if (btnClicker.Location.X < this.ClientSize.Width - btnClicker.Width && !_reachedTopRight)
        btnClicker.Location = new Point(btnClicker.Location.X + _increDecreValue, btnClicker.Location.Y);
    else if (btnClicker.Location.Y > StartYPos)
    {
        btnClicker.Location = new Point(btnClicker.Location.X, btnClicker.Location.Y - _increDecreValue);
        _reachedBottomRight = true;
    }
    else if (btnClicker.Location.X > StartXPos)
    {
        btnClicker.Location = new Point(btnClicker.Location.X - _increDecreValue, btnClicker.Location.Y);
        _reachedTopRight = true;
    }

    if (btnClicker.Location.X <= StartXPos && btnClicker.Location.Y <= StartYPos)
    {
        _reachedBottomRight = false;
        _reachedTopRight = false;
    }
}

If this is not what you are looking for then please comment.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top