Timer on Mouse Down in c# - c#

So I want to know for how long the user presses down on a button. I am using the button1_MouseDown method as you can see below. However the count variable is staying 0.
Can someone please help me solve this problem please?
Thanks in advance!
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.Controls)
{
if(sender == mk)
{
if(e.Button == MouseButtons.Left)
{
timer1.Enabled = true;
count = 0;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
sp.SoundLocation = ( ---directory---- + mk.musicNote + ".wav");
sp.Play();
}
}
}
}
private void timer1_Tick (object sender, EventArgs e)
{
count = count++;
}

Your problem is due to the assignment using a post increment.
count = count++;
The order of events is to evaluate the right hand side including side effects before the assignment - so the current value of count is stored (=0) count is then incremented & now the stored value is assigned - the original value of zero is being written back over the incremented value.
You only need to use count++;
private void timer1_Tick (object sender, EventArgs e)
{
count++;
}

Related

Creating decreasing sequence with (x++)%n in C#

So, I know that with a code snippet such as:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += (x++)%4 + 1;
}
a sequence of 12341234 is displayed on the form if the button is clicked 8 times.
My goal is to get 43214321 to display.
I'm able to get 32103210 with:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 3-(x++)%4;
}
I'm also able to get 32143214 with:
int x = 1; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4 + ;
}
What am I doing wrong? And is there a general formula for this?
Note: My x DOES have to be initialized to 1.
Just change the formula to:
Label1.Text += 4-((x-1)++)%4;
Try using this formula:
5-(1+(x+++3)%4)
That is:
Label1.Text += (5-(1+(x+++3)%4)).ToString();
The first line of code that you've written is basically cycling between 3 to 1.
x=0;
Label1.Text += 3-(x++)%4;
x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.
You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4;
}

need a timer for my C# morse converter

I'm trying to develop an application to convert text to morse code and vice versa. I just managed to do the first phase completely which means when you type a character you will see the encoded type of that character.
but in the second phase I got some problem:
here is my code:(hint:sw=first stopwatch,flagsw=second stopwatch,datas=dataset,dbc=databaseconverter,listofcode=string of '.' and '-')
private void txtletters_KeyDown(object sender, KeyEventArgs e)
{
txtletters.BackColor = Color.Yellow;
sw.Start();
if (flagsw.ElapsedMilliseconds > 400)
{
datas = dbc.srchfortext(listofcode);
lbltext.DataBindings.Clear();
lbltext.DataBindings.Add("text", datas, "t.letter");
txtletters.Text += lbltext.Text;
listofcode = "";
}
flagsw.Reset();
}
private void txtletters_KeyUp(object sender, KeyEventArgs e)
{
txtletters.BackColor = Color.White;
sw.Stop();
if (sw.ElapsedMilliseconds < 250)
listofcode += ".";
else
listofcode += "-";
sw.Reset();
flagsw.Start();
}
I just managed to do the work somehow but as the code shown:
when you press any key first timer will start and first timer determine if it is . or -
when you release it second timer will start (with that timer I want to know if the string of '.','-' should be closed and send to database to return the specified character...the problem in here is that the application won't end the timer and return the char unless I preform a keydown again and that means I'm not gonna see the char i typed unless I press another key(just don't tell me it's because that the second timer is in keydown, I had to do that cause I didn't have any other choice...But at least I know the Idea but don't know how to implement it...I just need somebody to help me implement it...)
I need that second timer works in background when a keydown occurred it will reset and when a keyup occurred(means that key released)it will start again. whenever second timer(flagsw.ElapsedMilliseconds > 400)got bigger than that time it will do the job and clear the string for next use.
First I have to thanks to Chris...with your answer I got the idea and found the way...
It's now fully implemented and works here is my code if anybody else wants to use...(it's just the decoder part of the morse project)
namespace Morse_Code
{
public partial class frmdecdotmode : Form
{
Boolean flag_isdown = false;
Stopwatch sw = new Stopwatch();
Timer morse_timer = new Timer();
string listofcode;
DataSet datas = new DataSet();
DataBaseController dbc = new DataBaseController();
public frmdecdotmode()
{
InitializeComponent();
}
private void frmdecdotmode_FormClosing(object sender, FormClosingEventArgs e)
{
MainMenu mm = new MainMenu();
mm.Show();
this.Hide();
}
private void txtletters_KeyDown(object sender, KeyEventArgs e)
{
flag_isdown = true;
txtletters.BackColor = Color.Yellow;
sw.Start();
morse_timer.Stop();
}
private void txtletters_KeyUp(object sender, KeyEventArgs e)
{
flag_isdown = false;
txtletters.BackColor = Color.White;
sw.Stop();
if (sw.ElapsedMilliseconds < 250)
listofcode += ".";
else
listofcode += "-";
sw.Reset();
morse_timer.Start();
}
private void frmdecdotmode_Load(object sender, EventArgs e)
{
morse_timer.Interval = 1000;
morse_timer.Enabled = true;
morse_timer.Tick += morse_timer_Tick;
}
private void morse_timer_Tick(object sender, EventArgs e)
{
if (flag_isdown == false && listofcode != null)
{
datas = dbc.srchfortext(listofcode);
lbltext.DataBindings.Clear();
lbltext.DataBindings.Add("text", datas, "t.letter");
txtletters.Text += lbltext.Text;
listofcode = "";
}
}
}
}
Thanks to every body who helped me do this...
Ya Ali(a.s)

Winforms Progress Bar Visible true false

