Loop Script not updating other forms - c#

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";
}
}
}

Related

Exit opened Application

I'd like to know how to exit my opened Application properly.
The way I am currently trying is not working.
This is how I am opening the application:
private void button1_Click(object sender, EventArgs e)
{
if (status != true)
{
status = true;
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = "C:\\Users\\David\\Desktop\\Test\\Test.exe";
myProcess.Exited += new EventHandler(Process_Exited);
myProcess.EnableRaisingEvents = true;
myProcess.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
myProcess.Close();
status = false;
}
I've managed to do it, just do:
myProcess.Kill();

Displaying different label text each second

I have three forms, From 1 is a main form and Form2 is splash screen and Form3 is a mini form.
So what i am trying to do is when ever i send a mail this From3 will pop up which has a gif image
and a label. So i am successfully able to make the From3 for 5 sec, in which the label will
change for different words for each second.
In form 3
i am using timer1 to run the mini form only for 5 seconds. and timer two to run only for 1 sec.
I guess we can do this in a better way which is pretty simple and easy.. Any good ideas and
help are most welcome!!!
Note:- Also when i again press the button send mail.. the label is starting from - Done!!.. Any helps.. The first time it starts from Connecting to smtp server..but on second time onwards its staring from Done!! then label going to Connecting to smtp server.. and so on!!
Here is my code:
Form1
private void sendmail_Click(object sender, EventArgs e)
{
//mail basic function here!!!!
smtp.Send(msg);
_f3.ShowDialog();//- - ->> goes to mini form Form3
smtp.Dispose();
MessageBox.Show("Email Successfully Sent!!!", "Mail!!!.");
}
Form3
private void Form3_Load(object sender, EventArgs e)
{
timer1.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Interval = 1000;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
timer1.Stop();
}
int StopTime = 0;
private void timer2_Tick(object sender, EventArgs e)
{
StopTime++;
if (StopTime == 1)
{
label1.Text = " Connecting to smtp server..";
}
if (StopTime == 2)
{
label1.Text = " Fetching recipients..";
}
if (StopTime == 3)
{
label1.Text = " Attaching G-code files..";
}
if (StopTime == 4)
{
label1.Text = " Done!!";
StopTime = 0;
timer2.Stop();
}
}
Does Form3 close after it displays Done? You could do something like this:
private void Form3_Load(object sender, EventArgs e)
{
SetLabel1Text(); //reset label text
timer1.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Interval = 1000;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
timer1.Stop();
}
int StopTime = 0;
private void timer2_Tick(object sender, EventArgs e)
{
StopTime++;
SetLabel1Text();
if (StopTime == 4)
{
StopTime = 0;
timer2.Stop();
}
}
private void SetLabel1Text()
{
string[] label1Text = { " Connecting to smtp server..", " Connecting to smtp server..", " Fetching recipients..", " Attaching G-code files..", " Done!!" };
label1.Text = label1Text[StopTime]; //populate label from array of values
}

Check internet connection is available or not

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();
}

c# Forms Timer does not stop

