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)
13917정성태4/30/202528VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/2025430디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20251637닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20251964디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251187오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/2025848닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251075오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20251240디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20251710닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20252121닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20251904VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20252157닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20252191Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20251879디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20251508VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20251719개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20252097Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20252331스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251790스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20252109오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20252343닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20252162Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20252205Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20252233Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20252180Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...