Textbox not displaying text and UI screen not moving - c#

This is my requirement I have to use while loop inside timer, after launch application after click on button UI is locked not able to move and text is not diplaying at textbox too
below is the code
using System;
using System.Windows.Forms;
namespace WinScreenLocked
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int Number = 0;
private void timer1_Tick(object sender, EventArgs e)
{
while (true)
{
textBox1.Text = Number.ToString();
Number++;
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
}
}

// Create a 30 min timer
timer = new System.Timers.Timer(1800000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// do stuff
}
with the usual caveats of: timer won't be hugely accurate and might need to GC.KeepAlive(timer)
See also: Why does a System.Timers.Timer survive GC but not System.Threading.Timer?

you can stop the thread to block the ui i.e using
System.Threading.Thread.Sleep(2000);
it takes miliseconds in above 2000 miliseconds is equal to 2 seconds.

Seeing as this is winforms you can use Application.DoEvents() to process the UI refresh.
See this : https://social.msdn.microsoft.com/Forums/en-US/b1b1969d-8a51-496c-9274-a0ac1708a8b4/what-does-applicationdoevents-actually-do?forum=csharplanguage

Related

How to use timer to click buttons in C#

How to use timers to trigger click button event every 3 seconds?
I'm trying to rotate 2 pictures in pictureboxes by triggering the rotate button automaticly using timer but it seems doesnt works. I never used timer before so this is my first time. Anyone know whats wrong with my code or any other code suggestion for it? Thanks
Code I'm using
private void timer1_Tick(object sender, EventArgs e)
{
rotateRightButton_Click(null, null);
pictureBox1.Refresh();
pictureBox2.Refresh();
}
private void timerStartButton_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timerStopButton_Click(object sender, EventArgs e)
{
timer1.Stop();
}
It's even possible (and more simple) with tasks
public partial class Form1 : Form
{
// variable to keep track if the timer is running.
private bool _timerRunning;
public Form1()
{
InitializeComponent();
}
private async Task StartTimer()
{
// set it to true
_timerRunning = true;
while (_timerRunning)
{
// call the rotateRightButton_Click (what you want)
rotateRightButton_Click(this, EventArgs.Empty);
pictureBox1.Refresh();
pictureBox2.Refresh();
// wait for 3 seconds (but don't block the GUI thread)
await Task.Delay(3000);
}
}
private void rotateRightButton_Click(Form1 form1, EventArgs empty)
{
// do your thing
}
private async void buttonStart_Click(object sender, EventArgs e)
{
// if it's already started, don't start it again.
if (_timerRunning)
return;
// start it.
await StartTimer();
}
private void buttonStop_Click(object sender, EventArgs e)
{
// stop it.
_timerRunning = false;
}
}
timer1.Interval = 3000; // set interval to 3 seconds and then call Time Elapsed event
timer1.Elapsed += Time_Elapsed;
//Event
private void Time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// will be triggered in every 3 seconds
rotateRightButton_Click(null, null);
pictureBox1.Refresh();
pictureBox2.Refresh();
}
Hope this helps!

moving a button using a timer

I have four buttons that are called "ship1,ship2" etc.
I want them to move to the right side of the form (at the same speed and starting at the same time), and every time I click in one "ship", all the ships should stop.
I know that I need to use a timer (I have the code written that uses threading, but it gives me troubles when stopping the ships.) I don't know how to use timers.
I tried to read the timer info in MDSN but I didn't understand it.
So u can help me?
HERES the code using threading.
I don't want to use it. I need to use a TIMER! (I posted it here because it doesnt give me to post without any code
private bool flag = false;
Thread thr;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
flag = false;
thr = new Thread(Go);
thr.Start();
}
private delegate void moveBd(Button btn);
void moveButton(Button btn)
{
int x = btn.Location.X;
int y = btn.Location.Y;
btn.Location = new Point(x + 1, y);
}
private void Go()
{
while (((ship1.Location.X + ship1.Size.Width) < this.Size.Width)&&(flag==false))
{
Invoke(new moveBd(moveButton), ship1);
Thread.Sleep(10);
}
MessageBox.Show("U LOOSE");
}
private void button1_Click(object sender, EventArgs e)
{
flag = true;
}
Have you googled Windows.Forms.Timer?
You can start a timer via:
Timer timer = new Timer();
timer.Interval = 1000; //one second
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.Start();
You'll need an event handler to handle the Elapsed event which is where you'll put the code to handle moving the 'Button':
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MoveButton();
}

How to set time interval to button_click in C# windows form application

