C# 如何获取 WebBrowser 控件的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9924382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the URL of a WebBrowser control
提问by Ian Lundberg
if (webBrowser1.Url.AbsoluteUri == "www.google.com")
{
label9.Text = webBrowser1.Url.AbsoluteUri;
}
This is my current code. When I press the button to run this I get the error.
这是我目前的代码。当我按下按钮运行它时,我收到错误消息。
Object reference not set to an instance of an object.
你调用的对象是空的。
And I don't know why it does that or how to fix it. Any help will be great.
我不知道它为什么这样做或如何解决它。任何帮助都会很棒。
Also It have to work in a timer so that it can be checked.
它也必须在计时器中工作,以便可以检查它。
采纳答案by ?zgür Kara
probably your webBrowser1.Urlis nulltry below to get url
可能您webBrowser1.Url正在null尝试以下获取网址
string url = "";
if (webBrowser1.Url != null)
{
url = webBrowser1.Url.AbsoluteUri;
}
if (url == "www.google.com")
{
label9.Text = url;
}
回答by ionden
The UrlProperty will remain nulluntill the control is rendered so use this:
该Url属性将一直保留null到控件被呈现,所以使用这个:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
if (webBrowser1.Url.ToString() == "www.google.com") {
label9.Text = webBrowser1.Url.ToString();
}
}
And in your button Clickevent add:
并在您的按钮Click事件中添加:
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
回答by Spiri
Well you didn't set any url (no page is loaded inside the web browser). You could try this:
好吧,您没有设置任何 url(Web 浏览器中没有加载任何页面)。你可以试试这个:
webBrowser1.Url = new Uri("http://www.google.com", UriKind.Absolute);
webBrowser1.Url = new Uri("http://www.google.com", UriKind.Absolute);
And get the url this way: webBrowser1.Url.ToString();
并以这种方式获取 url: webBrowser1.Url.ToString();
Wait for the page to load and the press then button.
等待页面加载,然后按下按钮。
回答by berni3mack
I thought id comment on this, I literally took your
我想我对此发表评论,我真的把你的
"webBrowser1.Url.AbsoluteUri;"
and in my case im using a combotextbox so Double click your browser form and it will take you to the even handler, i just put
在我的情况下,我使用了一个组合文本框,所以双击您的浏览器表单,它将带您到偶数处理程序,我只是把
"combobox1.text= webBrowser1.Url.AbsoluteUri;"
and it works for me now. You got me on the time, but whatever you need to check, check for the combobox1.text or whatever you are using for your url's
它现在对我有用。你让我准时了,但无论你需要检查什么,检查组合框1.text或任何你用于你的网址的
回答by Neo
if your browser1 is chromiumwebbrowser, then use
如果您的 browser1 是 Chromiumwebbrowser,则使用
string url = browser1.Address;
call the url and you will get it.
打电话给网址,你会得到它。

