Code Programming/C#2018. 6. 26. 17:02

FormParent (부모폼)에서 FormChild (자식폼)을 호출할 때,

FormChild (자식폼)에서 FormParent (부모폼)을 호출할 때,

 

MDI폼을 활용하여 프로퍼티를 활용한다면 간단하게 끝날 사항인거 같다.

하지만 Delegate와 Event를 직접 만들어서 사용하는 예제를 만들기 위해 서로 연관성이 없는 폼으로 연결을 해보았다.

 

 

* 아래는 이벤트를 만들때 사용하기 위한 EventArgs 객체와 Delegate 를 미리 선언한 클래스 파일이다.

------------------------------------------------------------------------------------------------------------------------------------

*** CustomEventClass.cs


    /// <summary>
    /// 이벤트 파라미터 정의 클래스
    /// </summary>
    internal static class EventArgClass
    {
        /// <summary>
        /// 부모폼 호출시 이벤트 파라미터
        /// </summary>
        internal class CallParentEventArgs : EventArgs
        {
            /// <summary>
            /// 자식폼의 메시지
            /// </summary>
            internal string ChildFormMessage { get; set; }
        }

        /// <summary>
        /// 자식폼 호출시 이벤트 파라미터
        /// </summary>
        internal class CallChildEventArgs : EventArgs
        {
            /// <summary>
            /// 부모폼의 메시지
            /// </summary>
            internal string ParentFormMessage { get; set; }
        }
    }

    /// <summary>
    /// 대리자 정의 클래스
    /// </summary>
    internal static class DelegateClass
    {
        /// <summary>
        /// 부모폼 호출 대리자
        /// </summary>
        /// <param name="childForm">자식폼</param>
        /// <param name="args">자식폼 이벤트 파라미터</param>
        internal delegate void CallParent(System.Windows.Forms.Form childForm, EventArgClass.CallParentEventArgs args);

        /// <summary>
        /// 자식폼 호출 대리자
        /// </summary>
        /// <param name="parentForm">부모폼</param>
        /// <param name="args">부모폼 이번테 파라미터</param>
        internal delegate void CallChild(System.Windows.Forms.Form parentForm, EventArgClass.CallChildEventArgs args);
    }

------------------------------------------------------------------------------------------------------------------------------------

 

사실 아직도 대리자에 대한 정확한 개념이 머리속에 잡히지 않았지만 난 주로 Event 를 만들때 사용할 것 같다.

 

EventArgs 클래스 같은 경우에는 커스텀으로 만들 경우에 반드시 EventArgs 형식으로 만들 필요는 없다.

원하는 구조체나 클래스를 만들어 사용하여도 무관하다.

 

대리자의 파라미터 구성요소로는 보통 이벤트에 포함되는 파라미터가 Sendor, EventArgs 인 형태가 대부분이여서 비슷하게 만들어 보았다.

파라미터의 요소는 생략 또는 2개 이상의 형식을 넣어도 무관하다.

 

또한 리턴값을 void 이외의 값으로 지정하면 이벤트이지만 값을 리턴받아 후위처리가 가능한 이벤트로 생성할 수 있는 것 같다.

 

 

 

* 아래는 폼 코딩이다.

------------------------------------------------------------------------------------------------------------------------------------

*** FormChild.cs

 

   public partial class FormChild : Form
    {
        /// <summary>
        /// 부모폼 호출 이벤트
        /// </summary>
        internal event DelegateClass.CallParent CallParentEvent;

        private string m_strFormName = String.Empty;


        public FormChild(FormParent frm)
        {
            InitializeComponent();

            this.m_strFormName = Guid.NewGuid().ToString().ToUpper().Replace("-", "");

            this.btnCallParent.Click += (s, e) => { CallParent(); };
            this.FormClosed += (s, e) => { frm.CallChildEvent -= ResponseParent; };
            frm.CallChildEvent += ResponseParent;
        }


        private void CallParent()
        {
            if (this.CallParentEvent != null)
            {
                CallParentEvent(this, new EventArgClass.CallParentEventArgs() { ChildFormMessage = String.Format("Hi. I'm {0}.", this.m_strFormName) });
            }
        }

        private void ResponseParent(Form parentForm, EventArgClass.CallChildEventArgs args)
        {
            if (this.CallParentEvent != null)
            {
                CallParentEvent(this, new EventArgClass.CallParentEventArgs() { ChildFormMessage = String.Format("Why? {0}.", this.m_strFormName) });
            }
        }
    }

------------------------------------------------------------------------------------------------------------------------------------

*** FormParent.cs


    public partial class FormParent : Form
    {
        /// <summary>
        /// 자식폼 호출 이벤트
        /// </summary>
        internal event DelegateClass.CallChild CallChildEvent;
      

        public FormParent()
        {
            InitializeComponent();
           
            this.btnNewChild.Click += (s, e) => { CreateChildForm(); };
            this.btnCallChild.Click += (s, e) => { CallChildForm(); };
        }

       
        private void CreateChildForm()
        {
            FormChild form = new FormChild(this);
            form.CallParentEvent += (s, e) => { CallParent(e); };

            form.Show();
        }

        private void CallChildForm()
        {
            if (this.CallChildEvent != null)
            {
                CallChildEvent(this, new EventArgClass.CallChildEventArgs() { ParentFormMessage = "HEY" });
            }
        }


        private void CallParent(EventArgClass.CallParentEventArgs e)
        {
            this.txtEventMessage.AppendText(e.ChildFormMessage);
            this.txtEventMessage.AppendText(Environment.NewLine);
        }

    }

------------------------------------------------------------------------------------------------------------------------------------

 

간단하게 부모폼에서 자식폼을 Show해주고 자식폼에서 버튼 클릭시 부모폼의 TextBox에 어떤 자식폼에서 부모폼을 호출하였는지 출력하고,

부모폼에서 자식폼 모두를 호출하였을 때, 활성화되어 있는 자식폼이 모두 부모폼의 TextBox에 출력하도록 구성했다.

 

별다른 내용은 없으므로.... 더이상의 설명은 생략 '-'

 

 

 

 

'Code Programming > C#' 카테고리의 다른 글

C# - HttpWebRequest 네이버 로그인(보안)  (2) 2018.06.28
Posted by 개돼지오크