Display IE window using WebBrowser - c#

I am working on a program that loads a webpage and calculates the load time. I want to give my program a URL and have it open an IE window at that page.
At first I was using Process.Start() to open the IE window, which works, but doesn't give me access to the WebBrowser.DocumentCompleted function. I am trying to create the IE window using a WebBrowser instance but I can't get the IE window to display.
using System;
using System.Windows.Forms;
namespace WebBrowserTest
{
public partial class Form1 : Form
{
WebBrowser IETestBrowser;
public Form1()
{
InitializeComponent();
IETestBrowser = new WebBrowser();
IETestBrowser.AllowNavigation = true;
IETestBrowser.Visible = true;
IETestBrowser.DocumentCompleted += ietb_DocumentCompleted;
}
private void LoadPageBtn_Click(object sender, EventArgs e)
{
IETestBrowser.Navigate("http://www.google.com");
IETestBrowser.Show();
TextDescriptionLbl.Text = "Loading Page...";
}
private void ietb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
TextDescriptionLbl.Text = "Done!";
}
}
}
This code works, and the DocumentCompleted event is triggered properly. I want the webpage to be visibly displayed in an IE window. How do I get the WebBrowser to draw on screen?

public Form1()
{
InitializeComponent();
IETestBrowser = new WebBrowser();
IETestBrowser.AllowNavigation = true;
IETestBrowser.Visible = true;
IETestBrowser.DocumentCompleted += ietb_DocumentCompleted;
//Add the WebBrowser Control to the form
IETestBrowser.Left = 100;
IETestBrowser.Top = 100;
this.Controls.Add(IETestBrowser);
}

Related

NET webbrowser - get HTML element ID by clicking on image

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">
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.
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"));
}
}
On simple way would be to use browser navigation. When clicking you can navigate to a special URL, then you handle the Navigating event and if the url is the special url you cancel the navigation and handle the data.
public MainWindow()
{
InitializeComponent();
br.NavigateToString(#"<img src=""F:\Temp\file12948.jpg"" id=""12948"" width=""180px"" >");
br.Navigating += this.Br_Navigating;
}
private void Br_Navigating(object sender, NavigatingCancelEventArgs e)
{
if(e.Uri.Host == "messages")
{
MessageBox.Show(e.Uri.Query);
e.Cancel = true;
}
}
This works if you have some control over the HTML. You could also set the URL from JS if you don't want to add the anchor.
Edit
The above version is for a WPF application. The winforms version is as follows:
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = #"<img src=""F:\Temp\file12948.jpg"" id=""12948"" width=""180px"" >";
webBrowser1.Navigating += this.webBrowser1_Navigating;
}
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.Host == "messages")
{
MessageBox.Show(e.Url.Query);
e.Cancel = true;
}
}

How do I get WebBrowsers url from the main Window C# WPF

i have no idea how to get the Url from the WebBrowser that gets created with c# code and does not exist in the Xaml before the code is execeuted.. The AddTabItem() function is called at the start at the program and later on if user wants to add more TabItems user can click on the add button.
public List<TabItem> tabItem;
public MainWindow()
{
try {
InitializeComponent();
//nardimo array za TabItem
tabItem = new List<TabItem>();
//Dodamo zaznamek (tabItem)
TabItem novTab = this.AddTabItem();
//bajndam tab
tabControl.DataContext = tabItem;
tabControl.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public TabItem AddTabItem()
{
int count = tabItem.Count;
TabItem tab = new TabItem();
tab.Header = string.Format("Zavihek {0}", count+1);
tab.Name = string.Format("zavihek{0}", count);
WebBrowser wb = new WebBrowser();
wb.Name = string.Format("Brskalnik{0}", count);
string a = "http://www.google.com";
wb.Navigate(a);
Url.Text = a;
tab.Content = wb;
tabItem.Insert(count, tab);
return tab;
}
Then user can search on the Web and wanted to make a bookmark.. so how do I get the Url from the site when he clicks on the add bookmark button? How do I access the WebBrowser since it is not located in the Xaml code? Keep in mind I have to add bookmarks from the second window and not the main one. I am really sorry for my bad English and would be really happy if someone could help <3 Thank you guys
What you want is:
wb.Source.AbsoluteUri
If you drop a WebBrowser on your window and call it "wb", and a Button then you can do this in the code behind:
using System.Diagnostics;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
wb.Navigate("http://google.com");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine(wb.Source.AbsoluteUri);
}
}
}
You could use the references that you add to the List<TabItem>:
WebBrowser wb = tabItem[tabItem.Count - 1].Content as WebBrowser;
string url = wb.Source.AbsoluteUri.ToString();

c# webbrowser navigate loop freezing form

I'm trying to display a website in a form and automatically reload the website to see if a certain text is present. I'm doing this in a C# form and try to call a while with an button. This is the code I made:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnStartLoop_Click(object sender, EventArgs e)
{
lblStatusLoop.Text = "Status loop: Started";
lblStatusLoop.ForeColor = System.Drawing.Color.Green;
int i = 0;
while (i < 10)
{
Browser.Navigate("www.google.com");
Browser.DocumentCompleted += Browser_DocumentCompleted;
Thread.Sleep(5000);
i++;
}
}
void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string ZoekText = txtSearchbox.Text.ToString();
if (Browser.DocumentText.Contains(ZoekText))
{
lblSearchResult.Text = "Text found";
}
else
{
lblSearchResult.Text = "Text not found";
}
}
}
As soon as I push the button the appliction freezes and I have to force quit it. I've done some research on google and suggestions were to wait for the document to complete loading but it has no effect.
I don't have much programming experience and do not have someone to fall back on so I hope someone here can point me into right direction.

