WebBrowser Control LoadCompleted - c#

I'm using Web browser in my form which navigates to multiple pages. I want to take screenshot of Last page once loaded completely. I've coded taking screen shot inside the webBrowser1_DocumentCompleted. However it is taking screenshot before page getting loaded. I'm confused where I can take screenshot. I found LoadCompleted event in google but not sure how to use. Please help me out.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace CC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string url = "http://www.lll.com";
webBrowser1.Navigate(new Uri(url));
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
catch (Exception ex)
{
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string AbsoluteURL = e.Url.AbsolutePath.ToString();
int count = 0;
switch (AbsoluteURL)
{
case "Page1":
var loginControl = webBrowser1.Document.GetElementById("user");
var passwordControl = webBrowser1.Document.GetElementById("password");
var btn = webBrowser1.Document.GetElementById("Submit");
if (loginControl != null)
loginControl.SetAttribute("value", "XXX");
if (passwordControl != null)
passwordControl.SetAttribute("value", "YYY");
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("tabindex") == "3")
{
elem.InvokeMember("click");
}
}
break;
case"Page2": // THIS IS NOT WORKING. TAKING SCREEN SHOT BEFORE PAGE GETTING LOADED FULLY. NEED HELP HERE
using (Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height, PixelFormat.Format24bppRgb))
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
PointToScreen(webBrowser1.Location),
new Point(0, 0),
webBrowser1.Size);
bitmap.Save(#"C:\123.bmp");
}
break;
default:
Console.WriteLine("Better try again");
break;
}
}
}
}
}

Try this one.
protected void Capture(object sender, EventArgs e)
{
string url = "www.google.com";
Thread thread = new Thread(delegate()
{
using (WebBrowser browser = new WebBrowser())
{
browser.ScrollBarsEnabled = false;
browser.AllowNavigation = true;
browser.Navigate(url);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
//do what do you want
}

In my experience, navigation and document loading are distinct from having the document be actually rendered. I would look at ReadyState https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserreadystate%28v=vs.110%29.aspx to determine of the document is actually rendered and not just loaded.

Related

Picture box not displaying Emgu.cv.mat.toBitmap image

Was following a tutorial on YouTube and tried to get my program to display the live video feed from my webcam into the forms picture box but for some reason the webcam comes on but the picture box isn't displaying anything
I have tried checking if the Mat class was returning null.
but it isn't this is my 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.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.UI;
namespace FaceRecognitionAttandanceSystem
{
public partial class StudentAdd : Form
{
public string fileName { get; set; }
VideoCapture capture;
public StudentAdd()
{
InitializeComponent();
}
//Open Folder
private void metroButton3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false };
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open file explorer
fileName = openFileDialog.FileName;
//pick image from file
Image img = Image.FromFile(fileName);
//Rotates Image by 90degrees
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox2.Image = img;
}
}
}
//Capture Image
private void metroButton4_Click(object sender, EventArgs e)
{
//If capture is empty start new video capture
if(capture == null)
{
capture = new Emgu.CV.VideoCapture(0);
}
capture.ImageGrabbed += Capture_ImageGrabbed;
capture.Start();
}
private void Capture_ImageGrabbed(object sender, EventArgs e)
{
try
{
Mat mat = new Mat();
if(mat == null)
{
Console.WriteLine("Here you Go");
}
capture.Retrieve(mat);
pictureBox1.Image = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
}
catch(Exception)
{
}
}
private void metroButton5_Click(object sender, EventArgs e)
{
}
}
}
The problem is very likely that the Capture_ImageGrabbed event is raised on a background thread. And you can only update the UI on the UI thread. You can place a break point in the event-handler and check the thread-debug window to confirm. To fix this you need to move execution to the UI thread. Try:
capture.Retrieve(mat);
var bitmap = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
pictureBox1.Invoke(() => pictureBox1.Image = bitmap );
You might need to write Invoke((Action)(() => pictureBox1.Image = bitmap) ), since I think there is some issues with the overload resolution of lambdas with the invoke-method.

How to display a popup on mouse hover of an HTML element in the WebBrowser control of a Form application

