Microsoft MVP성태의 닷넷 이야기
Windows: 235. Win32 - Code Modal과 UI Modal [링크 복사], [링크+제목 복사]
조회: 4525
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 21개 있습니다.)
Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법
; https://www.sysnet.pe.kr/2/0/13284

Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법
; https://www.sysnet.pe.kr/2/0/13285

Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
; https://www.sysnet.pe.kr/2/0/13286

Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법
; https://www.sysnet.pe.kr/2/0/13287

Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법
; https://www.sysnet.pe.kr/2/0/13288

Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법
; https://www.sysnet.pe.kr/2/0/13289

Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage
; https://www.sysnet.pe.kr/2/0/13292

Windows: 233.  Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법
; https://www.sysnet.pe.kr/2/0/13295

Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지
; https://www.sysnet.pe.kr/2/0/13296

Windows: 235. Win32 - Code Modal과 UI Modal
; https://www.sysnet.pe.kr/2/0/13297

Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
; https://www.sysnet.pe.kr/2/0/13299

Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
; https://www.sysnet.pe.kr/2/0/13300

Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)
; https://www.sysnet.pe.kr/2/0/13305

Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
; https://www.sysnet.pe.kr/2/0/13306

Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)
; https://www.sysnet.pe.kr/2/0/13312

Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의
; https://www.sysnet.pe.kr/2/0/13315

Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성
; https://www.sysnet.pe.kr/2/0/13329

Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
; https://www.sysnet.pe.kr/2/0/13330

Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의
; https://www.sysnet.pe.kr/2/0/13332

Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용
; https://www.sysnet.pe.kr/2/0/13333

Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
; https://www.sysnet.pe.kr/2/0/13334




Win32 - Code Modal과 UI Modal

지난 글에,

Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법
; https://www.sysnet.pe.kr/2/0/13295

인용한 Modality, part 1: UI-modality vs code-modality 글은 modality라는 동작에 대해 UI-modal과 code-modal로 나누고 있습니다.

우선 code-modal은 우리가 그동안 DialogBox API를 이용해 호출한 modal 대화창의 동작 방식일 텐데요, 좀 더 엄밀히 말하면 메시지 루프를 (중첩시켜) 만들어 블록킹을 시키면 그것을 code-modal이라고 지칭하고 있습니다.

반면 UI-modal은 "Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법" 글에서 든 예제와 같이 어떤 식으로든 UI가 modal로 동작하는 것을 의미합니다.

그러니까, 지난 예제는 (중첩 메시지 루프의) code-modal을 사용하지 않은 UI-modal을 만든 것인데요, Modality 2번째 글에서는,

Modality, part 2: Code-modality vs UI-modality
; https://devblogs.microsoft.com/oldnewthing/20050221-00/?p=36403

그 반대의 경우로, UI-modal 없이 (중첩 메시지 루프의) code-modal을 사용하는 것도 가능하다고 합니다. 실제로 후자의 경우가 더 흔한 사례라고 하는데요, 가령 스크롤바의 thumb 버튼을 드래그하는 중에, 윈도우의 캡션 바를 잡고 드래그하는 중에, 팝업 메뉴를 표시하는 중에, OLE drag/drop 작업을 개시할 때와 같은 상황에서 (중첩 메시지 루프의) code-modal을 활용합니다.

실제로 MsgWaitForMultipleObjects를 이용한 code-modal을 구현하는 예제를 링크하고 있는데,

One example is given in MSDN, 
; (broken) http://msdn.microsoft.com/library/en-us/dllproc/base/waiting_in_a_message_loop.asp

현재는 없는 자료입니다. ^^ 단지 인터넷에서 "waiting in a message loop"로 소스코드를 구할 수 있는데요,

int MessageLoop ( 
    HANDLE* lphObjects,  // handles that need to be waited on 
    int     cObjects     // number of handles to wait on 
  )
{ 
    // The message loop lasts until we get a WM_QUIT message,
    // upon which we shall return from the function.
    while (TRUE)
    {
        // block-local variable 
        DWORD result ; 
        MSG msg ; 

        // Read all of the messages in this next loop, 
        // removing each message as we read it.
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
        { 
            // If it is a quit message, exit.
            if (msg.message == WM_QUIT)  
                return 1; 
            // Otherwise, dispatch the message.
            DispatchMessage(&msg); 
        } // End of PeekMessage while loop.

        // Wait for any message sent or posted to this queue 
        // or for one of the passed handles be set to signaled.
        result = MsgWaitForMultipleObjects(cObjects, lphObjects, 
                 FALSE, INFINITE, QS_ALLINPUT); 

        // The result tells us the type of event we have.
        if (result == (WAIT_OBJECT_0 + cObjects))
        {
            // New messages have arrived. 
            // Continue to the top of the always while loop to 
            // dispatch them and resume waiting.
            continue;
        } 
        else 
        { 
            // One of the handles became signaled. 
            DoStuff (result - WAIT_OBJECT_0) ; 
        } // End of else clause.
    } // End of the always while loop. 
} // End of function.

