How to use multiple WebBrowser DocumentCompleted - c#

I would like to be able to open a web page, log in, and be able to do things on the next page. DoPlans will not execute. Here is my code so far... (I do know that I have t for a lot of the variables)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("t");
}
private void DoPlans(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
textBox1.AppendText("started");
webBrowser1.Document.GetElementById("t").InvokeMember("Click");
webBrowser1.Document.GetElementById("t").InvokeMember("Click");
foreach (HtmlElement elem in webBrowser1.Document.GetElementsByTagName("input"))
{
if (elem.GetAttribute("value") == "Submit Weekend Plans")
{
elem.InvokeMember("Click");
}
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.GetElementById("username").SetAttribute("value", "t");
webBrowser1.Document.GetElementById("password").SetAttribute("value", "t");
foreach (HtmlElement elem in webBrowser1.Document.GetElementsByTagName("input"))
{
if (elem.GetAttribute("value") == "Login")
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DoPlans);
elem.InvokeMember("Click");
}
}
}
}

Try something like this:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
switch (e.Url.ToString())
{
case "home page":
{
// fire click
break;
}
case "next page":
{
// handle logged in user
break;
}
}
}

Related

How to pass multiple button click event from child to parent in c#

I have 18 buttons on the child form "Control Test" which send event to the parent form
Out of 18 buttons, 14 are ON and OFF functionality, making 7 pairs as in the picture
The problem is raising the event for each button, it causes very long and messy code, both in the child and the parent form,
Is there any less complex way to do it? like I have done with the menu.
Child Form:
Child Form:
// B Plus Relay On Button
public event EventHandler BPRElayOnBtnClicked;
protected virtual void WhenBPRelayOnBtnClicked(EventArgs e)
{
BPRElayOnBtnClicked.Invoke(this, e);
}
private void BPRelayOn_btn_Click(object sender, EventArgs e)
{
WhenBPRelayOnBtnClicked(e);
}
// B Plus Relay OFF Button
public event EventHandler BPRElayOffBtnClicked;
protected virtual void WhenBPRelayOffBtnClicked(EventArgs e)
{
BPRElayOnBtnClicked.Invoke(this, e);
}
private void BPRelayOff_btn_Click(object sender, EventArgs e)
{
WhenBPRelayOffBtnClicked(e);
}
// B Minus Relay ON Button
public event EventHandler BMRElayOnBtnClicked;
protected virtual void WhenBMRelayOnBtnClicked(EventArgs e)
{
BMRElayOnBtnClicked.Invoke(this, e);
}
private void BMRelayOn_btn_Click(object sender, EventArgs e)
{
WhenBMRelayOnBtnClicked(e);
}
// B Minus Relay OFF Button
public event EventHandler BMRElayOffBtnClicked;
protected virtual void WhenBMRelayOffBtnClicked(EventArgs e)
{
BMRElayOffBtnClicked.Invoke(this, e);
}
private void BMRelayOff_btn_Click(object sender, EventArgs e)
{
WhenBMRelayOffBtnClicked(e);
}
...... //event for each button
Parent Form:
private void viewToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
switch (menu.Name)
{
case "controlTestToolStripMenuItem":
if (Application.OpenForms["CtrlTest"] is CtrlTest ctrlTest)
{
ctrlTest.Focus();
return;
}
ctrlTest = new CtrlTest();
ctrlTest.BPRElayOnBtnClicked += CtrlTest_BPRElayOnBtnClicked;
ctrlTest.BPRElayOffBtnClicked += CtrlTest_BPRElayOffBtnClicked;
ctrlTest.BMRElayOnBtnClicked += CtrlTest_BMRElayOnBtnClicked;
ctrlTest.BMRElayOffBtnClicked += CtrlTest_BMRElayOffBtnClicked;
ctrlTest.PreRElayOnBtnClicked += CtrlTest_PreRElayOnBtnClicked;
ctrlTest.PreRElayOffBtnClicked += CtrlTest_PreRElayOffBtnClicked;
ctrlTest.MdiParent = this;
ctrlTest.Show();
break;
.........//Other menus ...
default:
break;
private void CtrlTest_BPRElayOnBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BPRElayOffBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BMRElayOnBtnClicked(object sender, EventArgs e)
{
//Do something here
}
private void CtrlTest_BMRElayOffBtnClicked(object sender, EventArgs e)
{
//Do something here
}
For the on/off, take a look at the following control. For the others setup one event and work out logic similar to the on/off buttons.
Download the source, add the class project to your Visual Studio solution. Open the class project and change the .NET Framework currently set to 4, to your project's .NET Framework version.
Setup an enum where for each on/off button set it's tag to one of the members. this ways things are clearer using a switch and enums.
public enum OperationType
{
BPlusRelay,
BMinusRelay,
PreRelay,
CycleCount,
PairDown,
TestMode,
StandbyMode
}
In the child form, setup and event and set tags for each on/off control. Change the names to reflect their purpose, I simply added them quickly for demoing purposes.
public partial class ChildForm : Form
{
public delegate void OnClicked(OperationType operationType, bool state);
public event OnClicked ClickedEvent;
public ChildForm()
{
InitializeComponent();
SetProperties();
}
public void SetProperties()
{
ToggleSwitch1.Tag = OperationType.BPlusRelay;
ToggleSwitch2.Tag = OperationType.BMinusRelay;
ToggleSwitch3.Tag = OperationType.PreRelay;
ToggleSwitch4.Tag = OperationType.CycleCount;
ToggleSwitch5.Tag = OperationType.PairDown;
ToggleSwitch6.Tag = OperationType.TestMode;
ToggleSwitch7.Tag = OperationType.StandbyMode;
var list = Controls.OfType<JCS.ToggleSwitch>().ToList();
foreach (var toggleSwitch in list)
{
toggleSwitch.CheckedChanged += ToggleSwitchOnCheckedChanged;
}
}
private void ToggleSwitchOnCheckedChanged(object sender, EventArgs e)
{
var current = (JCS.ToggleSwitch)sender;
ClickedEvent?.Invoke((OperationType)current.Tag, current.Checked);
}
}
In the main form, show the child form, subscribe to the event above.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void ShowChildFormButton_Click(object sender, EventArgs e)
{
var childForm = new ChildForm();
childForm.ClickedEvent += ClickedEvent;
try
{
childForm.ShowDialog();
}
finally
{
childForm.Dispose();
}
}
private void ClickedEvent(OperationType operationType, bool state)
{
switch (operationType)
{
case OperationType.BPlusRelay:
// TODO
break;
case OperationType.BMinusRelay:
// TODO
break;
case OperationType.PreRelay:
// TODO
break;
case OperationType.CycleCount:
// TODO
break;
case OperationType.PairDown:
// TODO
break;
case OperationType.TestMode:
// TODO
break;
case OperationType.StandbyMode:
// TODO
break;
}
}
}
Partly done form, and note you can change the size of the buttons.

