[C# 윈폼] C# 윈폼(Windows form) 컨트롤 복사 붙여넣기 하기(Clone)

안녕하세요.

 

오늘은 C# 윈폼에서 컨트롤 복사 붙여넣기 하는 방법에 대해서 알려 드리려고 합니다.

 

Clone 메서드는 제가 직접 구현한 것이 아니라, StackOverFlow 사이트에 있는 소스 코드를 가지고 사용한 점 참고해 주세요ㅎㅎ

 

그럼 바로 예제 프로그램을 만들어서 어떻게 컨트롤을 복사 + 붙여넣기 하는지 보여 드리도록 하겠습니다.

 

제가 만들 예제 프로그램은 부모폼, 자식폼 총 2개의 폼을 생성한 후, 자식폼에 있는 Button 컨트롤을 그대로 복사해 와서 자식폼의 Button 컨트롤을 그대로 부모폼의 Button 컨트롤에 복사 붙여넣기 하려고 합니다.

 

 

그럼 바로 예제 프로그램을 만들어 보겠습니다.

 

먼저 윈폼 프로젝트 하나를 생성해 주시고 Main폼과 Child폼 총 2개의 폼을 생성해 주시기 바랍니다.

 

부모 폼 UI

부모폼 UI는 위와 같이 구성 하였습니다.

 

먼저 잘 안보이시겠지만, FlowLayoutPanel 컨트롤 하나를 Dock 속성 Fill로 해서 전체 폼을 채워 주었고, Test1 이라는 Button 컨트롤 하나를 배치하였습니다.

 

위와 같이 여러분들도 UI 구성을 해주시기 바랍니다.

 

자식 폼 UI

자식폼 UI는 위와 같이 구성하였습니다.

 

다른 컨트롤 하나 없이 오로지 ChildButton 이라는 Button 컨트롤 하나를 배치하였습니다.

 

이제 제가 소스코드에서 할 작업은 자식폼의 ChildButton 컨트롤을 복사하여 이 Button을 부모폼에 그대로 붙여넣기 해보도록 하겠습니다.

 

소스코드는 아래를 참고해 주시면 됩니다.

 

Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ControlCloneTest
{
    static class Program
    {
        /// <summary>
        /// 해당 애플리케이션의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Main());
        }
    }
 
    /// <summary>
    /// Control Clone 내용 Class
    /// </summary>
    public static class ControlExtensions
    {
        public static T Clone<T>(this T controlToClone)
            where T : Control
        {
            PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
            T instance = Activator.CreateInstance<T>();
 
            foreach (PropertyInfo propInfo in controlProperties)
            {
                if (propInfo.CanWrite)
                {
                    if (propInfo.Name != "WindowTarget")
                        propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
                }
            }
 
            return instance;
        }
    }
}
 
cs

 

 

Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ControlCloneTest
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
 
            this.Load += Load_Event;
        }
 
        /// <summary>
        /// Load 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Load_Event(object sender, EventArgs e)
        {
            ButtonClone();
        }
 
        /// <summary>
        /// Button 컨트롤 10개 복사 메서드
        /// </summary>
        public void ButtonClone()
        {
            for (int i = 0; i < 10; i++)
            {
                Child chd = new Child();
                chd.btn.Visible = true;
 
                uiFlp_Main.Controls.Add(chd.btn);
            }
        }
    }
}
 
cs

 

 

Child.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ControlCloneTest
{
    public partial class Child : Form
    {
        public Button btn = null;
 
        public Child()
        {
            InitializeComponent();
 
            btn = uiBtn_Child.Clone();
        }
    }
}
 
cs

 

실행 결과

위와 같이 부모폼에서 총 10개의 ChildButton 컨트롤들이 제대로 복사 붙여넣기가 된 것을 확인하실 수 있습니다.

 

여기서 핵심은 Program.cs 에 있는 Clone 클래스의 내용이 핵심이기 때문에 이 부분의 Class와 메서드를 한번 분석해 보시는 것을 추천 드리겠습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY