C# - 컨트롤(이미지) 마우스 드래그로 위치 이동하기

반응형

 

드래그 이벤트 핸들러 추가하기

  • 솔루션 탐색기 - 폼 펼치기 - 폼.Designer.cs 우클릭 - 코드 보기

 

 

  • 드래그 이벤트를 추가할 객체에 이벤트 핸들러 코드 추가

pictureBox1.MouseDown += pictureBox1_MouseDown;
pictureBox1.MouseMove += pictureBox1_MouseMove;

드래그 이벤트 메소드 구현하기

MouseDown

  • 마우스 좌클릭 시 수행될 이벤트 핸들러
  • 클릭할 경우 클릭한 지점의 위치 정보를 저장하여 매끄러운 이동 처리 구현
    • 이미지의 시작 포인트를 기준으로 이동하기 때문에 마우스다운으로 시작 위치의 값을 받지 않으면 클릭시 이미지가 살짝 우측하단으로 내려감
// Handle the MouseDown event of the PictureBox
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        startPoint = e.Location;
    }
}

MouseMove

  • 마우스 이동 시 수행될 이벤트 핸들러
  • 마우스 좌클릭을 하고 이동하는 동안의 위치 정보를 실시간 반영
// Handle the MouseMove event of the PictureBox
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        pictureBox1.Left += e.X - startPoint.X;
        pictureBox1.Top += e.Y - startPoint.Y;
    }
}

전체 코드

Form1.Designer.cs

// Form1.Designer.cs
private void InitializeComponent()
{
    pictureBox1 = new PictureBox();
    ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
    SuspendLayout();
    // 
    // pictureBox1
    // 
    pictureBox1.BackColor = Color.Transparent;
    pictureBox1.Image = Properties.Resources.send_button_image;
    pictureBox1.Location = new Point(150, 100);
    pictureBox1.Name = "pictureBox1";
    pictureBox1.Size = new Size(50, 50);
    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
    pictureBox1.TabIndex = 0;
    pictureBox1.TabStop = false;
    pictureBox1.MouseDown += pictureBox1_MouseDown;
    pictureBox1.MouseMove += pictureBox1_MouseMove;
    // 
    // Form1
    // 
    AutoScaleDimensions = new SizeF(7F, 15F);
    AutoScaleMode = AutoScaleMode.Font;
    BackColor = SystemColors.ActiveCaption;
    ClientSize = new Size(400, 300);
    Controls.Add(pictureBox1);
    Name = "Form1";
    Text = "Form1";
    ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
    ResumeLayout(false);
}

private PictureBox pictureBox1;

Form1.cs

// Form1.cs
namespace ImageButtonTest
{
    public partial class Form1 : Form
    {
        private Point startPoint;

        public Form1()
        {
            InitializeComponent();
        }

        // Handle the MouseDown event of the PictureBox
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                startPoint = e.Location;
            }
        }

        // Handle the MouseMove event of the PictureBox
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                pictureBox1.Left += e.X - startPoint.X;
                pictureBox1.Top += e.Y - startPoint.Y;
            }
        }
    }
}

실행 화면

  • 처음 실행 화면

 

  • 마우스 좌클릭으로 이미지를 드래그하여 임의로 이동한 화면

 

반응형