How to display the route using GMap in C#? - c#

My main problem is that it doesn't display the line between the 2 markers when I click on the display button.It should draw my route between the first pin and the second pin, but it doesn't show me anything at all. I've been trying for some time to figure out what's wrong.
This is the code. I also uploaded images, maybe it will help.
Can anyone help me with this? Thanks!
code
interface
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 GMap.NET.MapProviders;
using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
namespace Licenta
{
public partial class Map : Form
{
List<PointLatLng> _points;
public Map()
{
InitializeComponent();
_points = new List<PointLatLng>();
}
private void Map_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = "#AIzaSyBreQ8N4txQ74BwKwigtnmkSW8Vhisyles";
gMapControl1.ShowCenter = false;
}
private void btnAdauga_Click(object sender, EventArgs e)
{
_points.Add(new PointLatLng(Convert.ToDouble(txtLat.Text), Convert.ToDouble(txtLong.Text)));
}
private void btnSterge_Click(object sender, EventArgs e)
{
if (gMapControl1.Overlays.Count > 0)
{
gMapControl1.Overlays.RemoveAt(0);
gMapControl1.Refresh();
}
}
private void btnAfiseaza_Click(object sender, EventArgs e)
{
var route = GoogleMapProvider.Instance.GetRoute(_points[0], _points[1], false, false, 14);
var r = new GMapRoute(route.Points, "My Route")
{
Stroke = new Pen(Color.Red, 5)
};
var routes = new GMapOverlay("routes");
routes.Routes.Add(r);
gMapControl1.Overlays.Add(routes);
lblDist.Text = route.Distance + " km";
}
GMapOverlay markers = new GMapOverlay("markers");
private void btnIncarca_Click(object sender, EventArgs e)
{
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.MapProvider = GMapProviders.GoogleMap;
double lat = Convert.ToDouble(txtLat.Text);
double longt = Convert.ToDouble(txtLong.Text);
gMapControl1.Position = new PointLatLng(lat, longt);
gMapControl1.MinZoom = 2;
gMapControl1.MaxZoom = 100;
gMapControl1.Zoom = 7;
PointLatLng point = new PointLatLng(lat, longt);
GMapMarker marker = new GMarkerGoogle(point, GMarkerGoogleType.red_pushpin);
markers.Markers.Add(marker);
gMapControl1.Overlays.Add(markers);
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gMapControl1.SetPositionByKeywords("Timisoara, Romania");
}
private void button5_Click(object sender, EventArgs e)
{
_points.Clear();
}
}
}

Related

reading sensors data in a Drone GUI

I'm designing a GUI that receives voltage and current readings from a drone and displays it in text books.
I receive data in the form (H,0.00,0.00,)
I used the split function to read the values.
but when I start the program I get the error message
"system.indexOutOfRangeException:"index was outside the bound of the array"
I'm a beginner in C#. any suggestions on how to resolve the issue
...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 System.IO;
namespace G_Station
{
public partial class Form1 : Form
{
string ArduData = "";
string[] pot;
string current = "";
string voltage = "";
public Form1()
{
InitializeComponent();
}
private void ConnectBtn_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = PortCmb.Text;
serialPort1.BaudRate = Convert.ToInt32(BaudCmb.Text);
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Encoding = System.Text.Encoding.GetEncoding(28591);
serialPort1.DataBits = 8;
serialPort1.Open();
ConnectBtn.Enabled = false;
DisconnectBtn.Enabled = true;
timer1.Enabled = true;
}
catch (Exception errName)
{
MessageBox.Show(errName.ToString());
}
}
private void DisconnectBtn_Click(object sender, EventArgs e)
{
try
{
//serialPort1.PortName = PortCmb.Text;
//serialPort1.BaudRate = Convert.ToInt32(BaudCmb.Text);
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Encoding = System.Text.Encoding.GetEncoding(28591);
serialPort1.DataBits = 8;
serialPort1.Close();
ConnectBtn.Enabled = true;
DisconnectBtn.Enabled = false;
timer1.Enabled = false;
}
catch (Exception errName)
{
MessageBox.Show(errName.ToString());
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.BytesToRead < 3 )
{
ArduData = "H,00.0,00.0,";
}
else
{
ArduData = serialPort1.ReadLine();
}
pot = ArduData.Split(',');
current = pot[2];
voltage = pot[1];
VoltLbl.Text = current;
CurrentLbl.Text = voltage;
}
private void VoltLbl_Click(object sender, EventArgs e)
{
}
private void CurrentLbl_Click(object sender, EventArgs e)
{
}
}
}...