In the following code, C# and js are linked together and ToolStripDropDown is used to create a popup, but the mouseleave event of js does not fire when the mouse leaves the HTML element.
However, when I move the mouse over the popup, the mouseleave event fires.
If you move the mouse away from other directions, the mouseleave event will not fire.
Also, it seems to fire when the popup is not shown on the C# side.
I tried writing a code to focus on the WebBrowser control after Show, but even so, mouseleave of js doesn't fire.
I wonder why this is.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public ToolStripDropDown toolStripDropDown;
public Form1()
{
InitializeComponent();
toolStripDropDown = new ToolStripDropDown();
toolStripDropDown.Margin = Padding.Empty;
toolStripDropDown.Padding = Padding.Empty;
toolStripDropDown.DropShadowEnabled = false;
webBrowser1.ObjectForScripting = new TestClasss(this);
webBrowser1.DocumentText = #"<script>
window.onload = function() {
var elm = document.createElement('div');
elm.innerHTML = 'test';
document.body.appendChild(elm);
elm.onmouseover = function() {
window.external.ShowPopup(this.getBoundingClientRect().left, this.getBoundingClientRect().top);
};
elm.onmouseleave = function()
{
window.external.ClosePopup();
};
};
</script>";
}
}
[ComVisible(true)]
public class TestClasss
{
private Form1 viewer;
public TestClasss(Form1 viewer)
{
this.viewer = viewer;
}
public void ShowPopup(int x, int y)
{
var panel1 = new Panel();
panel1.BackColor = Color.Red;
var label1 = new Label();
label1.Text = "popup";
panel1.Controls.Add(label1);
var toolStripControlHost = new ToolStripControlHost(panel1);
toolStripControlHost.Margin = Padding.Empty;
toolStripControlHost.Padding = Padding.Empty;
viewer.toolStripDropDown.Items.Clear();
viewer.toolStripDropDown.Items.Add(toolStripControlHost);
viewer.toolStripDropDown.Show(viewer.webBrowser1, new Point(x, y), ToolStripDropDownDirection.AboveRight);
}
public void ClosePopup()
{
viewer.toolStripDropDown.Close();
}
}
}
Try this code
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Body.MouseOver += new HtmlElementEventHandler(Body_MouseOver);
}
void Body_MouseOver(object sender, HtmlElementEventArgs e)
{
if (e.ToElement != null && e.ToElement.TagName == "H1" && e.ToElement.GetAttribute("processed") != "true")
{
string[] words = e.ToElement.InnerHtml.Split(' ');
e.ToElement.InnerHtml = "";
for (int i = 0; i < words.Length; i++)
e.ToElement.InnerHtml += "<span> " + words[i] + " </span>";
foreach (HtmlElement el in e.ToElement.GetElementsByTagName("span"))
el.MouseOver += new HtmlElementEventHandler(e_MouseOver);
e.ToElement.SetAttribute("processed", "true");
}
}
void e_MouseOver(object sender, HtmlElementEventArgs e)
{
toolStripTextBox1.Text = e.ToElement.InnerText;
}
}

The process cannot access the file because it is being used by another process

The code that I got was from naudio record sound from microphone then save and many thanks to Corey
This is the error message that I get when I run the code for the second or subsequent times.
The first time it runs, it runs with no issues what so ever.
If I change the file name it works perfectly.
Unable to copy file "obj\Debug\Basque.exe" to "bin\Debug\Basque.exe". The process cannot access the file 'bin\Debug\Basque.exe' because it is being used by another process. Basque
Could someone gave me some guidance to where I'm making my 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.Tasks;
using System.Windows.Forms;
using NAudio.Wave;
namespace Basque
{
public partial class FlashCard : Form
{
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public FlashCard()
{
InitializeComponent();
StopBtn.Enabled = false;
StartBtn.Enabled = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
StartBtn.Enabled = false;
StopBtn.Enabled = true;
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(#"C:\Temp\bas0001.wav", waveSource.WaveFormat);
waveSource.StartRecording();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBtn.Enabled = false;
waveSource.StopRecording();
}
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
StartBtn.Enabled = true;
}
private void PlayBtn_Click(object sender, EventArgs e)
{
}
private void ExitBtn_Click(object sender, EventArgs e)
{
}
}
}
It might help to put a Formclosing method with Application.Exit(); in it. If it only works on the first try, it might be because the application isn't fully closing.
You can check if this will fix it when you check task manager. Just make sure that your application isn't still there. Even if it isn't still there, the Application.Exit(); might help.

