Adding a image element to a webbrowser control pag

2019-08-31 03:40发布

I'm trying to create an element with a image to a windows forms webbrowser control existing site. Then I want to move the created element to a certain position. I have this code, but it doesn't work.

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.GetElementById("gpu_notice").Style = "display:none"; 
        webBrowser1.Document.GetElementById("header").OuterHtml = "";
        webBrowser1.Document.GetElementById("ads").OuterHtml = "";
        webBrowser1.Document.GetElementById("the_game").Style += "position: absolute; top: 0px; right: 0px;";
        HtmlElement logo = webBrowser1.Document.CreateElement("logo");
        logo.SetAttribute("SRC", @"C:\Users\Susana\Documents\Projeto HaxballK\Design\Logo HK.png");
        webBrowser1.Document.Body.AppendChild(logo);
        logo.SetAttribute("float", "right");
    }

标签: c# forms
2条回答
唯我独甜
2楼-- · 2019-08-31 03:55

Is the task inserting an element to an existing HTML document displayed with the WebBrowser class? If yes, then the steps could be (not tested, sorry)

  1. download the document using WebClient as a HTML string
  2. make <body> relative in the HTML string (insert style='position: relative' into the <body> element)
  3. insert the element into the HTML string, just after <body>, make the element absolute (setting style='position: absolute; left=...; right=...'
  4. set the modified HTML string into DocumentText property of the WebBrowser class
查看更多
Anthone
3楼-- · 2019-08-31 04:06

You have to use "img" tag instead of "logo" and set the file path with using file protocol.

HtmlElement logo = webBrowser1.Document.CreateElement("img");
logo.SetAttribute("SRC", @"file:///C:/Users/Susana/Documents/Projeto HaxballK/Design/Logo HK.png");
webBrowser1.Document.Body.AppendChild(logo);
logo.SetAttribute("float", "right");

UPDATED

If you want to add the image after all the JavaScript initializations have run, simply use one off Timer.

System.Windows.Forms.Timer timer = new Timer();
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // other processes

    timer.Interval = 1 * 1000 * 5; // 5 seconds
    timer.Tick += timer_Tick;
    timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    timer.Tick -= timer_Tick;

    HtmlElement logo = webBrowser1.Document.CreateElement("img");
    logo.SetAttribute("SRC", @"file:///C:/Users/Susana/Documents/Projeto HaxballK/Design/Logo HK.png");
    webBrowser1.Document.Body.AppendChild(logo);
    logo.SetAttribute("float", "right");
}
查看更多
登录 后发表回答