How to make a customized progressbar in c#

I would like to learn how to make a progressbar like the one shown in this video.
I tried to replicate it in VS C#, but I get the error:
C# Property or indexer cannot be assigned to -- it is read only
If I try using if (txProgressBar.Text.Length == 85), I will get this in the TextBox (txProgressBar)
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox, Text: Syst...██
Textbox Progressbar Tutorial VB 2010
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;
namespace CustomizedProgressBar
{
public partial class Form1 : Form
{
int last = 1;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (txProgressBar.Text.Length = "85")
{
timer1.Stop();
MessageBox.Show("Counted!");
}else
{
if (last == 1)
{
txProgressBar.Text = txProgressBar + "█";
last = 2;
}
else
{
txProgressBar.Text = txProgressBar.Text + "█";
last = 1;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txProgressBar.Text = "";
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
Your line:
txProgressBar.Text = txProgressBar + "█";
should be
txProgressBar.Text = txProgressBar.Text + "█"; or txProgressBar.Text &= "█";
I realized what was the problem. The txProgressBar.Text = txProgressBar + "█"; was missing the *.Text. That solved the problem and the message is shown as well.

Error 2 Cannot implicitly convert type 'int' to 'SmallStore.Product_Type'

This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SmallStore
{
public partial class AddProduct : Form
{
private db_Entities db = new db_Entities();
private Byte[] byteBLOBData;
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Description";
comboCatagory.ValueMember = "Product_Type";
comboCatagory.Invalidate();
}
private void AddProduct_Load(object sender, EventArgs e)
{
//check the data type cant cast to int dont know why
//MessageBox.Show(comboCatagory.SelectedValue.GetType().ToString());
}
private void btnUpload_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
MemoryStream memBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(memBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Product product = new Product();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
/*THIS IS THE PROBLEM*/
product.Product_Type = (int)comboCatagory.SelectedValue;
db.Products.Add(product);
db.SaveChanges();
}
}
}
i have been wracking my brain on this problem for 2 days now. i have a dbEntities model bound to a comboCatagory box in a Product SQL table. Product_type is of type int and description is a varchar(MAX). everything else is working. when i save "btnSave_Click" i get an invalid cast error. Can anyone please explain what i am doing wrong. i been using c# for a week i come from java and c/x86asm. im am very new to .net and entity framework. i know there are other ways to do this but i really like the EF. Thanks friends! also i did check other questions but they are not dealing with ef and data binding to combobox.
Here's the problem, you need "ProductType" not "Product_Type" in value member of the Combobox
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Description";
comboCatagory.ValueMember = "ProductType"; //Not Product_Type
comboCatagory.Invalidate();
}
This is the code that compiles i made a error in the first one
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SmallStore
{
public partial class AddProduct : Form
{
private db_Entities db = new db_Entities();
private Byte[] byteBLOBData;
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Product_Type";
comboCatagory.ValueMember = "Description";
comboCatagory.Invalidate();
}
private void AddProduct_Load(object sender, EventArgs e)
{
//check the data type cant cast to int dont know why
//MessageBox.Show(db.Product_Type.ToList().GetType().ToString());
}
private void btnUpload_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
MemoryStream memBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(memBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Product product = new Product();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
/*this is the line in question*/
product.ProductType = (int)(comboCatagory.SelectedValue);
db.Products.Add(product);
db.SaveChanges();
}
}
}

Record video with Accord.net (AForge)

I used Accord.net (AForge) for connect to the webcam and record video
But stored videos is slow motion ...
this my project :
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace CaptureWebcam
{
public partial class Form1 : Form
{
private VideoCaptureDeviceForm captureDevice;
private string path = Path.GetDirectoryName(Application.ExecutablePath) + #"\Videos\";
private FilterInfoCollection videoDevice;
private VideoCaptureDevice videoSource;
private VideoFileWriter FileWriter = new VideoFileWriter();
private Bitmap video;
bool isRecord = false;
public Form1()
{
InitializeComponent();
}
private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void btnStartCam_Click(object sender, EventArgs e)
{
videoDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
videoSource = captureDevice.VideoDevice;
videoSource = captureDevice.VideoDevice;
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
timer1.Enabled = true;
}
//videoSource.DisplayPropertyPage(IntPtr.Zero);
}
private Thread workerThread = null;
private bool stopProcess = false;
private void recordLiveCam()
{
if (!stopProcess)
{
while (isRecord)
{
FileWriter.WriteVideoFrame(video);
}
FileWriter.Close();
}
else
{
workerThread.Abort();
}
}
private void btnRecord_Click(object sender, EventArgs e)
{
//try
//{
isRecord = true;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(path + "recorded at " + DateTime.Now.ToString("HH-mm-ss") + ".mp4", w, h, 25, VideoCodec.MPEG4);
stopProcess = false;
workerThread = new Thread(new ThreadStart(recordLiveCam));
workerThread.Start();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStopRecord_Click(object sender, EventArgs e)
{
stopProcess = true;
isRecord = false;
FileWriter.Close();
workerThread.Abort();
video = null;
}
private void btnStopCam_Click(object sender, EventArgs e)
{
try
{
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource.Stop();
pictureBox1.Image = null;
pictureBox1.Invalidate();
if (FileWriter.IsOpen)
{
FileWriter.Close();
video = null;
}
}
else
return;
}
catch
{
videoSource.Stop();
FileWriter.Close();
video = null;
}
}
float fts = 0.0f;
private void timer1_Tick(object sender, EventArgs e)
{
fts = videoSource.FramesReceived;
label1.Text = "Frame Rate : " + fts.ToString("F2") + " fps";
}
}
}
And when click the btnStopRecord following error :
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
"Slow motion" can have multiple reasons. First you need to know if the actual framerate, at which the NewFrames get produces is so slow (how many HZ then?) or if the CPU is too busy. Or the graphics card maybe.
For everything DirectShow related I strongly suggest using GraphEdit and AMCap to see what the real capabilites of the device are. AForge was prone to oversampling and I would not wonder if it's similar in Accord.
Also, you can always rely on good old processexplorer to see if the load (if any) is caused by SYSTEM or INTERRUPRS or is actually produced by your executable.
Another thing that happened to me was PictureBox. VideoSourcePlayer is far better and I wound up doing my own blitting.
It is worth mentioning these three optimizations:
DO NOT USE Bitmap.GetPixel!
Use videoSource.DisplayPinPropertyPage(IntPtr.Zero)
Check the color space of the videostream
Bitmap.GetPixel
The problem with GetPixel is, that it's really slow as it has to unmanage/manage a lot for every single pixel. It is fine as along as you only get a small a mount of calls and use it on a loaded bitmap. It is definately the wrong approach if you want to use it on all pixelx every couple of milliseconds. The CPU load from this phenomenon is associated with your application and will show as such in process explorer.
In the end I wrote my own pixel routines starting here: Work with bitmap faster with Csharp
If you just want a kernel or something more usual than I needed, implement a
custom Filter.
VideoSource.DisplayPinPropertyPage
If you use the AForge-buit-in mechanism for choosing the resolution and initiating the video stream, you cannot set the Framerate (I do not consider this a bug in AForge). So AForge always chooses the highest framerate. If you circumvent videoSource.VideoCapabilities and directly show the native device configuration dialog (it's formally called "Video Capture Pin Properties Dialog"). There you can set all the parameters manually and the dialog will fill in the appropriate framerate. This way, you will get the "real" (hardware) refresh rate in your callbacks. The CPU load of this oversampling happens in the SYSTEM process.
Color space conversion
In my case, the camera supports three output formats: YUY2, MJPG and RGB24. Depending on what format you use, the image is transformed by AForge into RGB (I think actually it's ARGB32). The rendered DirectShow graphs for all three formats are different and RGB obviously uses much less CPU than the others, as the color conversion is quite trivial. The load from this conversion also shows up in the SYSTEM process and not in your applications exe.
You can try to put some timers to understand which operation is slowing down the process.(Stopwatch class will be perfect)
I don't know the format of your Frame but usually the conversion to Bitmap is the bottle neck, AForge is quite fast. Furthermore you can pass a time stamp to WriteVideoFrame method, then the frame rate indicated in Open is just for replaying the video. Aforge will ordinate the frames in the right order with the right time.
That's according to my experience. Hope it can help.
Try this
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 AForge;
using AForge.Video.DirectShow;
using Accord.Video.FFMPEG;
using System.IO;
using AForge.Video;
using System.Threading;
namespace New_Project_2
{
public partial class Form1 : Form
{
private VideoCaptureDeviceForm captureDevice;
private FilterInfoCollection videoDevice;
private VideoCaptureDevice videoSource;
private VideoFileWriter FileWriter = new VideoFileWriter();
bool isRecord = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
if (isRecord == true)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
FileWriter.WriteVideoFrame((Bitmap)eventArgs.Frame.Clone());
}
}
catch (Exception)
{
throw;
}
}
private void button1_Click(object sender, EventArgs e)
{
videoDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
isRecord = true;
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open("d:\\" + "recorded at " + DateTime.Now.ToString("HH-mm-ss") + ".mp4", w, h, 25, VideoCodec.MPEG4);
videoSource = captureDevice.VideoDevice;
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
}
//videoSource.DisplayPropertyPage(IntPtr.Zero)
}
private void button2_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
isRecord = false;
FileWriter.Close();
}
private void button4_Click(object sender, EventArgs e)
{
}
}
}
You can use emguCV to record videos.
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;
using Emgu.CV;
using Emgu.CV.Structure;
namespace Load_Images
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
double TotalFrame;
double Fps;
int captureFrameNo;
VideoCapture capture;
VideoWriter writer;
bool isCapturing = false;
private void button1_Click(object sender, EventArgs e)
{
if (isCapturing == false)
{
capture = new VideoCapture(0);
TotalFrame = capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameCount);
Fps = capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps);
isCapturing = true;
int fourcc = fourcc = VideoWriter.Fourcc('H', '2', '6', '4');
capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth, 2048);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight, 1024);
//int fourcc = Convert.ToInt32(capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FourCC));
int width = Convert.ToInt32(capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth));
int height = Convert.ToInt32(capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight));
string destin_path = "D:\\out.mp4";
writer = new VideoWriter(destin_path, fourcc, Fps, new Size(width, height), true);
capture.ImageGrabbed += Capture_ImageGrabbed;
capture.Start();
}
}
private void Capture_ImageGrabbed(object sender, EventArgs e)
{
try
{
if (isCapturing == true)
{
if (capture == null)
{
return;
}
Mat m = new Mat();
capture.Retrieve(m);
writer.Write(m);
pictureBox1.Image = m.ToImage<Bgr, byte>().Bitmap;
}
}
catch (Exception)
{
throw;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (isCapturing == true) {
capture.Stop();
isCapturing = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (capture != null) {
capture.Pause();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (writer.IsOpened)
{
isCapturing = false;
writer.Dispose();
}
MessageBox.Show("Completed");
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
if you write file on newFrame handler Func will cause fastplaqy/slow record on some codec VP8-VP9 etc. (mpeg4 not effect) but if you start different timer on some time to write you solve your issues

I'm trying to use backgroundworker with webBrowser to download images but getting exception. What should i do?

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 System.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
using System.Text.RegularExpressions;
namespace Extract_Images
{
public partial class Form1 : Form
{
private string[] linkstoextract;
private int numberoflinks;
private int currentLinkNumber = 0;
private string mainlink;
private WebClient client;
private WebBrowser webBrowser1;
private string htmlCode;
private bool pagesorimages = false;
public Form1()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
label1.Text = "Number of links: ";
mainlink = "http://www.test.com/";
numberoflinks = 13;
backgroundWorker1.RunWorkerAsync();
}
private void ProcessNextLink()
{
if (currentLinkNumber < numberoflinks)
{
currentLinkNumber++;
string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
pagesorimages = false;
backgroundWorker1.ReportProgress(0,currentLinkNumber);
webBrowser1.Navigate(linktonav);
}
}
int count = 0;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
string pageSource = objHtmlDoc.documentElement.innerHTML;
List<string> links = new List<string>();
string[] hrefs = this.webBrowser1.Document.Links.Cast<HtmlElement>()
.Select(a => a.GetAttribute("href")).Where(h => h.Contains(".jpg")).ToArray();
foreach(string a in hrefs)
{
using (WebClient client = new WebClient())
{
client.DownloadFile(a, #"C:\Images\file" + count + ".jpg");
}
count ++;
pagesorimages = true;
backgroundWorker1.ReportProgress(0, count);
}
//ProcessNextLink();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ProcessNextLink();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (pagesorimages == false)
{
label1.Text = e.UserState.ToString();
}
if (pagesorimages == true)
{
label2.Text = e.UserState.ToString();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
The exception is on the second ReportProgress:
backgroundWorker1.ReportProgress(0, count);
This operation has already had OperationCompleted called on it and further calls are illegal
What i want to do is to report first the current page number in this case it's 1 to label1.
And then to report the number of downloaded images in this page to label2.
Then to move to the next page with the method ProcessNextLink(); and again report the page number it should be 2 and then to report the number of images downloaded in page 2.
But i'm getting this exception already on the first page.
It was working fine without the backgroundworker in the event webBrowser1_DocumentCompleted i called ProcessNextLink(); in the bottom and it was working fine. But with the backgroundworker it's not working.

Categories