need a timer for my C# morse converter - c#

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)

Related

How to use check a Button in another Button statement? c#

I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}

Stop and repeat process by using a timer in C# Windows Form

I am trying to use a timer to achieve a sort of old animation used in the past to show that a process is running.
The way I would like to do that is by adding dots to a sentence (in a label control), for example:
"Process is running." to "Process is running.." and "Process is running..." with a limit of 3 dots and then revert back to a single dot.
I am not sure as to the fact using a timer here would be the best choice, but I thought it should work fine for such a simple example.
The code I used is as follows:
public string InitialProcessText;
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
//InitialProcessText = ProcessLbl.Text;
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
ProcessTimer.Stop();
}
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
//For every two ticks, ProcessLbl.Text = InitialProcessText
ProcessLbl.Text += ".";
}
What could I add to set a limit of adding 2 dots and then remove the dots and add dots again (I would assume to do this in the ProcessTimer_Tick method)?
You can just use your _ticks variable:
private readonly int _ticksPerUpdate = 2;
private readonly int _maxNumberOfDots = 3;
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
if(_ticks == (_ticksPerUpdate * (_maxNumberOfDots + 1)))
{
_ticks = 0;
ProcessLbl.Text = InitialProcessText;
}
else if(_ticks % _ticksPerUpdate == 0)
{
ProcessLbl.Text += ".";
}
}
Remember to reset the ticks counter every time you start the timer:
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
InitialProcessText = ProcessLbl.Text;
// reset the variable
_ticks = 0
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
I assume that _ticks counts the number of ticks. You could then go :
if(ticks%3 == 0)
{
ProcessLbl.Text = "Application is now running."
}
else
{
ProcessLbl.Text+=".";
}
Then, at 1st tick, 1%3=1 so it adds a dot, at 2nd tick, 2%3=2 so it adds a dot and 3rd tick, 3%3=0, so it gets back to original.
Just because...here's another approach:
private void ProcessTimer_Tick(object sender, EventArgs e)
{
ProcessLbl.Text = ProcessLbl.Text.EndsWith("...") ? ProcessLbl.Text.TrimEnd(".".ToCharArray()) + "." : ProcessLbl.Text + ".";
}

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

axWindowsMediaPlayer1_PlayStateChange event not working

i want to play automatically next song in my player. I have use windows media player object.
this is my code.
private void timer2_Tick(object sender, EventArgs e)
{
if (songList.SelectedIndex < files.Length - 1)
{
songList.SelectedIndex++;
timer2.Enabled = false;
}
else
{
songList.SelectedIndex = 0;
timer2.Enabled = false;
}
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer2.Interval = 100;
timer2.Enabled = true;
}
}
but it's not working i have chacked timer code it is working but i think axWindowsMediaPlayer1_PlayStateChange event not working and in the designer code when i wrote this line for axWindowsMediaPlayer
this.axWindowsMediaPlayer1.PlayStateChange += new System.EventHandler(this.axWindowsMediaPlayer1_PlayStateChange);
it shows this error:
No overload for axWindowsMediaPlayer1_PlayStateChange matches delegate System.EventHandler
is there any solution?
Take a look at the documentation for PlayStateChange. It gives you a clear example.
Rather than using what you have, simply use this event assignment instead:
axWindowsMediaPlayer1.PlayStateChange +=
new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(axWindowsMediaPlayer1_PlayStateChange);

Countdown after clicking a button that goes from 10 to 0 setting text on a label C#

My problem is very simple but I can't figure it out, so I need your help.
The problem is that I have a button and a label in a form, I simply want to click the button and see the label countdown from 10 to 0 and after that happens the form closes, that simple, can someone help me with this?
BTW, my real app is a form that shows video in real time from my webcam and the idea is to click the button, see the count down and when it finishes the appp saves the current frame as an image.
Thanks in advice!
It sounds like you probably just need three things:
A counter in your class as an instance variable
A timer (System.Windows.Forms.Timer or a DispatcherTimer depending on what UI framework you're using)
A method handling the timer's Tick even which decrements the counter, updates the UI, and stops the timer + takes a snapshot if the counter reaches 0
You can do all of this without any other threads.
Using WindowsFormsApplication u can do it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = false; // Wait for start
timer1.Interval = 1000; // Second
i = 10; // Set CountDown Maximum
label1.Text = "CountDown: " + i; // Show
button1.Text = "Start";
}
public int i;
private void button1_Click(object sender, EventArgs e)
{
// Switch Timer On/Off
if (timer1.Enabled == true)
{ timer1.Enabled = false; button1.Text = "Start"; }
else if (timer1.Enabled == false)
{ timer1.Enabled = true; button1.Text = "Stop"; }
}
private void timer1_Tick(object sender, EventArgs e)
{
if (i > 0)
{
i = i - 1;
label1.Text = "CountDown: " + i;
}
else
{ timer1.Enabled = false; button1.Text = "Start"; }
}
}
You only need a label, a button and a timer.
use this code. put one timer,label and button.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
}
private static int i = 10;
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "10";
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = (i--).ToString();
if (i < 0)
{
timer1.Stop();
}
}
}

Categories