Visual Basic:为Web浏览器添加边距

时间:2015-04-02 15:27:00

标签: vb.net visual-studio

我在VB中使用Web浏览器,我一直在尝试在页面顶部添加边距。我只需要在我导航到的页面上使用20-30px标题,删除。

我选择了webbrowser后测试了属性窗口上的设置,但它没有用(除非我做错了)

有没有办法以编程方式使用vb代码或可能使用固定在所有页面上的css / html,以便显示边距?

以下是我创建的图片的可视示例: http://s9.postimg.org/t7gqe5exb/webbrowser_example.png

1 个答案:

答案 0 :(得分:0)

您需要做的是,在网络浏览器完成加载页面时监控,然后将一个javascript代码注入页面,这将调整边距:

Imports System.IO

'add a reference to the COM object "Microsoft HTML Object Library" for this
Imports mshtml

Public Class Form4
    'execute a code every time the webBrowser finishes loading a page
    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        'find the head element of the loaded page
        Dim headElement As HtmlElement = WebBrowser1.Document.GetElementsByTagName("head")(0)
        'create a script element
        Dim scriptElement As HtmlElement = WebBrowser1.Document.CreateElement("script")
        Dim element As IHTMLScriptElement = DirectCast(scriptElement.DomElement, IHTMLScriptElement)
        'write the actual script to the script element 
        element.text = "function adjustMargin() {document.getElementsByTagName('body')[0].style['margin-top']='-40px';}"
        'append our new script element back to the head element of the page
        headElement.AppendChild(scriptElement)
        'call the function from our new script
        WebBrowser1.Document.InvokeScript("adjustMargin")
    End Sub

    Private Sub Form4_Activated(sender As Object, e As EventArgs) Handles Me.Activated
        WebBrowser1.Navigate("www.google.com")
    End Sub
End Class