Send or post a message to a Windows Forms message loop

前端 未结 3 432
离开以前
离开以前 2021-02-04 05:29

I have a thread that reads messages from a named pipe. It is a blocking read, which is why it\'s in its own thread. When this thread reads a message, I want it to notify the Win

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 05:42

    PostMessage (and likewise SendMessage) are Win32 API functions, and thus are not directly associated with .NET. .NET does however have good support for interoping with the Win32 API, using P/Invoke calls.

    As it seems you are new to doing Win32 programming .NET, this MSDN Magazine article provides a solid introduction on the topic.

    The excellent pinvoke.net website details how to use many of these API functions from C#/VB.NET. See this page for PostMessage specifically.

    The standard declaration is the following:

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    

    But as the page indicates, it is wise to wrap this function to handle Win32 errors properly:

    void PostMessageSafe(HandleRef hWnd, uint msg, IntPtr wParam, IntPtr lParam)
    {
        bool returnValue = PostMessage(hWnd, msg, wParam, lParam);
        if(!returnValue)
        {
            // An error occured
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }        
    

提交回复
热议问题