Setting a timer to an event - c#

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

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

C# Clear richTextBox in Timer

I want to save richTextBox.Text every minute, when user checked save checkbox.
here checkbox event.
num_saveTime is numericUpDown control for inpute minute.
save_timer is global variable.
private void chk_save_CheckedChanged(object sender, EventArgs e)
{
if (chk_save.Checked)
{
num_saveTime.Enabled = false;
save_timer = new System.Timers.Timer();
save_timer.Elapsed += new System.Timers.ElapsedEventHandler(save_timer_Elapsed);
save_timer.Interval = 250;
save_timer.Start();
}
else
{
num_saveTime.Enabled = true;
save_timer.Stop();
}
}
and Timer Event
delegate void TimerDelegate(object sender, System.Timers.ElapsedEventArgs e);
void save_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (rtxb_PKT.InvokeRequired)
{
TimerDelegate tdel = new TimerDelegate(save_timer_Elapsed);
rtxb_PKT.Invoke(tdel, new object[] { sender, e });
}
else
{
string now_ss = DateTime.Now.ToString("ss");
if (now_ss.Equals("00"))
{
string now_mm = DateTime.Now.ToString("mm");
string save_mm = Convert.ToInt32(num_saveTime.Value).ToString("D2");
if (save_mm.Equals(now_mm))
{
string path = Application.StartupPath + #"\" + DateTime.Now.ToString("yy-MM-dd--HH-mm-sss") + ".rtf";
rtxb_PKT.SaveFile(path, RichTextBoxStreamType.RichText);
rtxb_PKT.Clear(); //----here
}
}
}
}
I want clear richTextBox after save.
But I insert .Clear() that position, it clear text before save, so file is empty...
How can I clear it after saving?

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.

Label Text Refresh every second

I'm trying to make a label refresh every second so the countdown updates, having some trouble. I'm extremely new to C# apologies for the noob questions.
private void Form1_Load(object sender, EventArgs e)
{
bool ephCD = true;
int ephHours = (DateTime.Today.AddDays(1) - DateTime.Now).Hours;
int ephMinu = (DateTime.Today.AddDays(1) - DateTime.Now).Minutes;
int ephSecs = (DateTime.Today.AddDays(1) - DateTime.Now).Seconds;
label1.Text = ephHours.ToString() + ":" + ephMinu.ToString() + ":" + ephSecs.ToString();
while (ephCD == true)
{
label1.Refresh();
}
}
When launching this the program doesn't even appear.
Why does the program not appear?
You are performing an infinite loop in Form_Load. This means that the form will never finish loading, and your program will be stuck.
Your refresh loop needs to be on a separate thread, or ideally toss the loop and use a Timer instead of spin locking the CPU on an infinite loop.
Timer myTimer = new Timer(1000);
void Form1_Load()
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Update label here
}
Updating the label in a while statement is not a good option, a better approach would be to use Timer class
var aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
//update the label
}
This will do, just copy and paste:
private void Form1_Load(object sender, EventArgs e)
{
// To update the first time.
label1.Text = (DateTime.Today.AddDays(1)- DateTime.Now).ToString(#"hh\:mm\:ss");
var timer = new Timer {Interval = 1000};
timer.Tick += (o, args) =>
{
label1.Text = (DateTime.Today.AddDays(1)- DateTime.Now).ToString(#"hh\:mm\:ss");
};
timer.Start();
}
I ended up with this simpler solution:
<script>
var myTimer = setInterval(Atualizar, 20000);
function Atualizar() {
__doPostBack('UpdatePanelNew', '');
}
</script>
Make sure you wrap what you want to update within an UpdatePanel.
This code will request a postback in every 20s. So in the code behind I can do this:
protected void Page_Load(object sender, EventArgs e)
{
myLabel.InnerText = GetInDatabaseTheValueIwant();
}

How do i use a backgroundworker?

I have a backgroundworker in the designer. Set the option WorkerReportsProgress and WorkerSupportsCancellations to true.
Also added all the three events of the backgroundworker.
Now i have timer1 tick event:
private void timer1_Tick(object sender, EventArgs e)
{
counter += 1;
label9.Text = counter.ToString();
label9.Visible = true;
}
I havea method called it NewsUpdate:
private void NewsUpdate()
{
if (counter == 10)
{
scrollLabel1.Reset();
scrollLabel1.Text = " ";
scrollLabel1.Invalidate();
client.Encoding = System.Text.Encoding.GetEncoding(1255);
page = client.DownloadString("http://rotter.net/scoopscache.html");
TextExtractor.ExtractDateTime(page, newText, dateTime);
StreamWriter w = new StreamWriter(#"d:\rotterhtml\rotterscoops.html");
w.Write(page);
w.Close();
TextExtractor.ExtractText(#"d:\rotterhtml\rotterscoops.html", newText, dateTime);
combindedString = string.Join(Environment.NewLine, newText);
this.scrollLabel1.Text = combindedString;
scrollLabel1.Invalidate();
counter = 0;
}
}
And all the backgroundworker events:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
NewsUpdate();
}
Progress:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
Completed:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
What i want to do is to call each 10 seconds to the method NewsUpdate through the backgroundworker so it will not freeze the application for 1-2 seconds each time it's making an update. But now it's calling the NewsUpdate method only once.
How do i use the backgroundworker with the NewsUpdate method ?
What should i add if at all in each of the events of the backgroundworker ?
Are there any methods or files in the NewsUpdate method that the backgroundworker will throw exception on them since it's ui or something ?

Categories

Resources