I have created a timer, now I want whenever I click on "Add Timer" button a new panel with same existing panel property appears on the form below to existing panel. How can I do this?
The code I have so far:
public partial class Form1 : Form
{
int countdown;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
countdown = int.Parse(textBox1.Text);
TimeSpan ts = TimeSpan.FromSeconds(countdown);
label4.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", ts.Hours, ts.Minutes, ts.Seconds);
ts = ts.Subtract(new TimeSpan(0, 0, 1));
textBox1.Text = ts.TotalSeconds.ToString();
label4.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", ts.Hours, ts.Minutes, ts.Seconds);
if (ts.TotalSeconds == 0)
{
//timer1.Stop();
label4.ForeColor = System.Drawing.Color.Red;
MessageBox.Show("Times Up!");
}
}
private void button3_Click(object sender, EventArgs e)
{
if(button3.Text=="Start")
{
timer1.Enabled = true;
button3.Text = "Reset";
timer1.Start();
}
else
{
timer1.Enabled = false;
button3.Text = "Start";
timer1.Stop();
textBox1.Text = "00";
label4.Text = "00:00:00";
}
}
private void button4_Click(object sender, EventArgs e)
{
if(button4.Text=="Pause")
{
timer1.Stop();
button4.Text = "Resume";
}
else
{
button4.Text = "Pause";
timer1.Start();
}
}
Related
I've created a Typing Test Form that already works:
The Richtextbox where a Random word or paragraph will be shown
The Textbox2 where you type
But How to code everytime you type a letter if the Richtextbox and Textbox2 are equal (==) the same letter you type will be highlighted to color gray on Richtextbox until you completed a word then the whole paragraph
{
private int numberOfWords = 0;
private int counter = 300;
string[] randomWords = new string[] {
"It was Richter Belmont, the legendary vampire hunter, who succeeded in finally ending the menace of Count Dracula, Lord of the Vampires who had been brought back from the grave by the dark priest Shaft.",
"Being entirely honest with oneself is a good exercise.",
"With great power comes great responsibility.",
"Whosoever holds this hammer, if he be worthy, shall possess the power of Thor.",
"Coming from your friendly neighborhood Spider-Man!.",
"The time has once again come for the forces of Good and Evil to engage in their ancient battle. Dracula's castle beckons for you. And no man can say who shall emerge victorious.",};
public Advance()
{
InitializeComponent();
}
static void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ;)
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
textBox2.Focus();
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) && (richTextBox1.Text == textBox2.Text))
{
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
textBox2.Clear();
numberOfWords += 1;
label4.Text = numberOfWords.ToString();
}
else if ((e.KeyCode == Keys.Enter) && (richTextBox1.Text != textBox2.Text))
{
string message = "Fail. Try again";
MessageBox.Show(message);
timer1.Stop();
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 300;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
label1.Text = counter.ToString();
if (label1.Text == "0")
{
string message = "Corrected Paragraph ";
string title = "Result";
MessageBox.Show(message + numberOfWords.ToString(), title);
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 240;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
var TypingTest = new TypingTest();
TypingTest.Closed += (s, args) => this.Close();
TypingTest.Show();
}
private void Advance_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Stop();
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 300;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.Focus();
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
HighlightPhrase(richTextBox1, "a", Color.Red);
}
}
I want to sync my progress bar in my project with the timer countdown.
This is what I has now:
namespace Timer1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int counter=80;
DateTime dt = new DateTime();
private void button1_Click(object sender, EventArgs e)
{
int counter = 80;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
textBox1.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
progressBar1.Increment(1);
if (counter == 0)
{
timer1.Stop();
}
textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox1.Clear();
progressBar1.Value = 0;
}
}
}
I want the progress bar to finish when the timer to ends.
You need to specify the progressBar1 to have its .Step and Maximum properties match the Interval and counter variable. For example:
private int counter = 80;
DateTime dt = new DateTime();
private void button1_Click(object sender, EventArgs e)
{
// The max is the total number of iterations on the
// timer tick by the number interval.
progressBar1.Max = counter * 1000;
progressBar1.Step = 1000;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
textBox1.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
// Perform one step...
progressBar1.PerformStep();
if (counter == 0)
{
timer1.Stop();
}
textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
}
im kinda new to programming, and i was trying to recreate candybox (some interactive website)
in windows form application. i have a variable named candy, and a timer that every second adds one to the variable candy, i have tried putting the label.text = "candy: " + candy.ToString(); in that method and it doesnt seem to work, any one able to help?
code:
public partial class Form1 : Form
{
public int candy { get; set; }
public int lollipop { get; set; }
public Form1(int value, int lollipop)
{
this.candy = value;
this.lollipop = lollipop;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "candy: 0";
button2.Enabled = false;
button2.Visible = false;
label2.Visible = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerHandler);
timer.Start();
}
private void button1_Click(object sender, EventArgs e)
{
candy += 2;
UpdateCandy(candy, lollipop);
label2.Text = "lollipops" + lollipop.ToString();
if (candy > 9)
{
button2.Enabled = true;
button2.Visible = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (candy <= 10)
{
button2.Enabled = false;
}
candy -= 10;
lollipop += 1;
UpdateCandy(candy, lollipop);
label2.Text = "lollipops" + lollipop.ToString();
label2.Visible = true;
}
System.Timers.Timer timer = new System.Timers.Timer(1000);
private void TimerHandler(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime start;
TimeSpan elapsed = TimeSpan.MaxValue;
while (elapsed.TotalSeconds > 1.0)
{
start = DateTime.Now;
candy += 1;
elapsed = DateTime.Now - start;
}
timer.Interval = 1000 - elapsed.TotalMilliseconds;
timer.Start();
}
public void Form1_Shown(object sender, EventArgs e)
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerHandler);
timer.Start();
}
private void UpdateCandy(int candy, int lollipop)
{
label1.Text = "candy: " + candy.ToString();
label2.Text = "lollipops" + lollipop.ToString();
}
}
and im using visual studio 2012 (if this information is of any help)
I have created a C# windows application in that I inserted the progress bar.
When a button is clicked the progress bar should appear and then it should start the process for some 2 to 3 seconds and when the process bar is completed it should be hidden.
I have used this code to solve this but its not working.
While the Progress bar is running, the label box that should be like "Generating... 45%" and after completing the label box should be "Generated 100%..", but when I insert the label its showing some errors.
Here is the picture before clicking the Generate button..
On Processing I Should get like this..
On Final Process id should be like this and the progress bar should hidden..
ProgressBar1.Visible = true;
if (isProcessRunning)
{
MessageBox.Show("A process is already running.");
return;
}
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
isProcessRunning = true;
for (int n = 0; n < 100; n++)
{
Thread.Sleep(1);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = n));
}
MessageBox.Show("Generated!!!");
if (progressBar1.InvokeRequired)
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = 0));
isProcessRunning = false;
}
));
// Start the background process thread
backgroundThread.Start();
I suggest you to use BackgroundWorker to show progress bar in C# winform .
Here is an example ,
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label1.Text = "";
label2.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int total = 57; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
bgw.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
}
You can set your progress bar's visible to false in bgw_RunWorkerCompleted .
The following links will show how to use backgroundworker
DotNetPerls
MSDN Reference
CodeProject
Good Luck :)
This is the Code i am using backgroundWorker..
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label3.Text = "";
this.StartPosition = FormStartPosition.CenterScreen;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btn_generate_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
bgw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int total = 100; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(10);
int percents = (i * 100) / 100;
bgw.ReportProgress(percents, i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
if (e.ProgressPercentage == 100)
{
label3.Text = String.Format("Generated.. {0} %", e.ProgressPercentage);
}
// label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
}
}`
In this There is a problem in the below code when i click the button for first time the progress bar runs one time and if i clicked second time it runs for 2 times and so on.. other wise the code is perfectly working..
public partial class Form1 : Form {
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label3.Text = "";
this.StartPosition = FormStartPosition.CenterScreen;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btn_generate_Click(object sender, EventArgs e)
{ new BackgroundWorker();
progressBar1.Visible = true;
bgw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int total = 100; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(10);
int percents = (i * 100) / 100;
bgw.ReportProgress(percents, i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
if (e.ProgressPercentage == 100)
{
label3.Text = String.Format("Generated.. {0} %", e.ProgressPercentage);
}
// label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
}
}
I have a timer and in 30 minutes I want to count clicks and show it in a textbox. but how? here is timer code:
decimal sure = 10;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
sure--;
label3.Text = sure.ToString();
if (sure == 0)
{
timer1.Stop();
MessageBox.Show("Süre doldu");
}
}
Declare your clickCounter at global, and raise your counter++ in Mouse Click Event.
If you do it more specific, you can use Background Worker, to track time.
and use Application.DoEvents() to write remaining to to textBox
Put a button, 2 labels, and a timer. rename labels with lblClickCount and lblRemainingTime
private int clickCounter = 0;
private void button1_Click(object sender, EventArgs e)
{
clickCounter++;
lblClickCount.Text = clickCounter.ToString();
}
decimal sure = 10;
private void timer1_Tick(object sender, EventArgs e)
{
sure--;
lblRemainingTime.Text = sure.ToString();
Application.DoEvents();
if (sure == 0)
{
timer1.Stop();
MessageBox.Show("Süre doldu. Toplam tiklama sayisi:" + clickCounter.ToString());
}
}
If you wanted to reuse buttoN1 to count the clicks but not Start new timer you can add a if around the code you want to protect.
bool hasTimerStarted = false;
int numberOfClicks = 0;
private void button1_Click(object sender, EventArgs e)
{
if(!hasTimerStarted)
{
button1.Enabled = true;
timer1.Start();
hasTimerStarted = true;
}
++numberOfClicks;
}
When the timer expires you reset the count and if the timer has started.
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
label3.Text = elapsedTime;
labelClicks.Text = "User clicked " + clicksNo.toString() + "nt times..";
if (stopWatch.ElapsedMilliseconds >= this.minutes * 60 * 1000)
{
timer1.Stop();
MessageBox.Show("Time elapsed.");
hasTimerStarted = false;
numberOfClicks = 0;
}
}