My code that works:
private void textBox1_TextChanged(object sender, EventArgs e)
{
progressBar1.Visible = true;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
progressBar1.Visible = false;
}
If I add something for the computer to do, as seen in the following code example, the computer does not show the progress bar until it's done doing the computation. What I want it to do is show the progress bar first, then do the computation, then on some other event I want to hide the progress bar. Why can't I do it this way?
private void textBox1_TextChanged(object sender, EventArgs e)
{
progressBar1.Visible = true;
FindPrimeNumber(50000);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
progressBar1.Visible = false;
}
The requested FindPrimeNumber code:
public int FindPrimeNumber(int n)
{
int count = 0;
int a = 2;
while (count < n)
{
int b = 2;
int prime = 1;// to check if found a prime
while (b * b <= a)
{
if (a % b == 0)
{
prime = 0;
break;
}
b++;
}
if (prime > 0)
count++;
a++;
}
return (--a);
}
the FindPrimeNumber code is just something to make the computer do a task for a while, so I can test to see if my progress bar is going to show.
I figured it out. In this example, a user enters a 5 digit number in a text box, then a progress bar shows up on the form as it is processing the number in a math function, then the result is put into a second text box and the progress bar goes away.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.TextLength == 5)
{
progressBar1.Visible = true;
int textFromTextBox1 = Int32.Parse(textBox1.Text);
backgroundWorker1.RunWorkerAsync(textFromTextBox1);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = FindPrimeNumber((int)e.Argument);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
textBox2.Text = e.Result.ToString();
backgroundWorker1.CancelAsync();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
progressBar1.Visible = false;
}
Note: This example does not handle all exceptions, but it works great. As you can probably see in the code I am passing a value into the BackgroundWorker which gets passed into the FindPrimeNumber method, then I am retrieving the result out of the BackgroundWorker.
More notes for newbies:
I have the BackgroundWorker property WorkerSupportsCancellation set to True.
In WinForms, after dropping the BackgroundWorker onto the form, when you double click it, it will generate the DoWorkEventHandler for you, then in the Solution Explorer go to the Events and double click on RunWorkerCompleted so it can generated that for you as well. Otherwise, you will have to do a lot of manual code entry.

C# specified time label change the structure

int sn = 0;
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Konfigürasyon Yükleniyor.";
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sn == 3)
{
label1.Text = "Ayarlar Alınıyor";
}
if (sn == 5)
{
label1.Text = "Program Başlatılıyor";
}
sn++;
timer1.Stop();
}
When I open the form I want to change the label when I select the text range.
I assume that event handler is attached in designer to this timer1.
As far as I can understand, this label is never set, because you stop Timer after it hits first time.
In this case variable sn = 0 so non of if condition from your event handler is met.
I think to solve problem you sould remove this timer1.Stop() from event handler.
You probably want
private void timer1_Tick(object sender, EventArgs e) {
if (sn == 3)
label1.Text = "Ayarlar Alınıyor";
else if (sn == 5) {
label1.Text = "Program Başlatılıyor";
timer1.Stop(); // <- stop timer here on the 5th second, not on the 1st one
}
sn++;
}

C#.Net printing one character of a string at a time in a TextBox

Am new to C# and i need your help on this, I want to display one character at a time in a textbox this is my code
private void timer1_Tick(object sender, EventArgs e)
{
int i = 0; //why does this don't increment when it ticks again?
string str = "Herman Lukindo";
textBox1.Text += str[i];
i++;
}
private void button1_Click(object sender, EventArgs e)
{
if(timer1.Enabled == false )
{
timer1.Enabled = true;
button1.Text = "Stop";
}
else if(timer1 .Enabled == true )
{
timer1.Enabled = false;
button1.Text = "Start";
}
}
why does this don't increment when it ticks again?
Because your variable i is local to your event. You need to define it at class level.
int i = 0; //at class level
private void timer1_Tick(object sender, EventArgs e)
{
string str = "Herman Lukindo";
textBox1.Text += str[i];
i++;
}
On exit of your event, variable i becomes out of scope and looses its value. On the next event it is considered a new local variable with the initialized value of 0.
Next, you should also look for cross threaded exception. Since your TextBox is not getting updated on the UI thread.
The issue with you code is that you are assigning i = 0 with every tick, so it will always be 0 everytime it is used. I would suggest using a class level variable for this.
However, using a variable at class level means you are going to need to reset to 0 at some point, probably each time you start the timer.
A further point is that you are going to want to validate the tick event to ensure you don't try to access an index that doesn't exist (IndexOutOfRangeException). For this I would recommend automatically stopping the timer once the last letter has been printed.
With all that in mind, here is my suggested code:
int i = 0;// Create i at class level to ensure the value is maintain between tick events.
private void timer1_Tick(object sender, EventArgs e)
{
string str = "Herman Lukindo";
// Check to see if we have reached the end of the string. If so, then stop the timer.
if(i >= str.Length)
{
StopTimer();
}
else
{
textBox1.Text += str[i];
i++;
}
}
private void button1_Click(object sender, EventArgs e)
{
// If timer is running then stop it.
if(timer1.Enabled)
{
StopTimer();
}
// Otherwise (timer not running) start it.
else
{
StartTimer();
}
}
void StartTimer()
{
i = 0;// Reset counter to 0 ready for next time.
textBox1.Text = "";// Reset the text box ready for next time.
timer1.Enabled = true;
button1.Text = "Stop";
}
void StopTimer()
{
timer1.Enabled = false;
button1.Text = "Start";
}

Categories