Unable to start after stop the application - c#

I have a little application contains a start and reset button in this
timer alike program.
In the button start event handler, I have a FileSystemWatcher and Timer
to call a function at certain time.
I also have another timer to count down the time call timerCounter just to do for visual aid.
What I want is to click the start button again to run the program
after the stop/reset button is clicked, but fail to do so.
Below is my part of the code that I have doubt how to restart the program again on the start button click event.
private void btnStart_Click(object sender, EventArgs e)
{
// file system watcher, timer and one other function inside this event handler
_timeLeft = (int)numUpDown.Value;
timerCounter.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
_timer.Stop();
timerCounter.Stop();
_timer.Dispose();
numUpDown.Value = 0;
timeLabel.Text = 0 + #" seconds";
lblResult.Text = #"Program has stopped, press start button to
process again.";
_fsw.Dispose();
}
private void timerCounter_Tick(object sender, EventArgs e)
{
if (_timeLeft > 0)
{
_timeLeft = _timeLeft - 1;
timeLabel.Text = _timeLeft + " seconds";
lblResult.Text = $#"Process began and counting down {timeLabel.Text} in seconds";
}
else
{
timerCounter.Stop();
timerCounter.Enabled = false;
timeLabel.Text = $#"Time's up";
}
}

Related

Loop Script not updating other forms

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

Can't write to the richTextBox

I have this simple program :
private static System.Timers.Timer t3;
private void button1_Click(object sender, EventArgs e)
{
t3 = new System.Timers.Timer(5000);
t3.AutoReset = true; t3.Enabled = true; t3.Elapsed += OnTimedEvent3;
}
private void OnTimedEvent3(Object source, ElapsedEventArgs e)
{
// MessageBox.Show("event raised");
richTextBox1.Text = "t3 is elapsed ";//
}
PROBLEM : : Nothing appears in the richTextBox1 after event is fired ! I have tried MessageBox and that works fine . what could be the problem ??
Your problem is the following:
The eventhandler of your timer is running on a different thread like your UI. You need to invoke the control like
if(richTextBox1.InvokeRequired == true)
{
richTextBox1.Invoke((MethodInvoker)delegate
{
richTextBox1.Text = "t3 is elapsed "
});
}
else
{
richTextBox1.Text = "t3 is elapsed ";
}
to access it correctly. Thats because UI objects are related to their thread. Creating a MessageBox for example is possible out of every thread - because your Box is not existing already.

Stop Writing File to TextBox C#

I have some problem with writing file to TextBox in C#. Something what I want is when I press button, date and time will be written to textbox and automatically stop writing even though the button still be pressed. What should I do ? I can't stop writing file to TextBox.
private void button1_Click(object sender, EventArgs e)
{
countermerah1++;
if (countermerah1 == 1)
{
StatusBox.Text += "B" + "\r\n";
countermerah1 = 0;
}
}
Would this meet your requirements?
private void button1_Click(object sender, EventArgs e)
{
StatusBox.Text += "B" + "\r\n";
StatusBox.Enabled = false;
}

SendKeys GUI Bug

I've made this program in C#:
namespace Spammer
{
public partial class Form1 : Form
{
int delay, y = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
delay = int.Parse(textBox2.Text);
timer1.Interval = delay;
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
String textt = textBox1.Text;
SendKeys.SendWait(textt);
}
}
}
It works fine most of the time, and it can really send keys quickly.
But when I insert a delay of, for example, 10 MS, it's very hard to click the "Stop" button to stop it. The only way to stop the sending is to close the program and I don't want to do that.
Is there anyway I can send keys very quickly, like 5-10 MS, without it impairing my ability to press the buttons inside the program? I can't click while it's sending quickly...
The problem is that you're using SendWait. That will wait for the target application to respond - and while that's happening, your application won't be able to respond to user input. If you use Send instead of SendWait, your UI thread won't be blocked waiting for the key press to be processed.
I was able to reproduce the issue. The app is sending a keystroke every 10 milliseconds. To me, this is not at all surprising that the app is causing freezes. A keystroke every 10 milliseconds is quite a barrage to the active App. Threading is not going to help. Why is this behavior surprising?
In other words, I don't expect things to work out well when I overload the message pump.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Spammer//your own namesapce
{
public partial class Form1 : Form
{
int delayInMilliseconds, y = 1;
private Timer timer1;
public Form1()
{
InitializeComponent();
//StartTimerWithThreading();
SetupTimer();
}
void StartTimerWithThreading()
{
Task.Factory.StartNew(() =>
{
SetupTimer();
});
}
void SetupTimer()
{
timer1 = new Timer();//Assume system.windows.forms.timer
textBox2.Text = "10";//new delay
timer1.Tick += timer1_Tick;//handler
}
private void button1_Click(object sender, EventArgs e)
{
delayInMilliseconds = int.Parse(textBox2.Text);
timer1.Interval = delayInMilliseconds;
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
String textt = textBox1.Text;
SendKeys.SendWait(textt);
}
}
}
The simple solution is instead of adding code to a Click event handler for your button, we need a MouseDown event handler:
//MouseDown event handler for the button2
private void button2_MouseDown(object sender, EventArgs e) {
timer1.Enabled = false;
}
Or you can keep using the Click event handler but we send the key only when the MouseButtons is not Left like this:
private void timer1_Tick(object sender, EventArgs e) {
String textt = textBox1.Text;
if(MouseButtons != MouseButtons.Left) SendKeys.Send(textt);
}
//then you can freely click your button to stop it.

Setting a timer to an event

I intend to put a timer in my the following code so that that the button will be enabled again after 5 seconds. AS you can see, my send button will be disabled after the user send 5 message. I want to enabled it after 5 seconds have elapsed.
Any suggestion is welcomed.
public bool stopSpam(int counter)
{
int spam = counter;
if (spam < 6)
{
return false;
}
else
{
return true;
}
}
private void button1_Click(object sender, EventArgs e)
{
counter++;
bool check = stopSpam(counter);
if (check == false)
{
if (textBox2.Text != "")
{
if (textBox2.Text.ToLower().StartsWith("/"))
{
onCommand(textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
else
{
m_ChildConnection.SendMessage("MSG :" + textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
}
}
else
{
button1.Enabled = false;
}
Thanks in adavence!
Have a timer, set its interval to 5 seconds (5000). Keep it disabled by default.
When the button is pressed enable the timer
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
timer.Enabled = true;
}
When a tick occurs after 5 seconds, enable the button and disable the timer again.
private void timer_Tick(object sender, EventArgs e)
{
button1.Enabled = true;
timer.Enabled = false;
}
Hard to figure out what you're trying to achieve but you could take the following steps to disable the enable the button after 5 seconds.
Add:
private Timer t;
as a class variable.
then after your InitializeComponent add:
t = new Timer(5000){Enabled = false, Tick += (myTick)};
then add this method:
private void myTick(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}
Also, consider updating this method:
your stopSpam method to:
public bool stopSpam(int counter)
{
return counter >= 6;
}
In fact, there is actually no need for the method:
Simply change
if(check == false)
to
if(counter > 5)
You can simply use System.Timers.Timer class to put timer.
//Define the timer
private System.Timers.Timer buttonTimer;
// Initialize the timer with a five second interval.
buttonTimer= new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
buttonTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//Start the timer
buttonTimer.Start();
// Enable the button in timer elapsed event handler
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}

Categories

Resources