I imported the IPreviewHandler COM interface into a WinForms application and use it to display a preview for various types of documents (I look at the GUID of the corresponding preview handler in the registry, and then use Activator.CreateInstance(guid) to create an instance of a specific COM class.
This works great for the vast majority of file types - Office formats, PDF files, videos, etc. However, after I create the instance of the "Microsoft Windows TXT Preview Handler" {1531d583-8375-4d3f-b5fb-d23bbd169f22} , initialize its stream containing the regular .txt file, set the borders of the preview window, and then finally call DoPreview() , I get an exception that cannot be caught with 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 go to the debugger, the Visual Studio hosting process crashes. Without a debugger, the application crashes without AppDomain.UnHandledException or Application.ThreadException events.
Actually, I do not mind that I cannot view text files using this technique (preview handlers for Office formats, etc. are sufficient for my applications), but I am worried that the user selects a .txt file. Is there a way to catch this error and handle it gracefully? Even better, is there a way to overcome it and make the handler work?
c # winforms com
Bradley smith
source share