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)
13356정성태5/15/20233894DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233830.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234089.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233698.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234206VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233477오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233782.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233686.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234076.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233905오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235280.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236489.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234360디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234272.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234005닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234078오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234740닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234261닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234764Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234569.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234673.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234307Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233750Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233852Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233883오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233526Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...