Retrieving the URL of a clicked link in a C# WebBrowser control - c#

Okay. So, I'm making my own internet browser and I have tabs. But, I'm trying to make it a real time url updater while if you click on any link it will show up in the textbox of the url.
It will not work.
Here is the tab button.
private void button8_Click(object sender, EventArgs e)
{
WebBrowser Browser = new WebBrowser();
tabControl1.TabPages.Add("New Page");
tabControl1.SelectTab(tabControl1.TabPages.Count - 1);
Browser.Name = "Web Browser";
Browser.Dock = DockStyle.Fill;
tabControl1.SelectedTab.Controls.Add(Browser);
((WebBrowser)(tabControl1.SelectedTab.Controls[0])).GoHome();
And here is where my textbox isn't getting the right url.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
button1.Enabled = true;
textBox1.Enabled = true;
//textBox1.Text = Browser.Url.ToString();
((WebBrowser) (this.tabControl1.SelectedTab.Controls[0])).Url.ToString();
}

In order for this to work, you need to get all link elements of the web page you've just loaded and assign a custom function to the HtmlElement.Click event of that element.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
button1.Enabled = true;
textBox1.Enabled = true;
var linkElements = Browser.Document.GetElementsByTagName("a");
foreach(HtmlElement link in linkElements)
{
link.Click += (s, args) =>
{
// a link is being clicked
// get the url the link is pointing to using the href attribute of the element
textBox1.Text = link.GetAttribute("href");
}
}
}

Related

WebBrowser.DocumentCompleted and Navigate - C#

I'm trying to modify a simple application which use the WebBrowser item:
private void button1_Click(object sender, EventArgs e)
{
var menu = webBrowser1.Document.GetElementById("SomeItem").InvokeMember("click");
webBrowser1.Visible = true;
button1.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Visible = false;
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("domain");
}
This works fine, the page load and then after clicking the button the user is redirected to the desired location.
Now I'm trying to make this without the help of the button.
Simply put the button code inside the load function didn't help, so I've introduced in my code the DocumentCompleted event.
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("SomeDomain");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentComplete);
}
private void wb_DocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
wb.Document.GetElementById("SomeItem").InvokeMember("click");
}
By debugging it, I saw that the wb object is correctly instantiated with the "domain" but I got System.NullReferenceException when I try to retrieve SomeItem.
The document is not fully loaded because I'm still in the load function ?

C# write text to textbox which adds written text to linklabel and when linklabel clicked goes to url?

I'm trying to do the following: I write link to textbox and it displays in a linklabel and after I click linklabel it goes to that url written in it? Everything goes well but pressing linklabel doesn't go to url.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
label2.Text = textBox1.Text;
linkLabel1.Text = textBox2.Text;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.checkbox = checkBox1.Checked;
Properties.Settings.Default.textbox = textBox1.Text;
Properties.Settings.Default.label = label2.Text;
Properties.Settings.Default.linkLabel = linkLabel1.Text;
Properties.Settings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
checkBox1.Checked = Properties.Settings.Default.checkbox;
textBox1.Text = Properties.Settings.Default.textbox;
label2.Text = Properties.Settings.Default.label;
linkLabel1.Text = Properties.Settings.Default.linkLabel;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
You have to start a process with the text of the LinkLabel, which should be a valid URL. This code will open the URL in the default browser:
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(linkLabel1.Text);
}
More info on the Process Class.
If the default browser is IE and you want to open it in Chrome for example you'll have to provide the necessary info:
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Users\<UserName>\AppData\Local\Google\Chrome\chrome.exe";
p.StartInfo.Arguments = linkLabel1.Text;
p.Start();
}
Of course you'll have to do validation to check if the text of the LinkLabel is a valid URL.
You should use following code to add a link to LinkLabel as:
// Add a link to the LinkLabel.
LinkLabel.Link link = new LinkLabel.Link();
link.LinkData = textbox2.Text;
linkLabel1.Links.Add(link);

Loading Image into Picturebox from URL

