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 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법

스레드 메시지는 PostThreadMessage를 이용해서 발생시킬 수 있는데요,

BOOL PostThreadMessageW(
  [in] DWORD  idThread,
  [in] UINT   Msg,
  [in] WPARAM wParam,
  [in] LPARAM lParam
);

보는 바와 같이 대상 스레드, 즉 메시지 루프를 돌고 있는 스레드의 ID를 이용해 메시지를 (Send가 아닌 Post로) 전송하는 방식입니다. 그런데, 사실 일반적인 메시지 루프에서는 PostThreadMessage로 전송한 메시지는 처리되지 않습니다. 그 이유를 아래의 글에서 설명하고 있는데요,

Thread messages are eaten by modal loops
; https://devblogs.microsoft.com/oldnewthing/20050426-18/?p=35783

왜냐하면, 아래와 같이 구현한 메시지 루프의 경우,

while (GetMessage(&msg, NULL, 0, 0)) {
 TranslateMessage(&msg);
 DispatchMessage(&msg);
}

DispatchMessage는 msg.hwnd 필드에 지정한 윈도우로 메시지를 전송하는 것만 하기 때문입니다. 따라서 인자로 윈도우 핸들이 아닌 스레드 ID를 받는 PostThreadMessage로 전송하게 되면 msg.hwnd는 null이 되고 결국 그 메시지를 수신하는 Window Procedure가 없기 때문에 당연히 메시지 처리가 안 됩니다.

결국, 이에 대한 해결책으로 내놓는 것은,

Watching thread messages disappear
; https://devblogs.microsoft.com/oldnewthing/20050427-10/?p=35763

BOOL IsThreadMessage(MSG *pmsg)
{
 if (pmsg->hwnd == NULL) {
  switch (pmsg->message) {
   case WM_APP: MessageBeep(-1); return TRUE;
  }
 }
 return FALSE;
}

...[함수 생략]...
while (GetMessage(&msg, NULL, 0, 0)) {
    if (!IsThreadMessage(&msg)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    }
}

PostThreadMessage로 전송한 메시지를 별도로 처리하는 코드를 GetMessage 다음에 넣어두는 정도에 불과합니다. (실제로 제가 예전에 소개한 콘솔 응용 프로그램용 메시지 루프도 그런 식으로 구현됐습니다.)




하지만, 이런 노력이 물거품이 되는 순간이 있습니다. 바로 Modal 대화창을 띄운 경우인데요, 당연히 (그 어느 누가 임의로 구현했을) modal 메시지 루프에서는 PostThreadMessage 메시지 처리에 대한 배려가 전혀 없으므로 (사실 배려할 수도 없으므로) 그런 경우에는 동작하지 않게 됩니다.

물론, 공식적으로 Modal 메시지 루프의 경우에도 PostThreadMessage로 전송한 메시지를 처리할 수 있는 방법이 제공됩니다. 바로 아래의 글에서 소개하고 있는데요,

Rescuing thread messages from modal loops via message filters
; https://devblogs.microsoft.com/oldnewthing/20050428-00/?p=35753

방법은 SetWindowsHookEx을 이용해 WH_MSGFILTER 대상의 훅을 걸어 두는 것입니다.

HHOOK g_hhkMSGF;
LRESULT CALLBACK MsgFilterProc(int code, WPARAM wParam, LPARAM lParam)
{
    MSG* pmsg = (MSG*)lParam;
    if (code >= 0 && IsThreadMessage(pmsg)) return TRUE;
    return CallNextHookEx(g_hhkMSGF, code, wParam, lParam);
}

BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
{
    g_hhkMSGF = SetWindowsHookEx(WH_MSGFILTER, MsgFilterProc, NULL, GetCurrentThreadId());
    if (!g_hhkMSGF) return FALSE;
    ...
}

엄밀히 말해서 WH_MSGFILTER 옵션은 협업에 의한 메시지 후킹 처리를 하는 것인데요, 설명을 보면,

The WH_MSGFILTER hook can only monitor messages passed to a menu, scroll bar, message box, or dialog box created by the application that installed the hook procedure.


Window Manager가 구현한 요소에서만 후킹이 되는 것으로 나옵니다. 왜냐하면, 이런 요소들이 생성한 메시지 루프는, 달리 말해 마이크로소프트가 작성한 Modal 메시지 루프는 반드시 CallMsgFilter를 호출하도록 작성했기 때문입니다.

MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
 if (!CallMsgFilter(&msg, MSGF_MYLIBRARY)) {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }
}

/*
MSGF_MYLIBRARY는 임의의 식별자에 불과하며 다른 예로 commctrl.h에 정의된 상수들이 있습니다.
이 값들은 SetWindowsHookEx로 설치한 후킹 함수의 첫 번째 인자로 전달받게 됩니다.

#define MSGF_COMMCTRL_BEGINDRAG     0x4200
#define MSGF_COMMCTRL_SIZEHEADER    0x4201
#define MSGF_COMMCTRL_DRAGSELECT    0x4202
#define MSGF_COMMCTRL_TOOLBARCUST   0x4203
*/

저렇게 CallMsgFilter가 호출되는 경우에만 SetWindowsHookEx/WH_MSGFILTER로 걸어둔 후킹 메시지가 실행되기 때문에 PostThreadMessage로 전송한 메시지를 처리할 수 있는 기회를 얻게 되는 것입니다.

물론, 위의 방법에도 단점이 있습니다. 일단 마이크로소프트가 만든 Modal 메시지 루프는 전부 CallMsgFilter를 호출하고 있지만, 그렇지 않은 메시지 루프를 갖고 있는 3rd-party 라이브러리도 있을 것이기 때문입니다.

어쩔 수 없습니다. 그런 경우까지 모두 고려해야 한다면 (WH_MSGFILTER가 아닌) WH_GETMESSAGE 옵션으로 SetWindowsHookEx를 설치해야 합니다. 그렇게 되면 GetMessage API 호출 시마다 후킹 함수가 실행돼 자연스럽게 모든 문제가 해결됩니다. 여기서 주의할 것은, Modal Message Loop에서만이 아닌, 기본적으로 모든 메시지에 대한 후킹을 하게 되는 것이므로 부하가 더 커진다는 점입니다.




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







[최초 등록일: ]
[최종 수정일: 4/29/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)
12401정성태11/5/202010838VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207775오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011456.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202010002오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202010184.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208453VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209803오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208188오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208688오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012801.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011054디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010783.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010248오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011033.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011264Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209078오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010298오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011183.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208903오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010583VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207973오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202011002.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010406.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011712디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208406오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209794Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...