对于 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/