I'm programming an algorithm in C# to download an image from a website and my software automatically fills all the required fields and presses the download button. The problem is that I'm not able to load the image. The dialog box to download image on Internet Explorer is appearing, so I need to get the url of the picture after clicking the button "generate" and load it into the picture box. My code:
private void simpleButton6_Click(object sender, EventArgs e)
{
string i = "0";
HtmlElement hu = webBrowser3.Document.GetElementById("data-text");
hu.Focus();
hu.SetAttribute("Value", txtEncodeData.Text);
HtmlElement hu1 = webBrowser3.Document.GetElementById("color");
hu1.Focus();
Color c = customColorBlender1.SelectedColor;
string hex = c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
hu1.SetAttribute("Value", hex);
HtmlElement hu2 = webBrowser3.Document.GetElementById("effect");
hu2.Focus();
if (comboBoxEdit1.SelectedIndex == 1)
{
i = "1";
}
hu2.SetAttribute("Value", i);
webBrowser3.Document.GetElementById("generate").InvokeMember("click");
t.Interval = 1000;
t.Start();
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
t.Stop();
String url = Convert.ToString(webBrowser3.Document.GetElementById("download").InvokeMember("click"));
MessageBox.Show(url);
pictureBox15.ImageLocation = Convert.ToString((Uri)webBrowser3.Document.GetElementById("download").InvokeMember("click"));
}

How to use WebBrowser in windows phone?

I'm using the following code to make my app to load a url,
WebBrowser wb = new WebBrowser();
wb.Navigate(new Uri(uri,UriKind.Absolute));
But still it is not loading that page? What could be the problem??
WebBrowser is a control. Like a button or a textblock, you won't see anything unless you put it somewhere in your page.
To launch an external browser, use WebBrowserTask:
var webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri(uri, UriKind.Absolute);
webBrowserTask.Show();
Yo can't have any callbacks with the default WebBrowserTask in wp, if you need more control, use the WebBrowser as you have been doing,
Xaml
<phone:WebBrowser IsScriptEnabled="True" LoadCompleted="UriContentLoaded" x:Name="browserControl" />
Code Behind
public MainPage() //Your page constructor
{
InitializeComponent();
this.browserControl.Loaded += SetBrowserUri;
}
private void SetBrowserUri(object sender, RoutedEventArgs e)
{
browserControl.Navigate(new Uri("http://www.bing.com"));
}
private void UriContentLoaded(object sender, NavigationEventArgs e)
{
if (MessageBox.Show("Do you want to load a second uri?", "Load again", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
browserControl.LoadCompleted -= this.UriContentLoaded; //Remove previous handler
browserControl.LoadCompleted += this.SecondUriContentLoaded; //Add new handler
browserControl.Navigate(new Uri("http://www.google.com"));
}
}
private void SecondUriContentLoaded(object sender, NavigationEventArgs e)
{
MessageBox.Show("Finished loading");
}

web browser cannot work with 1 click

I have a situation which occurs in WebBrowser with C#.
I am trying to do downloader through a site However , when i click first time, it doesn't work but if I click second times it works.
How can i solve this problem .
Sincerely.
Codes :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementById("youtube-url").SetAttribute("value", textBox1.Text);
webBrowser1.Document.GetElementById("submit").InvokeMember("click");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
label3.Text = "Video Alındı , indirme işleminin hazır olması bekleniyor";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("a");
String link = "";
foreach (HtmlElement el in col)
{
if (el.InnerText == "Download")
{
link = el.GetAttribute("href");
Download(link);
label3.Text = "Video indiriliyor";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("http://www.youtube-mp3.org/tr");
}
void Download(String link)
{
WebClient downloader = new WebClient();
downloader.DownloadFileAsync(new Uri(link),#"D:\a.mp3");
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = "Video İndiriliyor : " + progressBar1.Value + "%";
if (progressBar1.Value == 100)
label3.Text = "Video İndirildi";
}
You're blocking yourself from investigating what the problem is. It's never a good idea to disable script errors for WebBrowser control (as you do with ScriptErrorsSuppressed = true), unless you handle them internally in your host app. Do the following:
enable script errors (ScriptErrorsSuppressed = false);
enable script debugging for all applications;
implement WebBrowser Feature Control (FEATURE_BROWSER_EMULATION), so the web page is getting the same (or close) experience and HTML features as with full-featured IE browser.
Then, hopefully, you can find out what's going wrong when you're simulating a button click, and debug it.

Categories