Single output on timer c# - c#

I'm a beginner and trying to understand what timer is and how can I use it. I'll be really grateful to you if you replied to my question.
I have a timer called "Elapsed_Time" and I set the interval to 1000 millisecond.
What I wanted to achieve is to show my message: "Hi just once" just once instead of showing it for every 1 second.
private void Elapsed_Time_Tick(object sender, EventArgs e)
{
Messagebox.show("Hi just once");
}

if you still want the timer's Tick event to fire then try this...
private bool _hasTicked = false;
private void Elapsed_Time_Tick(object sender, EventArgs e)
{
if(!_hasTicked)
{
Messagebox.show("Hi just once");
_hasTicked = true;
}
}

private void Elapsed_Time_Tick(object sender, EventArgs e)
{
Messagebox.show("Hi just once");
Elapsed_Time_Tick.Enabled = false;
}
You can do like this

Related

C# If messagebox is displayed, then stop timer

When I write something wrong on a textbox and click a button, a messagebox pops up, and keeps popping up since I have a timer.
So I want to make an if statement that if the messagebox is displayed, then stop the timer, until the button is clicked once again.
I tried using this:
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
if (errormsg)
{
timer1.Stop();
}
data();
}
private void data()
{
//code
Now here's what's in my timer1 code:
private void timer1_Tick(object sender, EventArgs e)
{
int value;
if (int.TryParse(textBox1.Text, out value))
{
if (value > 0)
{
timer1.Interval = value;
}
}
button1.PerformClick();
}
here's the error message:
private void errormsg()
{
MessageBox.Show("Sorry, there was an error. Please, try again.");
}
I will also note that I'm using errormsg in an else statement on my //code
//code
else
{
errormsg();
}
So my question is:
How can I make the timer stop, if a wrong value is displayed on my textbox (//code) causing a messagebox to appear. Then, when a correct value is displayed on a textbox, and I click the button, the timer would start again?
Stop the timer in your errormsg() function. When you clicked the button1 it starts again.
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
data();
}
private void errormsg()
{
timer1.stop();
MessageBox.Show("Sorry, there was an error. Please, try again.");
}

Check if user writes text in textbox

I am programming a chat in C# and I need a function to check if text in textbox is changed. It can be done with TextChanged event but I need to check it only at start of writing.
private void messageText_TextChanged(object sender, TextChangedEventArgs e)
{
chatApp.WriteChatLine(userName + "is typping...");
}
This code writes a chat message every time the text is changed. How to restrict it only for the first time when the user started to write a text into a textbox? I am sorry if this is a stupid question but I can't get it working. Thank you for help!
You can unsubscribe from event handler:
private void messageText_TextChanged(object sender, TextChangedEventArgs e)
{
chatApp.WriteChatLine(userName + "is typping...");
messageText.TextChanged -= messageText_TextChanged;
}
This event handler will be executed once, and then removed from handlers list. Thus further changes of text will not fire event (if there is no other subscribers) or this particular handler will not be executed.
UPDATE: As #karim noted, you will probably need to automatically reset this message after message is sent, or user stopped typing, or user deleted everything. It can be done with timer component (set it's Interval to value you want typing message be displayed after user stopped typing)
private void messageText_TextChanged(object sender, TextChangedEventArgs e)
{
// if timer already running, then don't update status
if (!timer.Enabled)
chatApp.WriteChatLine(userName + "is typping...");
timer.Stop(); // restart timer
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
ClearStatus();
}
private void buttonSend_Click(object sender, EventArgs e)
{
// send message
ClearStatus();
}
private void ClearStatus()
{
chatApp.WriteChatLine(""); // some code which clears status message
timer.Stop(); // stop timer
}
You can simplify this code, by creating property which will handle status update and timer starting/stopping:
private void messageText_TextChanged(object sender, TextChangedEventArgs e)
{
IsUserTyping = true;
}
private void timer_Tick(object sender, EventArgs e)
{
IsUserTyping = false;
}
private void buttonSend_Click(object sender, EventArgs e)
{
// send message
IsUserTyping = false;
}
private bool IsUserTyping
{
get { return timer.Enabled; }
set {
if (value)
{
if (!IsUserTyping)
chatApp.WriteChatLine(userName + "is typping...");
timer.Stop();
timer.Start();
}
else
{
timer.Stop();
chatApp.WriteChatLine("");
}
}
}
You could have a sentinel variable to detect if the change has already fired once or not, something like so:
bool textboxChanged = false;
private void messageText_TextChanged(object sender, TextChangedEventArgs e)
{
if(!textboxChanged) //if not changed
{
chatApp.WriteChatLine(userName + "is typping...");
}
}
So the event still gets fired but it won't do anything until you change the sentinel variable. This has the extra value of allowing you to reset the sentinel variable later on if need be without having to worry about resubscribing to the event.
The simplest version would be
bool wasUserTyping = false;
private void messageText_KeyUp(object sender, KeyEventArgs e){
wasUserTyping = true;
}
private void messageText_TextChanged(object sender, TextChangedEventArgs e){
if(wasUserTyping){
//Yaaay!! User did type
}
}

C# how to show message after specific time period

In my project I would like to show message or call methods after 5 minutes for example, If the users didn't click on specific button, I wrote this code
Boolean flage = false;
private void button1_Click(object sender, EventArgs e)
{
Timer Clock;
Clock = new System.Windows.Forms.Timer();
Clock.Interval = 1000;
Clock.Start();
Clock.Tick += new EventHandler(Timer_Tick);
}
public void Timer_Tick(object sender, EventArgs eArgs)
{
if (flage == false)
{
MessageBox.Show("after period of time ");
}
}
private void button2_Click(object sender, EventArgs e)
{
flage = true;
}
Its keeping show the messageBox can any body help me.
Your Timer Clock variable is on the stack and ceases to exist when the function exits.
Try making it a member of the class.

Running a method in BackGroundWorker and Showing ProgressBar

What I want is when some method is doing some task UI keeps itself active and I want to show the progress of the work in a progress-bar.
I have a method, a BackGroundWorker and a Progressbar. I want to call the method when BackGroundWorker starts running and show the progress. The method contains a loop. So, it can report the progress.
So, what can be done?
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.TBLMARKET' table. You can move, or remove it, as needed.
myBGWorker.WorkerReportsProgress = true;
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
parseFiles();
}
private void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
}
private void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void parseButton_Click(object sender, EventArgs e)
{
myBGWorker.RunWorkerAsync();
}
public void parseFiles()
{
for()
{
//parsing
myBGWorker.ReportProgress(...);
}
}
But it's not working. The Progressbar is not updating. Only a small progress is showing after the MessageBox "Done".
Instead of using one ParseFiles method (which should depend on myBGWorker) use loop and method which parse one file. Report progress percentage in that loop:
private void parseButton_Click(object sender, EventArgs e)
{
parseButton.Enabled = false;
myBGWorker.RunWorkerAsync();
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
for(int i = 0; i < filesCount; i++)
{
ParseSingleFile(); // pass filename here
int percentage = (i + 1) * 100 / filesCount;
myBGWorker.ReportProgress(percentage);
}
}
void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
}
void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
parseButton.Enabled = true;
MessageBox.Show("Done");
}
To. soham.m17
using with sender argument
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
for(int i = 0; i < filesCount; i++)
{
ParseSingleFile(); // pass filename here
int percentage = (i + 1) * 100 / filesCount;
worker.ReportProgress(percentage); // use not myBGWorker but worker from sender
}
}
I am sorry about the question. Actually the code works fine. It was not showing the Progressbar as the argument in myBGWorker.ReportProgress() was fraction and not percentage. So, it was not showing it. Sorry for the inconvenience.
Moderator may delete this thread. Otherwise it can be a tutorial for others.

