visual studio 2008 sp1中如何让WebBrowser控件可编辑

我这里强调:是Visual studio 2008 sp1。因为sp1中微软加入了一个WebBrowser控件,这样我们就不需要再去引用WinForm的webBrowser控件了。

<WebBrowser Name="editorWebBrowser"></WebBrowser>

接着我们把 WebBrowser 的 designMode 设置为 "On"

((HTMLDocument)(editorWebBrowser.Document)).designMode = "On";

这样 WebBrowser 就是可编辑状态了

之后,我们来为 WebBrowser 添加几个样式 B(bold),I(italic),U(underline)
首先,定义两个变量 _document, _htmlBody

        private HTMLDocument _document;    //editorWebBrowser.Document as HTMLDocument
private HTMLBody _htmlBody; //(HTMLBody)(_document.body)

创建方法,获取到 WebBrowser 中选定的对象

        private IHTMLTxtRange GetTextRange()
{
IHTMLTxtRange range
= null;
try
{
range
= (IHTMLTxtRange)_document.selection.createRange();
}
catch (Exception)
{
range
= null;
}
return range;
}

好了,然后写一个方法,添加属性到选定的 TextRange

        private bool AppendTagToTextRange(string commandName, object value)
{
_htmlBody
= (HTMLBody)_document.body;

IHTMLTxtRange range
= GetTextRange();

if (range == null || string.IsNullOrEmpty(range.text))
return false;

return range.execCommand(commandName, false, value);

}

最后就是去实现 BI、和 U 三个样式了

AppendTagToTextRange("Bold", "b");

 

AppendTagToTextRange("Italic", "i");


AppendTagToTextRange("UnderLine", "u");
 

呵呵,好像和 Web Editor(网页编辑器)里面用 Javascript 的实现方式相同哦
注意:HTMLDocument,HTMLBody 都要引用控件 using mshtml; (Add References  Microsoft.mshtml)
 
注:原创文章,转载请添加出处,谢谢( http://chenjilv.cnblogs.com )
 

posted on 2008-11-12 10:50  jerreychen  阅读(1159)  评论(0编辑  收藏  举报

导航