Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 2개 있습니다.)
.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
; https://www.sysnet.pe.kr/2/0/13291

닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법
; https://www.sysnet.pe.kr/2/0/13687




C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법

테스트해 보니 PostThreadMessage를 일반적인 메시지 루프 관련 함수에선 수신이 안 됩니다. 아래는 테스트 코드인데요,

using System.Runtime.InteropServices;

namespace WinFormsApp1;

public partial class Form1 : Form
{
    public const int USER_MESSAGE = (0x0400 + 1);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool PostThreadMessage(uint idThread, uint Msg, uint wParam, uint lParam);

    [DllImport("kernel32.dll")]
    public static extern uint GetCurrentThreadId();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1.Interval = 1000;
        timer1.Start();
    }

    public override bool PreProcessMessage(ref Message msg)
    {
        if (msg.Msg == USER_MESSAGE)
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - PreProcessMessage");
        }

        return base.PreProcessMessage(ref msg);
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        if (m.Msg == USER_MESSAGE)
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - WndProc");
        }
    }

    protected override void DefWndProc(ref Message m)
    {
        base.DefWndProc(ref m);

        if (m.Msg == USER_MESSAGE)
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - DefWndProc");
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        PostThreadMessage(GetCurrentThreadId(), USER_MESSAGE, 0, 0);
    }
}

timer1_Tick를 사용해 1초마다 PostThreadMessage로 메시지를 보내고 있는데, PreProcessMessage, WndProc, DefWndProc 중 어느 것도 호출되지 않습니다.

남은 방법으로 생각나는 것이 ^^ IMessageFilter가 있군요,

public partial class Form1 : Form, IMessageFilter
{
    // ...[생략]...

    public Form1()
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    // ...[생략]...

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == USER_MESSAGE)
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - PreFilterMessage");
            return true;
        }

        return false;
    }

    // ...[생략]...
}

실행 결과, if 문을 잘 타고 있습니다.

그나저나, IMessageFilter가 은근히 사용 사례가 많군요. ^^

RawInput을 이용한 키보드/마우스 입력 모니터링
; https://www.sysnet.pe.kr/2/0/11615

Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법
; https://www.sysnet.pe.kr/2/0/12660

C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
; https://www.sysnet.pe.kr/2/0/13291

참고로, PostThreadMessage도 예전에 아래의 주제에서 한 번 다룬 적이 있습니다. ^^

C# - Console 응용 프로그램에서 UI 스레드 구현 방법
; https://www.sysnet.pe.kr/2/0/12139




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/6/2024]

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)
13591정성태4/2/20249429닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20249222Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20249606닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/202410661닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20249539오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/202412384Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/202410100Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/202411672개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법 [9]파일 다운로드1
13583정성태3/25/20249699Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/202410816Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/202410477개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20249461닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/202410410오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/202411145닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/202411077닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/202410344닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/202410803닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/202410283닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20249468닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20249470닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20249435닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/202410077닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/202410180닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20249721닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20249637오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20249543오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...