I've imported the COM interface IPreviewHandler
into a WinForms app and am using it to display previews for various types of documents (I look up the GUID of the appropriate preview handler in the registry, then use Activator.CreateInstance(guid)
to instantiate the specific COM class.
This works wonderfully for the vast majority of file types - Office formats, PDFs, videos, etc - however, after I instantiate the "Microsoft Windows TXT Preview Handler" {1531d583-8375-4d3f-b5fb-d23bbd169f22}
, initialise it with a stream containing an ordinary .txt file, set the bounds of the preview window and then finally call DoPreview()
, I get an exception that cannot be caught using 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
}
When I step through with the debugger, the Visual Studio Hosting Process crashes. With no debugger, the application crashes without firing the AppDomain.UnHandledException
or Application.ThreadException
events.
I don't really mind that I can't preview plain text files using this technique (the working preview handlers for Office formats, etc are sufficient for my app's requirements), but I am concerned about having my app crash uncontrollably should the user select a .txt file. Is there any way I can catch this error and handle it gracefully? Better yet, is there some way I can overcome it and get the handler to work?