【发布时间】:2011-04-05 15:50:35
【问题描述】:
我已将 COM 接口 IPreviewHandler 导入 WinForms 应用程序并使用它来显示各种类型文档的预览(我在注册表中查找相应预览处理程序的 GUID,然后使用 Activator.CreateInstance(guid)实例化特定的 COM 类。
这适用于绝大多数文件类型 - Office 格式、PDF、视频等 - 但是,在我实例化“Microsoft Windows TXT 预览处理程序”{1531d583-8375-4d3f-b5fb-d23bbd169f22} 后,将其初始化为一个包含普通 .txt 文件的流,设置预览窗口的边界,然后最后调用 DoPreview(),我得到一个使用 try...catch 无法捕获的异常:
try {
Type comType = Type.GetTypeFromCLSID(guid);
object handler = Activator.CreateInstance(comType);
if (handler is IInitializeWithStream) {
Stream s = File.Open(filename, FileMode.Open);
// this just passes the System.IO.Stream as the COM type IStream
((IInitializeWithStream)handler).Initialize(new StreamWrapper(s), 0);
}
else {
throw new NotSupportedException();
}
RECT r = new RECT();
r.Top = 0;
r.Left = 0;
r.Right = hostControl.Width;
r.Bottom = hostControl.Height;
((IPreviewHandler)handler).SetWindow(hostControl.Handle, ref r);
((IPreviewHandler)handler).DoPreview(); // <-- crash occurs here
}
catch (Exception) {
// this will never execute
}
当我使用调试器单步执行时,Visual Studio 托管进程崩溃。如果没有调试器,应用程序会在不触发 AppDomain.UnHandledException 或 Application.ThreadException 事件的情况下崩溃。
我真的不介意我不能使用这种技术预览纯文本文件(Office 格式的工作预览处理程序等足以满足我的应用程序的要求),但我担心我的应用程序崩溃失控应该用户选择一个 .txt 文件。有什么办法可以捕捉到这个错误并优雅地处理它?更好的是,有什么方法可以克服它并让处理程序工作吗?
【问题讨论】:
-
没有类型库。您是如何“导入”接口声明的?
-
@Hans Passant:使用
[ComImport]和[Guid]属性的手动声明。源码见我博客:brad-smith.info/blog/archives/79