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

비밀번호

댓글 작성자
 




... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12785정성태8/16/202116511.NET Framework: 1090. .NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원 [1]파일 다운로드1
12784정성태8/15/202116251오류 유형: 757. 구글 메일 - 아웃룩에서 메일 전송 시 Sending' reported error (0x800CCC0F, 0x800CCC92)
12783정성태8/15/202114255.NET Framework: 1089. C# - Indexer에 Range 및 람다 식을 이용한 필터 구현 [1]파일 다운로드1
12782정성태8/14/202113794오류 유형: 756. 파이썬 - 윈도우 환경에서 pytagcloud의 한글 출력 방법
12781정성태8/14/202116129오류 유형: 755. 파이썬 - konlpy 사용 시 JVM과 jpype1 관련 오류
12780정성태8/13/202114676.NET Framework: 1088. C# - 버스 노선 및 위치 정보 조회 API 사용을 위한 기초 라이브러리 [2]
12779정성태8/13/202116921개발 환경 구성: 596. 공공 데이터 포털에서 버스 노선 및 위치 정보 조회 API 사용법
12778정성태8/12/202113160오류 유형: 755. PyCharm - "Manage Repositories"의 목록이 나오지 않는 문제
12777정성태8/12/202115108오류 유형: 754. Visual Studio - Input or output cannot be redirected because the specified file is invalid.
12776정성태8/12/202113949오류 유형: 753. gunicorn과 uwsgi 함께 사용 시 ERR_CONNECTION_REFUSED
12775정성태8/12/202127372스크립트: 22. 파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 gunicorn을 이용해 실행
12774정성태8/11/202116996.NET Framework: 1087. C# - Collection 개체의 다중 스레드 접근 시 "Operations that change non-concurrent collections must have exclusive access" 예외 발생
12773정성태8/11/202116388개발 환경 구성: 595. PyCharm - WSL과 연동해 Django App을 윈도우에서 리눅스 대상으로 개발
12772정성태8/11/202117065스크립트: 21. 파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 uwsgi를 이용해 실행 [1]
12771정성태8/11/202115469Windows: 196. "Microsoft Windows Subsystem for Linux Background Host" / "Vmmem"을 종료하는 방법
12770정성태8/11/202116303.NET Framework: 1086. C# - Windows Forms 응용 프로그램의 자식 컨트롤 부하파일 다운로드1
12769정성태8/11/202113324오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main 두 번째 이야기
12768정성태8/10/202114725.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [1]파일 다운로드1
12767정성태8/10/202115673오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main
12766정성태8/9/202113742Java: 32. closing inbound before receiving peer's close_notify
12765정성태8/9/202114034Java: 31. Cannot load JDBC driver class 'org.mysql.jdbc.Driver'
12764정성태8/9/202152301Java: 30. XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid
12763정성태8/9/202116081Java: 29. java.lang.NullPointerException - com.mysql.jdbc.ConnectionImpl.getServerCharset
12762정성태8/8/202119371Java: 28. IntelliJ - Unable to open debugger port 오류
12761정성태8/8/202116045Java: 27. IntelliJ - java: package javax.inject does not exist [2]
12760정성태8/8/202112823개발 환경 구성: 594. 전용 "Command Prompt for ..." 단축 아이콘 만들기
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...