我试图弄清楚如何将 DispatcherObject(在我的情况下为 BitmapSource)复制到另一个线程中。
用例:
我有一个 WPF 应用程序需要在新线程中显示窗口(该应用程序实际上是 Outlook 插件,我们需要这样做,因为 Outlook 在主 UI 线程中有一些钩子,并且正在窃取我们需要使用的某些热键- Outlook、WPF(我们用于 UI)和 Winforms(我们需要使用某些 microsoft 提供的 winforms 控件)的互操作中“丢失翻译”)。
这样,我就有了 WPFMessageBox 的实现,它是通过设置一些静态属性来配置的——其中之一是用于图标的 BitmapSource。使用它是为了在启动时我可以设置 WPFMessageBox.Icon 一次,从那时起,每个 WPFMessageBox 都将具有相同的图标。
问题是分配给icon的BitmapSource是一个DispatcherObject,读取时会抛出InvalidOperationException:“调用线程无法访问这个对象,因为不同的线程拥有它。”。
如何将该 BitmapSource 克隆到实际线程中?它有 Clone() 和 CloneCurrentValue() 方法,它们不起作用(它们也抛出相同的异常)。我还想到使用 originalIcon.Dispatcher.Invoke(在此处进行克隆)-但 BitmapSource 的 Dispatcher 为空,并且仍然-我会在错误的线程上创建副本,但仍然无法在我的线程上使用它。BitmapSource.IsFrozen == 真。
关于如何将 BitmapSource 复制到不同的线程中的任何想法(没有从新线程中的图像文件完全重建它)?
编辑: 所以,冻结没有帮助:最后我有一个 BitmapFrame (Window.Icon 无论如何都不采用任何其他类型的 ImageSource),当我将它分配为 Window.Icon 在不同的线程上,即使冻结,我得到 InvalidOperationException:“调用线程无法访问此对象,因为不同的线程拥有它。” 带有以下堆栈跟踪:
WindowsBase.dll!System.Windows.Threading.Dispatcher.VerifyAccess() + 0x4a bytes
WindowsBase.dll!System.Windows.Threading.DispatcherObject.VerifyAccess() + 0xc bytes
PresentationCore.dll!System.Windows.Media.Imaging.BitmapDecoder.Frames.get() + 0xe bytes
PresentationFramework.dll!MS.Internal.AppModel.IconHelper.GetIconHandlesFromBitmapFrame(object callingObj = {WPFControls.WPFMBox.WpfMessageBoxWindow: header}, System.Windows.Media.Imaging.BitmapFrame bf = {System.Windows.Media.Imaging.BitmapFrameDecode}, ref MS.Win32.NativeMethods.IconHandle largeIconHandle = {MS.Win32.NativeMethods.IconHandle}, ref MS.Win32.NativeMethods.IconHandle smallIconHandle = {MS.Win32.NativeMethods.IconHandle}) + 0x3b bytes
> PresentationFramework.dll!System.Windows.Window.UpdateIcon() + 0x118 bytes
PresentationFramework.dll!System.Windows.Window.SetupInitialState(double requestedTop = NaN, double requestedLeft = NaN, double requestedWidth = 560.0, double requestedHeight = NaN) + 0x8a bytes
PresentationFramework.dll!System.Windows.Window.CreateSourceWindowImpl() + 0x19b bytes
PresentationFramework.dll!System.Windows.Window.SafeCreateWindow() + 0x29 bytes
PresentationFramework.dll!System.Windows.Window.ShowHelper(object booleanBox) + 0x81 bytes
PresentationFramework.dll!System.Windows.Window.Show() + 0x48 bytes
PresentationFramework.dll!System.Windows.Window.ShowDialog() + 0x29f bytes
WPFControls.dll!WPFControls.WPFMBox.WpfMessageBox.ShowDialog(System.Windows.Window owner = {WPFControlsTest.MainWindow}) Line 185 + 0x10 bytes C#