Move control either horizontally or vertically, not combination of both

前端 未结 2 1066
一整个雨季
一整个雨季 2021-01-28 11:12

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

2条回答
  •  清酒与你
    2021-01-28 11:44

    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.

提交回复
热议问题