Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (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 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)

지난 글에 소개한,

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

코드의 문제점을 개선해 볼까요? ^^ 전역 변수를 사용하는 것이 문제였는데요, 따라서 이후에 소개했던 또 다른 글을 이용해,

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

전역 변수를 윈도우 저장소에 보관함으로써 해결할 수 있습니다. 여기서 잠깐 지난번에 만든 (시간 만료를 갖는) 메시지 박스의 호출 코드를 볼까요?

TimedMessageBox(hWnd, L"TEXT", L"TITLE", MB_OK, 3000); 

혹시 저렇게 전달된 hWnd에 대해 GWLP_USERDATA를 사용하면 어떨까요? 아쉽게도 여기에는 2개의 문제가 있습니다. 우선, (Owner를 지정하는 것은 중요하지만) 사용자가 항상 hWnd를 전달할 거라는 보장을 할 수 없습니다. (물론, hWnd가 nullptr이면 오류를 반환하도록 결정하면 됩니다.) 결정적으로 2번째 이유가 있는데요, (라이브러리 성격의 TimedMessageBox API 입장에서) 사용자가 전달한 hWnd의 GWLP_USERDATA가 이미 다른 용도로 사용 중이라면 충돌을 야기할 수밖에 없습니다.

바로 그런 문제를 해결하기 위해, part 8에서는,

Modality, part 8: A timed MessageBox, the better version
; https://devblogs.microsoft.com/oldnewthing/20050304-00/?p=36273

Owner 윈도우와 대화창 사이에 우리의 시간 만료 기능을 위해 필요한 데이터를 저장할 dummy 윈도우를 하나 끼워 넣고 있습니다. 아래는 그 윈도우를 위한 코드로,

ATOM RegisterDummyWindowClass(HINSTANCE hInstance)
{
    WNDCLASS wc = {
          0,                              // style
          DefWindowProc,                  // lpfnWndProc
          0,                              // cbClsExtra
          0,                              // cbWndExtra
          hInstance,                        // this file's HINSTANCE
          NULL,                           // hIcon
          LoadCursor(NULL, IDC_ARROW),    // hCursor
          (HBRUSH)(COLOR_BTNFACE + 1),      // hbrBackground
          NULL,                           // lpszMenuName
          TEXT("Dummy"),                // lpszClassName
    };
    return RegisterClass(&wc);
}

HWND CreateDummyWindow(HWND hwndParent)
{
    HWND hwnd;
    hwnd = CreateWindow(TEXT("Dummy"), NULL, hwndParent ? WS_CHILD : WS_OVERLAPPED,
        0, 0, 0, 0, hwndParent, NULL, NULL, NULL);

    return hwnd;
}

기존에 전역 변수로 두었던 2개의 변수를,

static BOOL s_fTimedOut;
static HWND s_hwndMBOwnerEnable;

Dummy 윈도우로 생성한 저장소 공간에 GWLP_USERDATA로 보관해 두는 방식으로 소스코드를 수정하면 됩니다.

#define IDT_TOOLATE     1
typedef struct TOOLATEINFO {
    BOOL fTimedOut;
    HWND hwndReenable;
} TOOLATEINFO;

void CALLBACK MsgBoxTooLateProc(HWND hwnd, UINT uiMsg, UINT_PTR idEvent, DWORD dwTime)
{
    TOOLATEINFO* ptli = reinterpret_cast<TOOLATEINFO*>(
        GetWindowLongPtr(hwnd, GWLP_USERDATA));
    if (ptli) {
        ptli->fTimedOut = TRUE;
        if (ptli->hwndReenable) {
            EnableWindow(ptli->hwndReenable, TRUE);
        }
        PostQuitMessage(42);
    }
}

int TimedMessageBox(HWND hwndOwner, LPCTSTR ptszText,
    LPCTSTR ptszCaption, UINT uType, DWORD dwTimeout)
{
    TOOLATEINFO tli;
    tli.fTimedOut = FALSE;
    BOOL fWasEnabled = hwndOwner && IsWindowEnabled(hwndOwner);
    tli.hwndReenable = fWasEnabled ? hwndOwner : NULL;
    HWND hwndScratch = CreateDummyWindow(hwndOwner);
    if (hwndScratch) {
        SetWindowLongPtr(hwndScratch, GWLP_USERDATA,
            reinterpret_cast<LPARAM>(&tli));
        SetTimer(hwndScratch, IDT_TOOLATE, dwTimeout, MsgBoxTooLateProc);
    }
    int iResult = MessageBox(hwndOwner, ptszText, ptszCaption, uType);
    if (hwndScratch) {
        KillTimer(hwndScratch, IDT_TOOLATE);
        if (tli.fTimedOut) { // We timed out
            MSG msg;
            // Eat the fake WM_QUIT message we generated
            PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
            iResult = -1;
        }
        DestroyWindow(hwndScratch);
    }
    return iResult;
}

위의 소스코드가 약간 복잡해 보이는 듯하지만, 사실 지난번 소스코드를 이해했다면 GWLP_USERDATA에 따른 처리만 추가된 것임을 알 수 있을 것입니다.

위의 메시지 박스에 대한 사용법은 동일하게 호출할 수 있고,

TimedMessageBox(hWnd, L"TEXT", L"TITLE", MB_OK, 3000);

지정한 3초의 시간이 흐른 후 메시지 박스가 자동으로 닫히는 것을 확인할 수 있습니다. 물론, ^^ 위의 시간 만료 메시지 박스는 (전역 변수가 없으므로) 스레드 제약 없이 사용할 수 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




자, 이것으로 oldnewthing의 Modality에 관한 8개의 글을 모두 정리했습니다. ^^

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

Modality, part 1: UI-modality vs code-modality
; https://devblogs.microsoft.com/oldnewthing/20050218-00/?p=36413

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

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

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

Modality, part 3: The WM_QUIT message
; https://devblogs.microsoft.com/oldnewthing/20050222-00/?p=36393

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

Modality, part 4: The importance of setting the correct owner for modal UI
; https://devblogs.microsoft.com/oldnewthing/20050223-00/?p=36383

Modality, part 5: Setting the correct owner for modal UI
; https://devblogs.microsoft.com/oldnewthing/20050224-00/?p=36373

Modality, part 6: Interacting with a program that has gone modal
; https://devblogs.microsoft.com/oldnewthing/20050228-00/?p=36343

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

Modality, part 7: A timed MessageBox, the cheap version
; https://devblogs.microsoft.com/oldnewthing/20050301-00/?p=36333 

요즘 시대에 이 글이 유용할지는 모르겠지만! ^^




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







[최초 등록일: ]
[최종 수정일: 4/24/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)
13439정성태11/10/20233100닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232669닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232853닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233106닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233004닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232781스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232470스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232551오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232935스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232764닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233052닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233153닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233340닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233490스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233256닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233233스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233391닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233477닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235796스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233286스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233999닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233527닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233802닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233580디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233776닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...