C# opening a Form out of a TrayIcon

i just used this snippet for creating a tray application with two buttons (settings and exit):
using System;
using System.Windows.Forms;
using System.Drawing;
using WindowsFormsApplication1;
//*****************************************************************************
abstract class NotIco
{
private static NotifyIcon notico;
//==========================================================================
public static void Main(string[] astrArg)
{
ContextMenu cm;
MenuItem miCurr;
cm = new ContextMenu();
miCurr = new MenuItem();
miCurr.Index = 0;
miCurr.Text = "&Settings";
miCurr.Click += new System.EventHandler(SettingsClick);
cm.MenuItems.Add(miCurr);
miCurr = new MenuItem();
miCurr.Index = 1;
miCurr.Text = "Beenden";
miCurr.Click += new System.EventHandler(ExitClick);
cm.MenuItems.Add(miCurr);
notico = new NotifyIcon();
notico.Icon = new Icon("tanss.ico");
notico.Text = "TANSS Busylight Connector";
notico.Visible = true;
notico.ContextMenu = cm;
notico.DoubleClick += new EventHandler(NotifyIconDoubleClick);
Application.Run();
}
//==========================================================================
protected static void ExitClick(Object sender, EventArgs e)
{
notico.Dispose();
Application.Exit();
}
//==========================================================================
protected static void SettingsClick(Object sender, EventArgs e)
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
// This should open the "Settings"-Popup, containing 3 textboxes and a button to save them to xml.
}
//==========================================================================
protected static void NotifyIconDoubleClick(Object sender, EventArgs e)
{
// ...
}
}
Now i want to open a new Form as a Popup containing 3 textboxes to write some values in and a button to save them.
In the background, a never ending loop is requesting a url and parsing a value out of a json.
could you help me opening the new form (its not made yet, i just need it to open first :/)
and where do i embedd my background loop-code?
thanks so much!
It is as simple as
MyForm form1 = new MyForm();
form1.Show();
You have to create a new form object and show it on screen.
and, if you want to, you can set all others properties
form1.Location = new Point(20, 20);
form1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
form1.MaximizeBox = true;
form1.ControlBox = true;
......
I think is better (easier actually) to create the form from the designer and avoid the creation of every textbox and everything from code.

Form submit issue when invoking click?

I'm trying to make a small program that loads a webpage into the form submits the form on the
page automaticlly - this is apart of a larger project but i cant get this part work properly.
This web page offer Court cases results when the correct case number and date (mm-yy) is typed in and submitted.
I created a simple webBrowser in a form and called it webBrowser1.
And here is my Form.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
// secondStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
HtmlElement caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
HtmlElement caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(0)");
HtmlElement inputTag = webBrowser1.Document.All["Header1_CaseLocatorHeaderUC2_SearchHeaderCaseButton"];
inputTag.InvokeMember("Click");
}
}
}
As you can see - I'm typing the values as shown in the picture and then invoking a click on the button that submits this form, but it doesn't work!? this webpage is very tricky and uses scripts that validate the input and then sets the correct values to be submits and by the way he works only on IE < 10....
any idea please?
EDIT:
Its working now - I am firing the invoke twice but I don't have an idea what was the problem.
Now the new problem is that I added a button click that fires the process btnGet_Click and when triggering this function I get an error - it seems that DetailsTag is set to null... but when I un-comment the function in the public Form1() its working fine and loading the website as it should.
What is the difference between calling the the function firstStep() in the button click / public form?
why I receive this error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private readonly object lock_ = new object();
HtmlElement caseNumber;
HtmlElement caseDate;
HtmlElement DetailsTag;
int checks = 1;
public Form1()
{
InitializeComponent();
//webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
//firstStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (checks < 1)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetDetails);
}
caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
if (caseNumber != null && caseDate != null)
{
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(6)");
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(3)");
checks = 0;
System.Windows.Forms.SendKeys.Send("{ENTER}");
}
else
{
MessageBox.Show("No such case - enter a new one");
}
}
private void GetDetails(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetDetails);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetResults);
DetailsTag = webBrowser1.Document.All["_ctl0_caseDetailsGrid_row1_ct6_Imagebutton1"];
if (DetailsTag != null)
{
DetailsTag.InvokeMember("Click");
}
else
{
MessageBox.Show("Error - try another case!");
}
}
private void GetResults(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetResults);
HtmlElement DetailsStatus = webBrowser1.Document.All["_ctl7_caseStatusIDlbl"];
HtmlElement DetailsCourt = webBrowser1.Document.All["_ctl7_courtIDlbl"];
HtmlElement DetailsType = webBrowser1.Document.All["_ctl7_caseTypeIDlbl"];
HtmlElement DetailsAmount = webBrowser1.Document.All["_ctl7_claimAmountlbl"];
HtmlElement DetailsPrev = webBrowser1.Document.All["_ctl7_privilegeIDlbl"];
txtAmount.Text = DetailsAmount.InnerText;
txtCount.Text = DetailsCourt.InnerText;
txtPrev.Text = DetailsPrev.InnerText;
txtStatus.Text = DetailsStatus.InnerText;
txtType.Text = DetailsType.InnerText;
}
public void btnGet_Click(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
}
}
}
As said via comment, your approach for populating the textboxes is not too orthodox and, actually, is not working on my computer. The usual proceeding is relying on the SetAttribute function. Your code would become:
caseNumber.SetAttribute("value", "12283");
caseDate.SetAttribute("value", "03-10");
If I do that and then I use your inputTag.InvokeMember("Click"), the form is submitted (at least, no popup appears and the browser is redirected to a new page).

Categories