Here the below code enables the particular bit as high in parallel port.How to set time interval for the button click in windows form.If i set the time interval to 2 seconds the timer should start then 2 seconds after that it should stop automatically.
private void button1_Click(object sender, EventArgs e)
{
PortAccess.Output(888,1);
}
can u please let me know any suggestion or example to do this.Inside this button_click.
So you just want to clear the bit 2 seconds later? Something like this should work:
private void button1_Click(object sender, EventArgs e)
{
// Prevent multiple button clicks
button.Enabled = false;
PortAccess.Output(888, 1);
Timer timer = new Timer { Interval = 2000 };
timer.Tick += HandleTimerTick;
timer.Start();
}
private void HandleTimerTick(object sender, EventArgs e)
{
Timer timer = (Timer) sender;
timer.Stop();
timer.Dispose();
button.Enabled = true;
PortAccess.Output(888, 0);
}
You may find it simpler to set up the timer just once, and store it as an instance variable. Then you could attach the Tick event and set the interval on construction, and add it to the components of the form so that it's automatically disposed. Your methods would then be:
private void button1_Click(object sender, EventArgs e)
{
button.Enabled = false;
PortAccess.Output(888, 1);
timer.Start();
}
private void HandleTimerTick(object sender, EventArgs e)
{
timer.Stop();
button.Enabled = true;
PortAccess.Output(888, 0);
}

how do I delay action on mouse enter rectangle c#

I would like to delay an action by several seconds after a mouse pointer has entered and remained for period of time in a winform graphics rectangle. What would be a way to do this?
Thanks
c#, .net 2.0, winform
private Timer timer;
private void rect_MouseEnter(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = 3000;
timer.Start();
timer.Tick += new EventHandler(t_Tick);
}
private void rect_MouseLeave(object sender, EventArgs e)
{
timer.Dispose();
}
void t_Tick(object sender, EventArgs e)
{
timer.Dispose();
MessageBox.Show(#"It has been over for 3 seconds");
}
Something such as:
static void MouseEnteredYourRectangleEvent(object sender, MouseEventArgs e)
{
Timer delayTimer = new Timer();
delayTimer.Interval = 2000; // 2000msec = 2 seconds
delayTimer.Tick += new ElapsedEventHandler(delayTimer_Elapsed);
}
static void delayTimer_Elapsed(object sender, EventArgs e)
{
if(MouseInRectangle())
DoSomething();
((Timer)sender).Dispose();
}
Probably could be done more efficiently, but should work :D
Two ways to set up MouseInRectangle -> one is to make it get the current mouse coordinates and the position of the control and see if it's in it, another way would be a variable which you would set to false on control.mouse_leave.
Try using the Timer control (System.Windows.Forms.Timer).
Please notice System.Windows.Forms.Timer is not Exact and you cannot rely it will act on exactly the interval given.
it would be prefeable to use System.Times.timer and use the Invoke action to return to the GUI thread.

C# Simple Countdown - What am I doing wrong?

I wanted to make a simple Countdown-Application with C# to show as an example.
For the very first and basic version I use a Label to display the current time left in seconds and a Button to start the countdown. The Button's Click-Event is implemented like this:
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 60;
while (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
System.Threading.Thread.Sleep(1000);
}
}
Now when the user clicks the Button the time is actually counted down (as the application freezes (due to Sleep())) for the chosen amount of time but the Label's context is not refreshed.
Am I doing something generally wrong (when it comes to Threads) or is it just a problem with the UI?
Thank you for your answers!
I now use a System.Windows.Threading.DispatcherTimer to do as you told me. Everything works fine so this question is officially answered ;)
For those who are interested: Here is my code (the essential parts)
public partial class WindowCountdown : Window
{
private int _time;
private DispatcherTimer _countdownTimer;
public WindowCountdown()
{
InitializeComponent();
_countdownTimer = new DispatcherTimer();
_countdownTimer.Interval = new TimeSpan(0,0,1);
_countdownTimer.Tick += new EventHandler(CountdownTimerStep);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 10;
_countdownTimer.Start();
}
private void CountdownTimerStep(object sender, EventArgs e)
{
if (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
}
else
_countdownTimer.Stop();
}
}
Yes, event handlers should not block - they should return immediately.
You should implement this by a Timer, BackgroundWorker or Thread (in this order of preference).
What you are seeing is the effect of a long-running message blocking the windows message queue/pump - which you more commonly associate with the white application screen and "not responding". Basically, if your thread is sleeping, it isn't responding to messages like "paint yourself". You need to make your change and yield control to the pump.
There are various ways of doing this (ripper234 does a good job of listing them). The bad way you'll often see is:
{ // your count/sleep loop
// bad code - don't do this:
Application.DoEvents();
System.Threading.Thread.Sleep(1000);
}
I mention this only to highlight what not to do; this causes a lot of problems with "re-entrancy" and general code management. A better way is simply to use a Timer, or for more complex code, a BackgroundWorker. Something like:
using System;
using System.Windows.Forms;
class MyForm : Form {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
Timer timer;
MyForm() {
timer = new Timer();
count = 10;
timer.Interval = 1000;
timer.Tick += timer_Tick;
timer.Start();
}
protected override void Dispose(bool disposing) {
if (disposing) {
timer.Dispose();
}
base.Dispose(disposing);
}
int count;
void timer_Tick(object sender, EventArgs e) {
Text = "Wait for " + count + " seconds...";
count--;
if (count == 0)
{
timer.Stop();
}
}
}

Categories

Resources