Editing and GDI+ Rendering HTML in Winforms (sample code)
NOTE: See end of article for attached solution file (VS 2005).
The task of editing or rendering HTML within a Winforms application is much more difficult than should be. Microsoft seemed to have conveniently forgotten the need to edit HTML, relying simply on their less-commonly used RTF format. Additionally, the ability to render HTML (or any rich text at all for that matter) using GDI+ also appears to be missing.
In my research on the web, I have not found a definitive solution to using HTML within a Winforms application and therefore crafted one myself by utilizing the MSHTML API’s and the .NET 2.0 WebBrowser control. Because I have a project that requires both HTML editing and GDI+ rendering of rich text, I started work on the control and drawing-helper class that are attached in the solution. With some implementation suggestions from Josh Einstein, I’ve gotten a usable version of both the HTML text box and the GDI+ renderer to the point where I need them to be to complete my initial goals. While my solution is not optimal, nor is it complete, it is a good start to fully implementing HTML editing within Windows Forms.
Current Features
The feature set of the components that are discussed in this article are multi-tiered and as follows:
· HTML Text Box
o Support for toggling bold/italic/underline.
o Bulleted lists
o Paste from other locations (however only by key command and no “MS Word Cleaning”.
o Change color, change font size
o Default CSS style.
o Full editing of HTML.
· GDI+ HTML Renderer
o Renders all HTML that IE is capable of rendering, as IE renders it
o Paints to any GDI+ Graphics device
Limitations and Incomplete Sections
I was admittedly not thorough in my implementation, as I do not wish to release all my intellectual property, nor did I have time to complete all aspects of this project. I expect that much of the coding here on out will have to be done by attaching events from JavaScript, or using MSHTML API’s to reach additional events in the WebBrowser control. Features I have omitted or not completed include:
· Cleaning MS Word HTML
· “Get” accessors of font properties
· Insert HTML at cursor location
· Handling and bubbling of events such as “TextChanged” and “OnClick” (these are not directly available from the Control and will have to be handled directly from the DOM).
This is all possible, and I have several ideas on how to implement this, however I have not gotten around to it. If this project shows a lot of interest, I may invest some additional time plugging these holes. If you want to share your experience plugging the holes with me, please leave me a comment with the changes you’ve made or suggestions you have.
Click here to download the Visual Studio.NET 2005 Solution with source code and a sample Winforms project.