본문 바로가기
Programming/WindowsForm

프로그래머가 만든 Thread에서 WindowsForm Control 접근시 문제

by subutie 2021. 2. 17.
728x90

프로그래머가 생성한 Thread에서 WindowsForm의 control을 직접 접근 할시 오류가 발생 합니다.

이 해결 법은 아래와 같이 (TextBox를 예로 든 코드 입니다.) 하시면 됩니다.

           if (box.InvokeRequired)
            {
                box.Invoke(new MethodInvoker(() => { 
                    box.Text = message;
                    box.Update(); 
                }));
            }
            else
            {
                box.Text = message;
                box.Update();
            }

 

여기서 코딩 하시다 보면 매번 코드를 반복하는 부분이 생기는데

이 경우 Extension Methods를 이용하면 편하게 사용 하실 수 있습니다.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

 

Extension Methods - C# Programming Guide

Extension methods in C# enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

docs.microsoft.com

 

정말 간단하게 설명 하면 아래와 같이 public static class에 public static 함수를 만들고 첫 인자를 this로 넣고 이 함수가 사용될 Control이나 object를 넣어 주시면 됩니다.

그럼면 예제 맨 아래줄과 같이 해당 Control에 Method처럼 확장 해서 사용 하실 수 있습니다.

public static class StaticClass
 {
        #region Control
        public static void SetTextBoxMsg(this TextBox box, string message)
        {
            if (box == null || string.IsNullOrEmpty(message)) return;

            if (box.InvokeRequired)
            {
                box.Invoke(new MethodInvoker(() => { box.Text = message; box.Update(); })); ;
            }
            else
            {
                box.Text = message;
                box.Update();
            }
        }
  }

댓글