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

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  173  174  175  176  177  178  179  [180]  ...
NoWriterDateCnt.TitleFile(s)
520정성태8/7/200722835VS.NET IDE: 51. Visual Studio 2008 베타 2 설치
519정성태7/27/200729178오류 유형: 44. System.BadImageFormatException [2]
518정성태7/26/200730216오류 유형: 43. System.ComponentModel.LicenseException [1]
517정성태7/19/200718435개발 환경 구성: 26. VPC - 일반 사용자 계정으로 구동
516정성태7/19/200721670오류 유형: 42. TFS - Error loading menu: Index was outside the bounds of the array [2]
515정성태7/18/200729645오류 유형: 41. SSL 서버 자격 증명을 만드는 동안 심각한 오류가 발생했습니다.
514정성태7/14/200722184Team Foundation Server: 19. Orcas에서 개선되는 TFS 기능들
513정성태7/4/200733341.NET Framework: 91. Foreground Thread / Background Thread [1]
512정성태6/27/200722839오류 유형: 40. error PRJ0050: Failed to register output.
511정성태6/25/200731043.NET Framework: 90. XmlSerializer 생성자의 실행 속도를 올리는 방법 [2]
510정성태6/25/200746281디버깅 기술: 15. First-Chance Exception
508정성태6/21/200729170Team Foundation Server: 18. Team Build에 사용되는 각종 Property 값 [4]
507정성태6/11/200726795VS.NET IDE: 50. Orcas - UAC 설정 관련
506정성태6/9/200721592오류 유형: 39. VC Package not available or not registered
505정성태6/9/200721318오류 유형: 38. Visual SourceSafe - DB 잠김 오류
504정성태6/9/200726647오류 유형: 37. Visual SourceSafe - Anaylze 도중 비정상 종료
503정성태6/7/200729335VS.NET IDE: 49. Orcas - VC++ 다중 소스 동시 컴파일 옵션: /MP
502정성태6/7/200724119VS.NET IDE: 48. Orcas - VC++ 프로젝트 마이그레이션
500정성태6/4/200732928VS.NET IDE: 47. Orcas - Web Browser Debugger를 이용한 보호 모드의 ActiveX 컨트롤 디버깅
499정성태6/3/200725476VS.NET IDE: 46. Orcas - ComUtil로 인한 증분(/INCREMENTAL) 링크 옵션 사용 제한파일 다운로드1
498정성태5/31/200719966Windows: 26. 스마트 카드 암호 바꾸는 방법.
497정성태5/31/200723416오류 유형: 36. SQL 2005 - DB 속성창 띄울 때 오류
496정성태5/29/200721385VS.NET IDE: 45. VS.NET 2005/Orcas 솔루션 파일과 UAC
495정성태5/28/200723799VS.NET IDE: 44. Orcas와 VS.NET 2005의 혼합 개발 [1]
494정성태5/26/200728115오류 유형: 35. 비스타 탐색기 - 특정 파일을 오른쪽 마우스 클릭했을 때, 비정상 종료되는 문제
493정성태5/26/200727104오류 유형: 34. Windows Server 2008 : CA 인증서 발급 실패
... 166  167  168  169  170  171  172  173  174  175  176  177  178  179  [180]  ...