I have a WinForms app that increments a timer once per second and updates a labels' text.
A second timer increments once every 20msec to look for recent mouse movements and writes the current coordinates to another label.
When the program receives Alt+F4 I instantiate "MessageBoxQueryClose" where the user is asked to close or resume operation. Before the MessageBox is displayed I'd like to stop
the once-per-second timer from firing, and after the user said "please continue" to re-enable it.
This is where I observed some 'strange' behavior: the once-per-second timer fires again
while the MessageBox is open and the mouse is moved.
Code for the form:
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.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool _altF4Pressed = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.F4)
_altF4Pressed = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// show the MessageBox asking the user if the programm should really exit
MessageBoxQueryClose msgBoxQC = new MessageBoxQueryClose();
msgBoxQC.QueryClose(ref _altF4Pressed, ref timer2, ref e);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 20;
timer1.Enabled = true;
timer2.Interval = 1000;
timer2.Enabled = true;
}
bool toggle = false;
private void timer2_Tick(object sender, EventArgs e)
{
if (toggle)
label1.Text = "tick";
else
label1.Text = "tack";
toggle = !toggle;
}
Point oldPos, newPos;
private void timer1_Tick(object sender, EventArgs e)
{
newPos = Cursor.Position;
label2.Text = Convert.ToString(newPos.X + ", " + newPos.Y);
CompareCursorPosition();
oldPos = newPos;
}
private void CompareCursorPosition()
{
if (oldPos != newPos)
Display_ResetFallback();
}
private void Display_ResetFallback()
{
timer2.Stop();
timer2.Start();
}
}
}
Code for MessageBoxQueryClose:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class MessageBoxQueryClose
{
public void QueryClose(ref bool _altF4Pressed, ref Timer timer, ref FormClosingEventArgs e)
{
if (_altF4Pressed)
{
// first, disable timer2 to stop Form1.label1 from being updated
timer.Enabled = false;
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult res;
res = MessageBox.Show("Close program ?", "timers",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (res == DialogResult.Yes)
{
return;
}
// if program execution shall continue, re-enable timer2
timer.Enabled = true;
}
e.Cancel = true;
_altF4Pressed = false;
}
}
}
}
I have the gut feeling that my issue is about timers and threading, but I only recently started out with .Net, so any insight is appreciated.
br, Chris
Your timer1_Tick event calls CompareCursorPosition(), which calls Display_ResetFallback(), which starts timer2 again.
So you stop timer2 in QueryClose(), but then the timer1_Tick event fires, starting timer2 up again.
You could modify Display_ResetFallback() to make sure your timer is only restarted if it's currently running:
if (timer2.Enabled)
{
timer2.Stop();
timer2.Start();
}
As a side note, I'd probably get rid of the MessageBoxQueryClose class entirely and just modify your FormClosing event accordingly:
if (e.CloseReason == CloseReason.UserClosing)
{
timer2.Stop();
if (MessageBox.Show("Close program ?", "timers", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
{
e.Cancel = true;
timer2.Start();
}
}
You can try this...
timer1.Stop();
label1.Text = timer1.Enabled == false ?"timer disabled":"timer enabled";
if (MessageBox.Show("Close program ?", "timers",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
//do stuff here if you want
}
timer1.Start();
label1.Text = timer1.Enabled == false ? "timer disabled" : "timer enabled";
just put those label text for you to check.
this edit you dont require the class
EDIT:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool _altF4Pressed = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.F4)
_altF4Pressed = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//show the MessageBox asking the user if the programm should really exit
//MessageBoxQueryClose msgBoxQC = new MessageBoxQueryClose();
//msgBoxQC.QueryClose(ref _altF4Pressed, ref timer2, ref e);
if (_altF4Pressed)
{
this.timer2.Stop();
if (MessageBox.Show("Close program ?", "timers",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
{
e.Cancel = true;
this.timer2.Start();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 20;
timer1.Enabled = true;
timer2.Interval = 1000;
timer2.Enabled = true;
}
bool toggle = false;
private void timer2_Tick(object sender, EventArgs e)
{
if (toggle)
label1.Text = "tick";
else
label1.Text = "tack";
toggle = !toggle;
}
//Point oldPos, newPos;
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = MousePosition.X.ToString() + " , " + MousePosition.Y.ToString();
}
//private void CompareCursorPosition()
//{
// if (oldPos != newPos)
// Display_ResetFallback();
//}
//private void Display_ResetFallback()
//{
// timer2.Stop();
// timer2.Start();
//}
}
Just put my first post inside your code....It stops for me,and no need for the extra class,removed the 2 points and the 2 methods(Display_ResetFallback and CompareCursorPosition),but you can use them(the 2 point variables) if you want and inside timer1 do your checks.

How to set timeout for webBrowser navigate event

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

Categories

Resources