WPF 应用程序消息循环和 PostThreadMessage

标签 wpf windows multithreading winapi

对于 WPF 应用程序,Application.Run 内部是否存在经典的消息循环(在 Windows 的 GetMessage/DispatchMessage 意义上)?是否可以使用 PostThreadMessage 捕获从另一个 Win32 应用程序发布的消息到 WPF UI 线程(没有 HWND 句柄的消息)。谢谢。

最佳答案

我使用 .NET Reflector 来跟踪 Applicaton.Run 实现直至 Dispatcher.PushFrameImpl。也可以从 .NET Framework reference sources 获得相同的信息。 .确实有一个经典的消息循环:

private void PushFrameImpl(DispatcherFrame frame)
{
    SynchronizationContext syncContext = null;
    SynchronizationContext current = null;
    MSG msg = new MSG();
    this._frameDepth++;
    try
    {
        current = SynchronizationContext.Current;
        syncContext = new DispatcherSynchronizationContext(this);
        SynchronizationContext.SetSynchronizationContext(syncContext);
        try
        {
            while (frame.Continue)
            {
                if (!this.GetMessage(ref msg, IntPtr.Zero, 0, 0))
                {
                    break;
                }
                this.TranslateAndDispatchMessage(ref msg);
            }
            if ((this._frameDepth == 1) && this._hasShutdownStarted)
            {
                this.ShutdownImpl();
            }
        }
        finally
        {
            SynchronizationContext.SetSynchronizationContext(current);
        }
    }
    finally
    {
        this._frameDepth--;
        if (this._frameDepth == 0)
        {
            this._exitAllFrames = false;
        }
    }
}

此外,这里是 TranslateAndDispatchMessage 的实现,它确实触发了 ComponentDispatcher.ThreadFilterMessage RaiseThreadMessage 中执行过程中的事件:

private void TranslateAndDispatchMessage(ref MSG msg)
{
    if (!ComponentDispatcher.RaiseThreadMessage(ref msg))
    {
        UnsafeNativeMethods.TranslateMessage(ref msg);
        UnsafeNativeMethods.DispatchMessage(ref msg);
    }
}

显然,它适用于任何已发布的消息,而不仅仅是键盘消息。您应该能够订阅 ComponentDispatcher.ThreadFilterMessage 并观察您感兴趣的消息。

关于WPF 应用程序消息循环和 PostThreadMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182809/

相关文章:

c++ - 有 libPNG 64 位吗?

java - JApplet显示

Java Swing : do I need two threads?

wpf - x 秒后删除图像源

wpf - 动画文本颜色

c# - 从 wpf datagrid 复制一个数据到 lotus notes

java - 您如何思考和预测这样的线程问题的输出?

wpf - 确保实现 WPF 任务栏窗口预览

windows - 无法连接到 URL 'svn://localhost' 的存储库

android - 以编程方式删除的文件仍然显示在 Windows 资源管理器中