C#

[C#]pictureBox 동적 생성 예제

선영아 사랑해 2016. 1. 15. 15:34

C#에서 PictureBox Control을 동적 생성 샘플 소스입니다.

기존 PictureBox 선택 후 Ctrl+C 누른 후 화면의 다른 곳에 마우스 좌클릭하면 다른 PictureBox 자동 생성되는걸 확인 할 수있습니다.


#region 전역변수
Point mouseClickPos;

int clickCnt = 0;

Bitmap bmp;
#endregion


private void pictuerBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.C && ((PictureBox)sender).Focus())  //pictureBox 선택 후 키보드에서 Ctrl+C하면 해당 pictureBox의 Image 파일 복사
    {
        bmp = (Bitmap)((PictureBox)sender).Image;
    }
}


private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
    ((PictureBox)sender).Focus();

    ((PictureBox)sender).BringToFront();
}


//Form에서 MouseDown Event 추가

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        mouseClickPos = e.Location;//마우스 좌클릭 위치 정보 저장
    }
}


//Form에서 MouseUp Event 추가

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left && bmp != null)
    {

       //마우스 좌클릭과 bmp 파일 정상 복사됐을 경우 pictureBox 생성. 생성 위치는 마우스 좌클릭 좌표
        PictureBox[] pictureBox = new PictureBox[1];

        pictureBox[0] = new PictureBox();

        pictureBox[0].Image = bmp;

        pictureBox[0].Name = string.Format("pictureBox{0}", clickCnt++);

        pictureBox[0].BorderStyle = BorderStyle.FixedSingle;

        pictureBox[0].BackColor = System.Drawing.Color.White;

        pictureBox[0].Location = new Point(mouseClickPos.X, mouseClickPos.Y);

        pictureBox[0].Size = new Size(bmp.Width, bmp.Height);

        pictureBox[0].PreviewKeyDown += new PreviewKeyDownEventHandler(pictuerBox_PreviewKeyDown);//pictureBox 생성 후 Event Add

        pictureBox[0].MouseDown += new MouseEventHandler(pictureBox_MouseDown);//pictureBox 생성 후 Event Add

        this.Controls.Add(pictureBox[0]);

        bmp = null;
    }
}