C#

[C#]Mouse Drag and Drop Control 생성 예제

선영아 사랑해 2016. 3. 25. 15:51

Mouse를 이용한 컨트롤 생성 시 마우스 위치에 따라 컨트롤 사이즈, 위치 관련 예제입니다.



Point position;
PictureBox pic;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        position = e.Location;
    }
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        int nX = e.X - position.X;
        int nY = e.Y - position.Y;

        pic = new PictureBox();

        pic.BackColor = Color.Red;

        if (nX < 0 && nY < 0) //마우스 커서를 아래에서 위로 좌측으로 이동하여 클릭했을 경우(↖)
        {
            pic.Size = new Size(position.X - e.X, position.Y - e.Y);

            pic.Location = new Point(e.X, e.Y);
        }
        else if (nX > 0 && nY < 0)    //마우스 커서를 아래에서 위로 우측으로 이동하여 클릭했을 경우(↗)
        {
            pic.Size = new Size(nX, position.Y - e.Y);

            pic.Location = new Point(position.X, e.Y);
        }
        else if (nX < 0 && nY > 0)  //마우스 커서를 위에서 아래로 좌측으로 이동하여 클릭했을 경우(↙)
        {
            pic.Size = new Size(position.X - e.X, nY);

            pic.Location = new Point(e.X, position.Y);
        }
        else if (nX > 0 && nY > 0)
        {
            //마우스 커서를 위에서 아래로 우측으로 이동하여 클릭했을 경우(↘)
            pic.Size = new Size(nX, nY);

            pic.Location = new Point(position.X, position.Y);
        }

        this.Controls.Add(pic);
    }
}

'C#' 카테고리의 다른 글

[C#]BadImageFormatException 관련  (0) 2016.03.29
[C#]ref 예제  (0) 2016.03.28
[C#]문자열을 char 배열 변환 예제  (0) 2016.03.25
[C#]SqlConnection 예제  (0) 2016.03.24
SATO Barcode Command(SBPL)  (0) 2016.03.24