Raising event when the checkbox of a webbrowser is checked in C#

I want to raise an event when the checkbox is checked in a web browser.
Here is what I have come up with:
public class HTMLCheckBoxArgs : EventArgs
{
public Guid ElementGuid;
}
public delegate void CheckBoxChangeEventHandler(object sender, HTMLCheckBoxArgs e);
public event CheckBoxChangeEventHandler CheckPressed;
void OnCheckPressed(HTMLCheckBoxArgs args)
{
if (CheckPressed != null)
CheckPressed(this, args);
}
protected void CheckBoxEvents()
{
HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement el in elements)
{
HTMLCheckBoxArgs checkbargs = new HTMLCheckBoxArgs();
if (el.GetAttribute("type") == "checkbox")
{
checkbargs.ElementGuid = Guid.Parse(el.Id);
el.AttachEventHandler("onclick", (sender, args) => OnCheckBoxClicked(el, checkbargs));
}
}
}
public void OnCheckBoxClicked(object sender, EventArgs args)
{
OnCheckPressed((HTMLCheckBoxArgs)args);
}
The problem that I have is the fact that this way I raise the event when the check box is clicked.
I want the event to be raised when the check box is checked.
Try this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<html><body><input type=\"checkbox\" id=\"chk\" value=\"some\">some thing</body></html>";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
foreach (HtmlElement el in webBrowser1.Document.All)
{
if (el.GetAttribute("type") == "checkbox")
{
el.AttachEventHandler("onclick", (send, args) => OnElementClicked(el, EventArgs.Empty));
}
}
}
private object OnElementClicked(HtmlElement el, EventArgs eventArgs)
{
if (el.GetAttribute("checked") == "True")
{
MessageBox.Show("checked");
}
return false;
}
}

User control and how to get button events from form

