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)
13707정성태8/6/20245999닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20246367개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20246523닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/20246105닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20246171닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20246113닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20246174닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20245771디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20246241닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20246129닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20246367닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20245952오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20245648닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20246165닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20245662개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20246321디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20245919디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20245291오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20246217디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20245988닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20245940닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/20245861오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/20246115스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/20246001닷넷: 2279. C# - 문자열 보간식 사례
13683정성태7/18/20245990오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/20245986닷넷: 2278. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...