I was here burning the midnight oil around some lines of code trying to solve a problem.
The code bellow will setup the control to be able to move anywhere within its p
Here is an example. I add a scripted small Panel
'piece' to a larger Panel
'board'.
I check for a minimum delta, so that a shaky hand won't start the movement..
One flag tracks the movement, another one the direction, with '0' being 'not yet' decided.
bool pieceMoving = false;
byte pieceDirection = 0;
Point startPosition = Point.Empty;
private void AddPieceButton_Click(object sender, EventArgs e)
{
Panel newPiece = new Panel();
newPiece.Size = new Size(16, 16);
newPiece.BackColor = Color.Blue;
pan_board.Controls.Add(newPiece);
newPiece.MouseDown += (sender2, evt) =>
{ pieceMoving = true; pieceDirection = 0; startPosition = evt.Location; };
newPiece.MouseUp += (sender2, evt) =>
{ pieceMoving = false; pieceDirection = 0;};
newPiece.MouseMove += (sender2, evt) =>
{
int delta = 0;
if (!pieceMoving) return;
if (pieceDirection == 0)
{
int deltaX = Math.Abs(startPosition.X - evt.X);
int deltaY = Math.Abs(startPosition.Y - evt.Y);
delta = deltaX + deltaY;
if (deltaX == deltaY) return;
if (delta < 6) return; // some minimum movement value
if (deltaX > deltaY) pieceDirection = 1; else pieceDirection = 2;
}
// else if (delta == 0) { pieceDirection = 0; return; } // if you like!
Panel piece = (Panel) sender2;
if (pieceDirection == 1) piece.Left += evt.X; else piece.Top += evt.Y;
};
Since I have put the code in a Button
click, I named the sender 'sender2' and I use it to allow for the same code being used for many pieces.