i created user control which looks like this:
and code behind looks like:
using System;
using System.Windows.Forms;
namespace Controlls
{
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
private void pbNaprej_Click(object sender, EventArgs e)
{
}
private void pbNazaj_Click(object sender, EventArgs e)
{
}
private void pbNovo_Click(object sender, EventArgs e)
{
}
private void bpbBrisi_Click(object sender, EventArgs e)
{
}
private void pbPotrdi_Click(object sender, EventArgs e)
{
}
private void txtOd_TextChanged(object sender, EventArgs e)
{
}
}
}
now i move this UC to form but there is a problem. How to get this events from UC. I need to implement click events for buttons in form where i use this user control. What i can see is that i can use it like one component and i can not get separate buttons from it.
Add 2 event handlers for yor control, and subscribe to the toobox event at the place you use it:
using System;
using System.Windows.Forms;
namespace Controlls
{
public enum ToolboxButtonType { Potrdi, Brisi, Novo, Nazaj, Naprej }
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
private void pbNaprej_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Novo);
}
private void bpbBrisi_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Brisi);
}
private void pbPotrdi_Click(object sender, EventArgs e)
{
OnToolboxClick(ToolboxButtonType.Potrdi);
}
private void txtOd_TextChanged(object sender, EventArgs e)
{
OnTextChanged(txtOd.Text);
}
}
private OnToolboxClick(ToolboxButtonType button)
{
if (ToolboxClick != null)
{
ToolboxClick(this, new ToolboxClickEventArgs(button));
}
}
private OnTextChanged(string text)
{
if (ToolboxTextChanged!= null)
{
ToolboxTextChanged(this, new ToolboxTextChangedEventArgs(text));
}
}
public class ToolboxTextChangedEventArgs: EventArgs
{
public string Text { get; private set; }
public ToolboxClickEventArgs(string text) { Text = text; }
}
public class ToolboxClickEventArgs : EventArgs
{
public ToolboxButtonType Button { get; private set; }
public ToolboxClickEventArgs(ToolboxButtonType button) { Button = button; }
}
public event EventHandler<ToolboxClickEventArgs> ToolboxClick;
public event EventHandler<ToolboxTextChangedEventArgs> ToolboxTextChanged;
}
For example:
//Toolbar toolbar = new Toolbar();
toolbar.ToolboxTextChanged += (s, e) => { btn1.Text = e.Text; };
toolbar.ToolboxClick += (s, e) =>
{
swith(e.Button)
{
case ToolboxButtonType.Brisi: //
break;
default:
break;
}
};
You need to create event in MainForm class and generarate it in hand mode.
If you also draw your icons on canvas or smth, you need to handle onClick your MainForm, than calculate mouse click position, and generate event that you were create.
If it amount of buttons or smth that has their own onClick events, you can hang on this buttons event the action that will generate your even in main form.
Answer what approach you use, and I past some code.
ADDED:
public partial class Toolbar : UserControl
{
public Toolbar()
{
InitializeComponent();
}
public enum ToolBarCommands
{
Naprej, Nazaj, Novo
}
public Action<object, ToolBarCommands> MenuItemClick;
private void pbNaprej_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Novo);
}
}
How to use it? easy:
// Define section
var toolbar = new Toolbar();
toolbar.MenuItemClick += MenuItemClickHandler;
...
MenuItemClickHandler(object sender, Toolbar.ToolBarCommands item)
{
switch(item)
{
case Toolbar.ToolBarCommands.Naprej:
// Naperej handler
break;
case Toolbar.ToolBarCommands.Nazaj:
// Nazaj handler
break;
case Toolbar.ToolBarCommands.Novo:
// Novo handler
break;
}
}
ADDED:
If names of your buttons same as enum members you can cut this part of code:
private void pbNaprej_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Naprej);
}
private void pbNazaj_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Nazaj);
}
private void pbNovo_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
MenuItemClick(this, ToolBarCommands.Novo);
}
It will look's like one method (hang this method to all your menu element events)
private void pbItem_Click(object sender, EventArgs e)
{
if(MenuItemClick != null)
{
ToolBarCommands command;
var res = ToolBarCommands.TryParse(((Button)sender).Name, command)
if(res == true)
MenuItemClick(this, command);
}
}

Detect scroll on a WebBrowser control

I have the following code that, weirdly, works for a couple of seconds and then stops working (my event handler method stops being called):
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.Navigate("google.com");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!webBrowser1.IsBusy && webBrowser1.Url == e.Url && webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
HTMLWindowEvents_Event windowEvents = webBrowser1.Document.Window.DomWindow as HTMLWindowEvents_Event;
windowEvents.onscroll += new HTMLWindowEvents_onscrollEventHandler(windowEvents_onscroll);
}
}
private void windowEvents_onscroll()
{
HtmlDocument htmlDoc = webBrowser1.Document;
int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
string text = scrollTop.ToString();
}
}
OK Found a solution:
protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
{
Follow();
if (!IsBusy && Url == e.Url && ReadyState == WebBrowserReadyState.Complete)
{
Document.Window.AttachEventHandler("onscroll", DocScroll);
}
}
If attached that way it works OK (so far...). Don't even need to use mshtml.

How can I make the WebBrowser control navigate to a specific address?

How can I make the code when run the code it go to example.com
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
webBrowser1.Navigate("www.example.com");
}
Please correct it when run program it go to example.com
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
webBrowser1.Navigate("www.example.com");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
if (document != null)
{
IHTMLSelectionObject currentSelection = document.selection;
IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
if (range != null)
{
const String search = "ant";
if (range.findText(search, search.Length, 2))
{
range.select();
}
}
}
}
}
Can you Navigate to example.com at Form.Load event? It's working fine in my machine.
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("www.example.com");
}
You need to handle the Load event of your form (Form1) if you want the WebBrowser control to automatically navigate to www.example.com whenever your form is shown on the screen.
As it's written now, you handle the Navigated event of the WebBrowser control and tell it to navigate somewhere else. However, the Navigated event is only raised when the browser has navigated to and begun loading a new page. Even if you get your code to work, it will be perpetually chasing its own tail.
Instead, try the following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.example.com");
}
}
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("http://www.example.com");
}
This execute the navigate method after the app is initialized.
I'm not sure if I understand your question: The e variable in the webBrowser1_DocumentCompleted method contains the Url property that holds the current Uri object with the URL where the browser control has arrived:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = (WebBrowser)sender;
if (e.Url.Host.EndsWith("example.com"))
{
// do something
}
}

Categories

Resources