【问题标题】:WPF application message loop and PostThreadMessageWPF 应用程序消息循环和 PostThreadMessage
【发布时间】:2013-08-13 12:25:34
【问题描述】:

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

【问题讨论】:

标签: wpf windows multithreading winapi


【解决方案1】:

我使用 .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 的实现,它确实会在RaiseThreadMessage 内部的执行过程中触发ComponentDispatcher.ThreadFilterMessage 事件:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 2021-03-23
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多