위의 코드를 보면 PeekMessage를 이용해 메시지 큐에 있는 모든 메시지를 소진한 다음 MsgWaitForMultipleObjects를 호출하는 구조로, 이에 대한 이유를 다음의 글에서 자세하게 설명하고 있습니다.

MsgWaitForMultipleObjects and the queue state
; https://devblogs.microsoft.com/oldnewthing/20050217-00/?p=36423

윈도우 메시지가 큐에 있는 경우, MsgWaitForMultipleObjects를 호출하면 신규로 들어오는 메시지에 대해서만 함수가 반환을 한다고 합니다. 따라서 메시지 큐에 처리되지 않은 메시지가 있어도 MsgWaitForMultipleObjects 호출 시 곧바로 반환하지는 않습니다.

MsgWaitForMultipleObjects로 기존 메시지를 처리하는 것도 가능한데, 다음과 같은 코딩이라면 메시지 처리에 문제가 되지는 않습니다.

bool hasMsg = NativeMethods.PeekMessage(out MSG msg2, IntPtr.Zero, 0, 0, PM_NOREMOVE);
if (hasMsg == false)
{
    // ...[이 사이에 메시지가 post된 경우]...
    // ... 아래의 MsgWaitForMultipleObjects는 곧바로 반환
    NativeMethods.MsgWaitForMultipleObjects(cObjects, null, true, -1, QS_ALLPOSTMESSAGE);
}

주의해야 할 점은, 위의 PeekMessage가 true를 반환했다면 그것을 별도로 처리해야 합니다. 왜냐하면 PeekMessage로 확인했다는 것은 그 시점까지 메시지 큐의 내용을 체크했다는 플래그가 설정돼 이후의 MsgWaitForMultipleObjects는 마찬가지로 신규 메시지만을 처리하기 때문입니다. 좀 뭔가 애매하죠?

이후 MsgWaitForMultipleObjectsEx는 MWMO_INPUTAVAILABLE 플래그를 둬서 이런 문제를 해결합니다. 그래서 예전에 만들어 둔 메시지 루프를,

C# - Console 응용 프로그램에서 UI 스레드 구현 방법
; https://www.sysnet.pe.kr/2/0/12139

다음과 같이 변경하는 것도 가능합니다.

while (true)
{
    try
    {
        uint cObjects = (uint)_pHandles.Length;
        uint result = NativeMethods.MsgWaitForMultipleObjectsEx(cObjects, _pHandles, 0xFFFFFFFF, QS_ALLPOSTMESSAGE, MWMO_INPUTAVAILABLE);

        if (result == cObjects)
        {
            NativeMethods.GetMessage(out MSG msg, IntPtr.Zero, 0, 0);
            WindowProc(msg);
            MessageArrived?.Invoke(this, new MessageEventArgs(msg));

            switch (msg.message)
            {
                case (uint)Win32Message.WM_QUIT:
                case (uint)Win32Message.WM_CLOSE:
                    OnClose();
                    return;
            }

            NativeMethods.DispatchMessage(ref msg);
        }
        else
        {
            OnClose();
            return;
        }
    }
    finally
    {
        _ewh_Sync.Set();
    }
}

_pHandles에 대기해야 할 커널 개체가 없다면, 그냥 바로 GetMessage를 호출하도록 바꾸면 됩니다.

참고로, 위의 코드에서 제가 PeekMessage(out MSG msg, IntPtr.Zero, 0, 0, PM_REMOVE); 대신 GetMessage를 사용했는데요, 이게 약간 묘하게 다른 점이 있습니다. 위의 메시지 루프를 동일하게 사용한다고 했을 때, 다음과 같이 사용 코드를 만들면,

using CustomMessageLoop;

class Program
{
    // Install-Package CustomMessageLoop
    static void Main(string[] args)
    {
        using (MessageLoop mml = new MessageLoop())
        {
            ThreadPool.QueueUserWorkItem((arg) =>
            {
                Thread.Sleep(1000);
                mml.PostMessage(Win32Message.WM_TIMER);
                mml.PostMessage(Win32Message.WM_TIMER);

                mml.PostMessage(Win32Message.WM_TIMER);
                mml.PostMessage(Win32Message.WM_TIMER);

                mml.PostMessage(Win32Message.WM_TIMER);
                Thread.Sleep(500);
                mml.PostMessage(Win32Message.WM_CLOSE);
            });

            mml.MessageArrived += Mml_MessageArrived;

            mml.Run();
            mml.WaitForExit();
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    private static void Mml_MessageArrived(object? sender, MessageEventArgs e)
    {
        Console.WriteLine(e.Message.message);
    }
}

분명히 5번의 WM_TIMER를 보냈지만 어쩌다 한 번씩 6번의 Console.WriteLine 출력이 나오게 됩니다. 반면 GetMessage로 처리한 경우에는 그런 현상이 없고.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/26/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13381정성태6/25/20233867오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233300스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233308스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233205오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237077오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233427.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233107스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233213오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234530오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233209개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233243개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233412개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233236개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233368개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233502오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233281.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233020오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233813.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233376스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233320.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233744오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233133오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233464오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233792.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233573.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233896DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...