I am trying to detect the internet connection, if the internet connection is available and it is connected, it will continue, otherwise it will throw message box says that the connection is not available.
What I am encounter is whether the internet connection is connected or not connected, the code will continue.
Here is the code:
** The program will continue to worker_ProgressChanged, even though there is no internet connection available **
public CheckUpdates()
{
InitializeComponent();
bool checkConnection = CheckConnection.IsConnectedToInternet();
progressBar1.Style = ProgressBarStyle.Marquee;
if (checkConnection == true)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(worker_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
else
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("No connection available, please check your internet connection!", "No connection");
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
private void CheckUpdates_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage.Equals(100))
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("No updates were available!", "No updates");
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_timer.Enabled = true;
_timer.Tick += new EventHandler(Timer_Tick);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
}
}
void Timer_Tick(object sender, EventArgs e)
{
_timer.Enabled = false;
}
class CheckConnection
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
}
Your answer much appreciated!
Thank you very much!
Because you call backgroundWorker1.RunWorkerAsync(); in the event WelcomeScreen_Load or in the event CheckUpdates_Load without checking if the Internet is connected or not. (Probably the worker_ProgressChanged is defined at design time withing the backgroundWorkder properties)
These events doesn't seems to be related to a Form.Load event handler because your class doesn't derive from Form. However it seems clear that you need to put a check there otherwise whoever triggers these events will start your background worker.
private void CheckUpdates_Load(object sender, EventArgs e)
{
if(CheckConnection.IsConnectedToInternet())
backgroundWorker1.RunWorkerAsync();
}
private void WelcomeScreen_Load(object sender, EventArgs e)
{
if(CheckConnection.IsConnectedToInternet())
backgroundWorker1.RunWorkerAsync();
}
Related
Long Story Short,
The app I am making will Launch a Game.
The Start button will then Check to make sure the games EXE is running..
IF it is running, it will run a script to press buttons 1, 2, and 3..
After that it will loop that script, but first checking if the game has not crashed (if it crashed it wont run the loop)
My Issue:
While the loop is running, which is using System.Threading.Thread.Sleep,
does not let other functions of the app preform (in this case showing and hiding button, and changing label colors.) The main reason this is important is the button it wont is the Stop button which is suppose to end the looping script.
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
Timer timer;
Stopwatch sw;
public Form1()
{
InitializeComponent();
button4.Visible = false;
button2.Enabled = false;
}
private void timer_Tick(object sender, EventArgs e)
{
label2.Text = sw.Elapsed.Seconds.ToString() + "seconds";
Application.DoEvents();
}
// ===============================================
// BUTTON FUNCTIONS
// ===============================================
// Launch GAME
private void button1_Click(object sender, EventArgs e)
{
// Launch GAME
Process.Start(#"C:\Windows\System32\Notepad.exe");
button2.Enabled = true;
}
// START BOT
private void button2_Click(object sender, EventArgs e)
{
status.Text = #"Starting Bot..";
timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
sw = new Stopwatch();
timer.Start();
sw.Start();
BotReady(sender, e);
}
// PLAYER DIED
private void button3_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"lol u ded";
}
// STOP THE BOT
private void button4_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"Bot Stopped";
button2.Visible = true;
button4.Visible = false;
button2.Enabled = true;
}
// KILL GAME AND BOT (IF IT CRASHED OR SOMETHING)
private void button5_Click(object sender, EventArgs e)
{
}
// ===============================================
// OTHER FUNCTIONS
// ===============================================
// Target GAME application
private void TargetAQ(object sender, EventArgs e)
{
// this part doesnt work yet.
// Selection.Application and Tab to it
}
// CHECK IF GAME IS STILL RUNNING, KILL BOT IF GAME IS NOT DETECTED
public void CheckStatus(object sender, EventArgs e)
{
Process[] GAME = Process.GetProcessesByName("notepad");
if (GAME.Length == 0)
// GAME NOT running
{
KillBot(sender, e);
button2.Enabled = false;
status.Text = #"GAME is not Running, Bot Stopped.";
uGAME.ForeColor = Color.Red;
button2.Visible = true;
button4.Visible = false;
button2.Enabled = false;
}
else
// GAME IS running
{
status.Text = #"GAME is Running!";
uGAME.ForeColor = Color.Green;
button2.Visible = false;
button4.Visible = true;
}
}
// Verify bot and GAME are running before starting
public void BotReady(object sender, EventArgs e)
{
CheckStatus(sender, e);
if (uGAME.ForeColor == Color.Green)
{
status.Text = #"Bot Started!";
Botting(sender, e);
}
else { status.Text = #"GAME is not running"; }
}
//THE BOT ACTIONS
public void Botting(object sender, EventArgs e)
{
// Check to make sure everything is still running
CheckStatus(sender, e);
TargetAQ(sender, e);
if (uGAME.ForeColor == Color.Green)
{
// all is running, then you good.
Script(sender, e);
}
//GAME died, kill scripts
else {
KillBot(sender, e);
status.Text = #"GAME Crashed:(";
}
}
//Things it does in-game
public void Script(object sender, EventArgs e)
{
status.Text = #"Bot in progress..";
// Use skills in game rotation
System.Threading.Thread.Sleep(3000);
SendKeys.Send("1");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("2");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("3");
// Go back and check the game has not crashed before re-running the script
Botting(sender, e);
}
// STOP THE BOT AND TIME COUNTER
public void KillBot(object sender, EventArgs e)
{
// kill the clock and bot
status.Text = #"Stopping bot...";
timer.Stop();
sw.Stop();
label2.Text = sw.Elapsed.Seconds.ToString() + " seconds";
status.Text = #"Bot Stopped";
}
}
}
I have a BackgroundWorker in a WPF application. If a condition is true, I want to immediately stop processing the _DoWork method and go straight to the _RunWorkerCompleted. I'm using .CancelAsync, but the code after this point continues to execute.
How can I cancel out of my _DoWork and fall into _RunWorkerCompleted?
Example:
private BackgroundWorker step1 = new BackgroundWorker();
public MyWindow()
{
InitializeComponent();
step1.WorkerSupportsCancellation = true;
step1.DoWork += new DoWorkEventHandler(step1_DoWork);
step1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(step1_RunWorkerCompleted);
}
private void step1_DoWork(object sender, DoWorkEventArgs e)
{
if (someCondition)
{
step1.CancelAsync();
}
// code I do not want to execute
}
private void step1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// I want to jump here from the cancel point
}
CancelAsync is a method designed to be called by something other than the DoWork handler to indicate that the DoWork handler should stop executing. The DoWork handler should be checking to see if the BGW has requested cancellation and if so, stop executing (either by returning, throwing an exception, or otherwise not performing further work).
In your DoWork handler, check the cancellation state.
private void step1_DoWork(object sender, DoWorkEventArgs e)
{
if (someCondition)
{
step1.CancelAsync();
}
if (!step1.CancellationPending)
{
// code I do not want to execute
}
else
{
e.Cancel = true;
return;
}
}
private void startAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void cancelAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}
// This event handler is where the time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
}
}
// This event handler updates the progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = "Done!";
}
}
}
}
This is how I create a thread that does domething reps times:
protected virtual void RedButtonClicked(object sender, System.EventArgs e)
{
Nuker n = new Nuker(target, reps);
bombThread = new Thread(new ThreadStart(n.nuke));
bombThread.Start();
}
The thread class:
public class Nuker
{
private string target;
private int reps;
//...
public void nuke()
{
for(int i=0; i<reps; ++i)
{
ICBM.nuke(target);
Thread.Sleep(5500);
}
System.Console.WriteLine("Done.");
}
}
(I create a new class to store some variables since I can't pass these in ThreadStart().)
Now I would like to have a simple visualisation of the process, let's say printing the current repetition in a text field on a form. How would I use the i from the loop to do that?
In the simplest form you proved a callback in the Nuker class
public Nuker(string target, int reps, Action reportCallback){..}
In the loop you just call reportCallback(i);
Nuker n = new Nuker(target, reps, ReportMethod);
with
private void ReportMethod(int currentIdx)
{
if (InvokeRequired) // Invoke if UI update
...
}
But, probably you want to use the BackgroundWorker that has build in methods for reporting progress on the UI thread. Just check the examples on MSDN.
you can do it with a backgroundworker, it´s one of the easiest threads :-)
below i have post you a sample that i have createt to teach some friends the use of the backgroundworker ;-)
private BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
public void buttonStart_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
bw.RunWorkerAsync(12); //Start
}
public int Pils(int i)
{
Thread.Sleep(2000);
bw.ReportProgress(70, "In the middle of the work..");
Thread.Sleep(2000);
bw.ReportProgress(90, "Returning the result..");
Thread.Sleep(2000);
return (2 * i);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
bw.ReportProgress(20, "Waiting for cancel..");
Thread.Sleep(2000);
if ((bw.CancellationPending == true))
e.Cancel = true;
else
{
bw.ReportProgress(50, "Starting process..");
e.Result = Pils((int)e.Argument);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bw.ReportProgress(100, "Work done..");
if ((e.Cancelled == true))
textBox1.Text = "Canceled!";
else if (e.Error != null)
textBox1.Text = ("Error: " + e.Error.Message);
else textBox1.Text = e.Result.ToString();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
bw.CancelAsync();
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add((e.ProgressPercentage.ToString() + "%") + " - " + e.UserState as String);
}
url to the blogpost: link
how can i set timeout for webBrowser navigate (url) event
c# netframework 4.0
By using a Timer of course. For example:
public void NavigateTo(Uri url) {
webBrowser1.Navigate(url);
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e) {
timer1.Enabled = false;
MessageBox.Show("Timeout on navigation");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
if (e.Url == webBrowser1.Url && timer1.Enabled) {
timer1.Enabled = false;
// etc..
}
}
I am using following approach based on Navigating and Navigated events. The time between these two events are observed for redirecting to home pgae.
//Navigation Timer
timer2.Enabled = true;
timer2.Interval = 30000;
br.DocumentCompleted += browser_DocumentCompleted;
br.DocumentCompleted += writeToTextBoxEvent;
br.Navigating += OnNavigating;
br.Navigated += OnNavigated;
br.ScriptErrorsSuppressed = true;
br.Navigate(ConfigValues.websiteUrl);
private void OnNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
//Reset Timer
timer2.Stop();
timer2.Start();
WriteLogFunction("OnNavigating||||||"+e.Url.ToString());
}
private void OnNavigated(object sender, WebBrowserNavigatedEventArgs e)
{
//Stop Timer
timer2.Stop();
WriteLogFunction("NAVIGATED <><><><><><><> " + e.Url.ToString());
}
private void timer2_Tick(object sender, EventArgs e)
{
WriteLogFunction(" Navigation Timeout TICK");
br.Stop();
br.Navigate(ConfigValues.websiteUrl);
}
Reference
Create a time-out for webbrowser loading method
webbrowser timeout if page wont load
I have a background worker. Before I invoke the worker I disable a button and make a gif visible. I then invoke the runworkerasync method and it runs fine until comleteion. On the 'RunWorkerCompleted()' I get a cross thread error. Any idea why?
private void buttonRun_Click(object sender, EventArgs e)
{
if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
{
try
{
u = new UpdateDispositionReports(
Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
, textBoxFolderLoc.Text
, Properties.Settings.Default.TemplatePath
, Properties.Settings.Default.ConnStr);
this.buttonRun.Enabled = false;
this.pictureBox1.Visible = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
//backgroundWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
}
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
buttonRun.Enabled = true;
pictureBox1.Visible = false;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
u.Execute();
}
It seems to be an issue with VSTO and BackgroundWorker.
The solution is here.
Basically you need to call
System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
before you call RunWorkerAsync. Works great.
To avoid instantiating the object every time you may have a static member in you AddIn's main class and reuse it. This way you only instantiate once.
something about VSTO running the background worker on the same thread as the controls. Not sure. I had to check the InvokeRequired
private void buttonRun_Click(object sender, EventArgs e)
{
if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
{
try
{
u = new UpdateDispositionReports(
Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
, textBoxFolderLoc.Text
, Properties.Settings.Default.TemplatePath
, Properties.Settings.Default.ConnStr);
this.buttonRun.Enabled = false;
this.pictureBox1.Visible = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
//backgroundWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
}
}
}
delegate void ReenableRunCallback();
private void ReenableRun()
{
if (this.buttonRun.InvokeRequired)
{
ReenableRunCallback r = new ReenableRunCallback(ReenableRun);
this.buttonRun.Invoke(r, null);
}
else
this.buttonRun.Enabled = true;
}
private void HideProgress()
{
if (this.pictureBox1.InvokeRequired)
{
ReenableRunCallback r = new ReenableRunCallback(HideProgress);
this.pictureBox1.Invoke(r, null);
}
else
this.pictureBox1.Visible = false;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ReenableRun();
HideProgress();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
u.Execute();
}