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)
13287정성태3/16/20233933Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234376Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233939Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234165Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233681오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20234001Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233963Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234727개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234234오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234239개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234884개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234544.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234843.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234422.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234178.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234402오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234342오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233916.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234534스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20235065개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234955.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234595오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234513.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20236047스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234208개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235250디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...