WebBrowser Control
设置 webBrowser1.DocumentText 时似乎重新排列 HTML 标记中的属性。
我想知道我是否缺少某种渲染模式或文档编码。只需将RichTextBoxControl
(txt_htmlBody) 和 WebBrowser 控件 (webBrowser1) 添加到 Windows 窗体即可看到我的问题。
添加 webBrowser1 WebBrowser 控件,并添加一个事件处理程序;webBrowser1_DocumentCompleted
我用它来将鼠标单击事件添加到 Web 浏览器控件。
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Attach an event to handle mouse clicks on the web browser
this.webBrowser1.Document.Body.MouseDown += new HtmlElementEventHandler(Body_MouseDown);
}
在鼠标点击事件中,我们像这样得到点击了哪个元素;
private void Body_MouseDown(Object sender, HtmlElementEventArgs e)
{
// Get the clicked HTML element
HtmlElement elem = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition);
if (elem != null)
{
highLightElement(elem);
}
}
private void highLightElement(HtmlElement elem)
{
int len = this.txt_htmlBody.TextLength;
int index = 0;
string textToSearch = this.txt_htmlBody.Text.ToLower(); // convert everything in the text box to lower so we know we dont have a case sensitive issues
string textToFind = elem.OuterHtml.ToLower();
int lastIndex = textToSearch.LastIndexOf(textToFind);
// We cant find the text, because webbrowser control has re-arranged attributes in the <img> tag
// Whats rendered by web browser: "<img border=0 alt=\"\" src=\"images/promo-green2_01_04.jpg\" width=393 height=30>"
// What was passed to web browser from textbox: <img src="images/PROMO-GREEN2_01_04.jpg" width="393" height="30" border="0" alt=""/>
// As you can see, I will never be able to find my data in the source because the webBrowser has changed it
}
添加txt_htmlBody
RichTextBox
到表单中,并设置一个TextChanged 的RichTextBox
事件来设置WebBrowser1.DocumentText
为RichTextBox
(txt_htmlBody) 文本改变。
private void txt_htmlBody_TextChanged(object sender, EventArgs e)
{
try
{
webBrowser1.DocumentText = txt_htmlBody.Text.Replace("\n", String.Empty);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
运行程序时,将下面的示例 HTML 复制到 txt_htmlBody 中,然后单击右侧的 Image 并调试 highLightElement。您会从我的评论中看到为什么我在搜索字符串中找不到指定的文本,因为WebBrowser
控件会重新排列属性。
<img src="images/PROMO-GREEN2_01_04.jpg" width="393" height="30" border="0" alt=""/>
有谁知道如何让 WebBrowser 控件按原样呈现我的 HTML?
感谢您的时间。