本文介绍了NET webbrowser - 通过单击图像获取 HTML 元素 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有 webbrowser 控件的 C# winform 项目.我正在将带有图像的 HTML 页面加载到网络浏览器中.每个图像都有不同的 ID:
I have a C# winform project with a webbrowser control. I'm loading an HTML page with images into the webbrowser. Each image has a different ID:
<img src="F:\Temp\file12948.jpg" id="12948" width="180px">
有没有办法在单击图像时将 ID 传递给变量,以便我可以在代码中使用 ID?也可以使用图像的路径,因为我可以从那里提取数字.
Is there a way to pass the ID into a variable when clicking on the image so I can use the ID in my code? The path to the image can also be used as I can extract the number from there.
我已经在这里到处寻找解决方案,但找不到任何相关的东西.
I have already searched here there and everywhere for a solution but can't find anything related.
推荐答案
您可以动态附加到图像的 onClick 事件.
You can dynamically attach to image's onClick event.
public class TestForm : Form
{
WebBrowser _WebBrowser = null;
public TestForm()
{
_WebBrowser = new WebBrowser();
_WebBrowser.ScriptErrorsSuppressed = true;
_WebBrowser.Dock = DockStyle.Fill;
this.Controls.Add(_WebBrowser);
WebBrowserDocumentCompletedEventHandler Completed = null;
Completed = (s, e) =>
{
//add onclick event dynamically
foreach (var img in _WebBrowser.Document.GetElementsByTagName("img").OfType<HtmlElement>())
{
img.AttachEventHandler("onclick", (_, __) => OnClick(img));
}
_WebBrowser.DocumentCompleted -= Completed;
};
_WebBrowser.DocumentCompleted += Completed;
var imgurl = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
//_WebBrowser.Navigate("http://edition.cnn.com/2017/09/09/us/hurricane-irma-cuba-florida/index.html");
_WebBrowser.DocumentText = $"<html> <img src='{imgurl}' id=123 /> </html>";
}
void OnClick(HtmlElement img)
{
MessageBox.Show(img.GetAttribute("id"));
}
}
这篇关于NET webbrowser - 通过单击图像获取 HTML 元素 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!