Issue with screen capture

I have a button on which a click and it takes a screenshot which i display in my Picture Box. I dont face issue with this code:
private void btnScreenShot_Click(object sender, EventArgs e)
{
btnSave.Visible = true;
sendto_bmpbox.Image = CaptureScreen();
}
However when i loop the entire Form freezes and i cannot click on anything:
private void btnScreenShot_Click(object sender, EventArgs e)
{
// Freezes here
btnSave.Visible = true;
while(flag == 0)
{
sendto_bmpbox.Image = CaptureScreen();
}
}
How do i fix this problem?
That's because your while() is infinite. What makes flag change from capture to capture?
In case you want to infinitely capture the screen - never use the main thread for such things, as it will cause it to hang and prevent your application from updating the UI.
Use the BackgroundWorker class for things like that, you can use this example.
private void button1_Click(object sender, EventArgs e)
{
btnSave.Visible = true;
Thread thread = new Thread(new ThreadStart(threadWork));
thread.Start();
}
int flag = 0;
private void threadWork()
{
while (flag == 0)
{
UpdateImage();
}
}
private void UpdateImage()
{
if (this.InvokeRequired)
{
this.Invoke(UpdateImage);
}
else
{
sendto_bmpbox.Image = CaptureScreen();
}
}
Try Application.DoEvents in loop. I think this can help you...
private void btnScreenShot_Click(object sender, EventArgs e)
{
// Freezes here
btnSave.Visible = true;
while(flag == 0)
{
Application.DoEvents();
sendto_bmpbox.Image = CaptureScreen();
}
}

Categories