ObjectListView show icons

Trying to put icons in ObjectListview, here's my piece of code where icon should have been put:
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
imageList1 already have an image, this code should have put an icon next to "Delete", but it did not appear at all, looked through cookbooks and Google and I still have no idea. Can anyone help me?
this is the full form code in case needed:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
objectListView1.AllowDrop = true;
objectListView1.DragEnter += new DragEventHandler(objectListView1_DragEnter);
objectListView1.DragDrop += new DragEventHandler(objectListView1_DragDrop);
objectListView1.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick;
objectListView1.CellEditStarting += deleteItems;
objectListView1.SmallImageList = imageList1;
deleteColumn.IsEditable = true;
deleteColumn.ImageGetter = delegate
{
return 0;
};
deleteColumn.AspectGetter = delegate
{
return "Delete";
};
}
private void objectListView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void objectListView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] droppedFiles = (string[]) e.Data.GetData(DataFormats.FileDrop);
foreach (string path in droppedFiles)
{
if (File.Exists(path))
{
FileObject fo = new FileObject(path, "added later");
objectListView1.AddObject(fo);
}
}
}
}
private void deleteItems(object sender, BrightIdeasSoftware.CellEditEventArgs e)
{
if(e.Column == deleteColumn)
{
e.Cancel = true;
objectListView1.RemoveObject(e.RowObject);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
In order for images to appear next to the text in a column, you must:
Connect the ObjectListView to an ImageList (using the SmallImageList property);
Install an ImageGetter delegate for the column that must show the images;
Make sure that there are actually images in the ImageList.
With this done, images will appear (I just tested this).
There is one catch, though. From your question, I suspect that the "Delete" column may not be the first column in the ObjectListView. The above steps only allow you to show an image in the very first column. For subsequent columns, you will have to set the ShowImagesOnSubItems property to True. Could that be it?

Working with C# Proxy List

I'm trying to build an application that goes to a certain website (from a textbox) x number of times (also from a textbox) through a proxy. What I'm having trouble with is getting the proxy list into the program and using it in the webBrowser control. Here's what I have so far. Any help is appreciated. Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net;
namespace LetsBot
{
public partial class TrafficBot : Form
{
public TrafficBot()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtURL.Clear();
this.txtProxy.Clear();
this.txtURL.Focus();
}
private void btnStart_Click(object sender, EventArgs e)
{
this.lblBrowsing.Show();
this.btnStart.Enabled = false;
int n = Convert.ToInt32(this.txtNumVisits.Text);
for (int i = 0; i < n; i++)
{
string url = this.txtURL.Text;
this.webBotBrowser.Navigate(url);
while (webBotBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
string PageText = this.webBotBrowser.DocumentText.ToString();
Thread.Sleep(5000);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
this.btnStart.Enabled = true;
this.webBotBrowser.Stop();
this.txtURL.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Exit Traffic Bot?", "Don't Let Me Go!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
else if (dialogResult == DialogResult.No)
{
}
}
private void webBotBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
if (e.CurrentProgress > 0)
{
ProgressBar.Value = (int)(e.CurrentProgress / e.MaximumProgress * 100);
}
}
private List<string> getProxyListFromText(string input)
{
List<string> list = new List<string>();
StreamReader reader = new StreamReader(input);
string item = "";
while (item != null)
{
item = reader.ReadLine();
if (item != null)
{
list.Add(item);
}
}
reader.Close();
return list;
for (int i = 0; i < listBox1.Items.Count; i++)
{
object url;
WebClient wc;
url = this.txtURL.Text;
wc = new WebClient();
//This should come from the proxy list
foreach (string prox in getProxyListFromText("Proxies.txt"))
{
wc.Proxy = new WebProxy(prox);
var page = wc.DownloadString(url.ToString());
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
var pplname = doc.DocumentNode.SelectNodes("/html/body/div[3]/div/div[2]/div[2]/div/div[4]/p");
}
}
}
}
}

Categories

Resources