첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 다중 UI 스레드 만들기

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


TestProject.zip


MainForm.cs

 

 

using System;

using System.Collections.Generic;

using System.Runtime.InteropServices;

using System.Threading;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : Form

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Import

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region 부모 설정하기 - SetParent(childWindowHandle, parentWindowHandle)

 

        /// <summary>

        /// 부모 설정하기

        /// </summary>

        /// <param name="childWindowHandle">자식 윈도우 핸들</param>

        /// <param name="parentWindowHandle">부모 윈도우 핸들</param>

        /// <returns>처리 결과</returns>

        [DllImport("user32.dll", SetLastError = true)]

        private static extern IntPtr SetParent(IntPtr childWindowHandle, IntPtr parentWindowHandle);

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 열 카운트

        /// </summary>

        private const int COLUMN_COUNT = 5;

 

        /// <summary>

        /// 행 카운트

        /// </summary>

        private const int ROW_COUNT = 5;

 

        /// <summary>

        /// 폼 리스트

        /// </summary>

        private List<PopupForm> formList = new List<PopupForm>();

 

        /// <summary>

        /// 난수기

        /// </summary>

        private Random random = new Random();

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

 

            #region 다중 UI 스레드 사용하기 체크 박스를 설정한다.

 

            this.useMultiUIThreadCheckBox.Checked = true;

 

            #endregion

            #region 데이터 그리드 뷰를 설정한다.

 

            ControlHelper.SetDoubleBuffering(this.dataGridView, true);

 

            for(int i = 0; i < COLUMN_COUNT; i++)

            {

                this.dataGridView.Columns.Add(i.ToString(), i.ToString());

            }

 

            this.dataGridView.RowCount = ROW_COUNT;

 

            #endregion

            #region 이벤트를 설정한다.

 

            FormClosing             += Form_FormClosing;

            this.createButton.Click += createButton_Click;

            this.timer.Tick         += timer_Tick;

 

            #endregion

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region 폼을 닫을 경우 처리하기 - Form_FormClosing(sender, e)

 

        /// <summary>

        /// 폼을 닫을 경우 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Form_FormClosing(object sender, FormClosingEventArgs e)

        {

            foreach(PopupForm form in this.formList)

            {

                try

                {

                    form.CloseForm();

                }

                catch

                {

                }

            }

 

            this.formList.Clear();

        }

 

        #endregion

        #region 팝업 폼 생성하기 버튼 클릭시 처리하기 - createButton_Click(sender, e)

 

        /// <summary>

        /// 팝업 폼 생성하기 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void createButton_Click(object sender, EventArgs e)

        {

            for(int i = 0; i < 20; i++)

            {

                if(this.useMultiUIThreadCheckBox.Checked)

                {

                    AddPopupFormWithUIThread();

                }

                else

                {

                    AddPopupForm();

                }

            }

        }

 

        #endregion

        #region 타이머 틱 처리하기 - timer_Tick(sender, e)

 

        /// <summary>

        /// 타이머 틱 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void timer_Tick(object sender, EventArgs e)

        {

            for(int i = 0; i < COLUMN_COUNT; i++)

            {

                for(int j = 0; j < ROW_COUNT; j++)

                {

                    this.dataGridView.Rows[j].Cells[i].Value = this.random.Next(0, 100).ToString();

                }

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Function

 

        #region 팝업 폼 추가하기 - AddPopupForm()

 

        /// <summary>

        /// 팝업 폼 추가하기

        /// </summary>

        private void AddPopupForm()

        {

            PopupForm form = new PopupForm();

 

            this.formList.Add(form);

 

            form.Show(this);

 

            SetParent(form.Handle, Handle);

        }

 

        #endregion

        #region UI 스레드를 갖는 팝업 폼 추가하기 - AddPopupFormWithUIThread()

 

        /// <summary>

        /// UI 스레드를 갖는 팝업 폼 추가하기

        /// </summary>

        private void AddPopupFormWithUIThread()

        {

            PopupForm form = null;

 

            Thread thread = new Thread(() => {

                form = new PopupForm();

                this.formList.Add(form);

                Application.Run(form);

            });

 

            thread.SetApartmentState(ApartmentState.STA);

 

            thread.Start();

 

            while(true)

            {

                if(form != null && form.IsHandleCreated == true)

                {

                    break;

                }

            }

 

            IntPtr handle = Handle;

 

            form.Invoke(new Action(delegate { SetParent(form.Handle, handle); }));

        }

 

        #endregion

    }

}

 

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

Posted by 사용자 icodebroker

댓글을 달아 주세요