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 대화창 구현 (쉬운 버전)

우리가 만든 대화창의 경우, 일정 시간 동안 사용자가 입력을 하지 않는다면 Dialog Procedure에 코드를 추가해 자동으로 닫는 것이 가능합니다.

예를 들어 볼까요? ^^ Visual Studio로 만든 기본 Windows Application C++ 프로젝트에서 About 대화창의 코드를 다음과 같이 바꿀 수 있습니다.

INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    static UINT _idTimer;

    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        _idTimer = SetTimer(hDlg, 0, 3000, nullptr);
        return (INT_PTR)TRUE;

    case WM_TIMER:
        if (_idTimer)
        {
            ::KillTimer(hDlg, _idTimer);
            _idTimer = 0;
        }
        EndDialog(hDlg, 0);
        break;

    case WM_CLOSE: // modal 대화창의 우측 상단 'x' 버튼을 누른 경우,
        ::OutputDebugString(L"About Dialog - WM_CLOSE\n");
        break;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            if (_idTimer)
            {
                ::KillTimer(hDlg, _idTimer);
                _idTimer = 0;
            }

            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

사용자가 OK/CANCEL 버튼이나 타이틀 바 영역의 'x' 버튼을 누르지 않는다면 3초 후 자동으로 대화창이 닫히게 됩니다.

자, 그렇다면 우리가 만든 대화창이 아닌 경우, 예를 들어 MessageBox라면 어떻게 할 수 있을까요? 여기서 관건은, MessageBox를 호출한 후 내부에서 실행되는 Message Loop를 일정 시간이 지났을 때 탈출하도록 만들어야 한다는 점입니다.

이것을 쉽게 구현하는 한 가지 방법을 다음의 글에서 소개하고 있습니다.

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

방법은 간단합니다. SetTimer를 이용해 일정 시간 후 메시지 루프를 벗어나도록 WM_QUIT 메시지를 생성하는 것입니다. 그럼 당연히 MessageBox 내의 Message Loop는 벗어나게 될 것입니다. 하지만 그와 함께 다시 WM_QUIT 메시지가 메시지 큐에 저장이 되는데요, 그걸 그냥 두면 윈도우 응용 프로그램이 생성해 둔 메시지 루프 전체로 퍼지게 됩니다. 따라서, 이것을 방지하기 위해 메시지 큐에 있는 WM_QUIT를 그냥 제거하는 처리를 하면 됩니다.

바로 그 역할을 하는 코드가 "Modality, part 7: A timed MessageBox, the cheap version" 글에 다음과 같이 실려 있습니다.

static BOOL s_fTimedOut;
static HWND s_hwndMBOwnerEnable;

void CALLBACK CheapMsgBoxTooLateProc(HWND hWnd, UINT uiMsg, UINT_PTR idEvent, DWORD dwTime)
{
    s_fTimedOut = TRUE;
    if (s_hwndMBOwnerEnable) EnableWindow(s_hwndMBOwnerEnable, TRUE); // 활성화 순서
    PostQuitMessage(42); // value not important
}

int TimedMessageBox(HWND hwndOwner, LPCTSTR ptszText, LPCTSTR ptszCaption, UINT uType, DWORD dwTimeout)
{
    s_fTimedOut = FALSE;
    s_hwndMBOwnerEnable = NULL;
    
    if (hwndOwner && IsWindowEnabled(hwndOwner)) {
        s_hwndMBOwnerEnable = hwndOwner;
    }

    UINT idTimer = SetTimer(NULL, 0, dwTimeout, CheapMsgBoxTooLateProc);
    int iResult = MessageBox(hwndOwner, ptszText, ptszCaption, uType);
    if (idTimer) KillTimer(NULL, idTimer);
    
    if (s_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;
    }
    
    return iResult;
}

보는 바와 같이 WM_QUIT를 생성해 MessageBox를 벗어난 다음, PeekMessage를 이용해 WM_QUIT를 제거하고 있습니다. 실제로 위의 함수를 이용하면,

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

3초 후에 MessageBox가 종료되는 것을 확인할 수 있습니다. 그런데 위의 코드에는 문제가 있습니다. 바로 전역 변수를 사용하기 때문에 그로 인해 발생하는 충돌을 조심해서 사용해야 하는 것입니다.




근데, WM_QUIT를 사용하기 때문에 솔직히 좀 복잡합니다. ^^ 그냥 단순히 WM_CLOSE를 사용한다면 저런 후처리를 하지 않아도 되는데요, 여기서 문제는 WM_CLOSE를 보내기 위해 MessageBox의 윈도우 핸들(HWND)을 알아내야 한다는 것입니다.

재미있는 것은, 위의 방법을 지난 글에서 설명했다는 점입니다. 즉, GetLastActivePopup을 사용하면 되는 건데요, 이것을 이용하면 위의 TimedMessageBox를 다음과 같이 축약시킬 수 있습니다.

#define IDT_TIMER 0x5000

void CALLBACK CheapMsgBoxTooLateProc(HWND hWnd, UINT uiMsg, UINT_PTR idEvent, DWORD dwTime)
{
    HWND hDlg = ::GetLastActivePopup(hWnd);
    if (IsWindow(hDlg))
    {
        ::SendMessage(hDlg, WM_CLOSE, 0, 0);
    }
}

int TimedMessageBox(HWND hwndOwner, LPCTSTR ptszText, LPCTSTR ptszCaption, UINT uType, DWORD dwTimeout)
{
    UINT idTimer = SetTimer(hwndOwner, IDT_TIMER, dwTimeout, CheapMsgBoxTooLateProc);
    int iResult = MessageBox(hwndOwner, ptszText, ptszCaption, uType);
    if (idTimer != 0)
    {
        KillTimer(hwndOwner, IDT_TIMER);
    }

    return iResult;
}

하지만 위의 코드도 문제가 있습니다. hwndOwner를 CheapMsgBoxTooLateProc에 전달하기 위해 SetTimer의 첫 번째 인자에 전달했는데요, 만약 TimedMessageBox를 라이브러리 성격의 DLL에 추가시켜 재사용하는 경우라면 hwndOwner로 전달한 윈도우가 기존에 생성한 SetTimer의 ID 값들 중에 IDT_TIMER(0x5000)와 겹칠 수 있는 가능성이 (거의 낮은 확률이지만) 존재한다는 점입니다. (아쉽게도 SetTimer에는 CheapMsgBoxTooLateProc에 전달할 수 있는 LPARAM 등의 인자가 없습니다.)

따라서 timer id 조차도 인자로 받도록 구성하면 좀 나아질 것입니다.

이 정도면, 뭐 그런대로 원리는 아시겠죠? ^^ 다음에 다룰 part 8에서는 위에서 소개한 자잘한 문제들을 해결한, 약간 복잡한 코드를 소개합니다.

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




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







[최초 등록일: ]
[최종 수정일: 4/10/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2024-09-04 08시10분
What is a hard error, and what makes it harder than an easy error?
; https://devblogs.microsoft.com/oldnewthing/20240116-00/?p=109274

Why did Windows 95 use blue screen error messages instead of hard error messages?
; https://devblogs.microsoft.com/oldnewthing/20240903-00/?p=110205
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12206정성태4/2/202018366오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015033스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015057스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017856오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021120개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018364오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018473VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016119오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019502오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018744VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015920오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018247.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020965오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017856개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019869개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021001개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015548오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021168개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202025986Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015505오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017368오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017939오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019866오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202017670오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202019167.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202019433기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...