How to stop System.Timers.Timer - c#

I'm using Windows Forms to start a System.Timers.Timer to fire an event every 3 seconds. When I close the form the process keeps firing, and that's fine. The problem happens when I reopen the form to stop the timer on click of a button btnSendOff_Click.
System.Timers.Timer sendTimer = new System.Timers.Timer();
sendTimer.Elapsed += new ElapsedEventHandler(sendProcessTimerEvent);
sendTimer.Interval = 3000;
private void sendProcessTimerEvent(object sender, EventArgs e)
{
MessageBox.Show("Send 3 sec");
}
private void btnSendOn_Click(object sender, EventArgs e)
{
sendTimer.Start();
}
private void btnSendOff_Click(object sender, EventArgs e)
{
sendTimer.Stop();
}
There will be more asynchronous timers on this form. How can I stop this timer when I reopen the form?

The form should not be creating a new timer every time you create a new instance of the form if it needs to keep running after the form closes. The way you have declared the timer, it will create another one each time the form is created. You should put the timer on a different form or declare it in some global module and only make the form activate or deactivate the timer. If the timer needs to keep running when the form is closed, the form should not be the one owning or creating the timer. If the timer doesn't need to keep running when the form is closed, then you should be using a Forms.Timer instead of a System.Timer.
Edit: Add Sample Code
static class Program
{
public static System.Timers.Timer sendTimer;
public static System.Text.StringBuilder accumulatedText;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
sendTimer = new System.Timers.Timer();
accumulatedText = new System.Text.StringBuilder("Started at " + DateTime.Now.ToLongTimeString() + Environment.NewLine);
sendTimer.Interval = 3000;
sendTimer.Elapsed += new System.Timers.ElapsedEventHandler(sendProcessTimerEvent);
Application.Run(new MainForm());
}
static void sendProcessTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
accumulatedText.AppendLine("Pinged at " + DateTime.Now.ToLongTimeString());
}
}
class MainForm : Form
{
ToolStrip mainToolStrip = new ToolStrip();
public MainForm()
{
mainToolStrip.Items.Add("Log Control").Click += new EventHandler(MainForm_Click);
Controls.Add(mainToolStrip);
}
void MainForm_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ShowDialog();
}
}
class Form1 : Form
{
private Button button1 = new Button();
private TextBox text1 = new TextBox();
public Form1()
{
button1.Dock = DockStyle.Bottom;
button1.Text = Program.sendTimer.Enabled ? "Stop": "Start";
button1.Click += new EventHandler(button1_Click);
text1 = new TextBox();
text1.Dock = DockStyle.Fill;
text1.Multiline= true;
text1.ScrollBars = ScrollBars.Vertical;
text1.Text = Program.accumulatedText.ToString();
Controls.AddRange(new Control[] {button1, text1});
}
void button1_Click(object sender, EventArgs e)
{
Program.sendTimer.Enabled = !Program.sendTimer.Enabled;
button1.Text = Program.sendTimer.Enabled ? "Stop" : "Start";
}
}

Related

Hide Form1, show Form2 on Form1_Load

The Form1 of my App is a login page that i want to:
- show on some conditions
- hide and show Form2 on some conditions
I can hide/show a form by the button click event like so,
private void button1_Click(object sender, EventArgs e)
{
Form2 f2= new Form2();
f2.Show();
this.Hide();
}
but the same technique does not work for Form1_Load.
I have tried the first example in this thread,
Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run();
}
Form1
private void Form1_Load(object sender, EventArgs e)
{
Form2 f2= new Form2();
f2.Show();
this.Hide();
}
but it's not showing neither Form1 or Form2, and i don't see how it could. The second example i can't understand how i can implement, and the next google results are even more confusing.
Please help i'm stuck on this for 2 hours.
In the last line in program.cs you must type new Form1() between the parenthesis. So, your program.cs code is as follow:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
C# can not hide form in form_load evant Apparently.
To resolve Hide problem, you can use of a timer and hide the form in tick event. i.e.:
Timer timer = new Timer();
private void timerTick(object sender, EventArgs e)
{
timer.Enabled = false;
this.Hide();
}
private void Form1_Load(object sender, EventArgs e)
{
timer.Tick += new EventHandler(timerTick);
timer.Interval = 10;
Form2 frm = new Form2();
frm.Show();
timer.Enabled = true;
}
This works. I tested it.
I hope this will be useful.
Hello You Can Use This
private void button1_Click(object sender, EventArgs e)
{
Form2 f2= new Form2();
if(condition==true)
{
this.Hide();
f2.ShowDialog();
this.Close();
}
}
Why don't you reverse the order of your forms? Start with the main form in the main method.
Application.Run(new Form2());
Now in the constructor of Form2 call the login form with ShowDialog and set the result of the login in a global variable inside the Form2
public class Form2:Form
{
private bool _isValidated = false;
public Form2()
{
InitializeComponent();
// Add here the conditions to check if you don't want to
// run the login process...
// if(loginNotRequired)
// _isValidated = true;
// else
using(Form1 fLogin = new Form1())
{
// This blocks until the user clicks cancel or ok buttons
DialogResult dr = fLogin.ShowDialog();
if(dr == DialogResult.OK)
_isValidated = true;
}
}
Now in the Form2.Load event check the status of your login and close the Form2 if the login is not successful
private void Form2_Load(object sender, EventArgs args)
{
if(!_isValidated)
this.Close();
else
.....
}

Automatically hide one form in C# after many second and show another form

I need to hide current form after many second and then show any form
I'm writing this code but it doesn't work.
namespace tempprj
{
public partial class ProfileFrm : Telerik.WinControls.UI.RadForm
{
public ProfileFrm()
{
InitializeComponent();
}
private void ProfileFrm_Load(object sender, EventArgs e)
{
Frm2 child = new Frm2();
Thread.Sleep(3000);
this.Hide();
child.ShowDialog();
}
}
}
Thread.Sleep(3000);
is going to prevent your project from doing anything at all for 3 seconds (not counting other threads) and freeze the UI. I suggest using the standard .NET timer.
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
This is a solution to my question:
private void ProfileFrm_Load(object sender, EventArgs e)
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
timer1.Interval = 4000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
this.Hide();
Frm2 f = new Frm2();
f.ShowDialog();
}

Timer in C# that fires X seconds after opening program?

How can I run a function, after 10 seconds, after the opening of the program.
This is what I tried, and I'm not able to make it work.
private void button1_Click(object sender, EventArgs e)
{
Timer tm = new Timer();
tm.Enabled = true;
tm.Interval = 60000;
tm.Tick+=new EventHandler(tm_Tick);
}
private void tm_Tick(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
You have a few problems:
You need to use the Load event rather than a button click handler.
You should set the interval to 10000 for a 10 second wait.
You are using a local variable for the timer instance. That makes it hard for you to refer to the timer at a later date. Make the timer instance be a member of the form class instead.
Remember to stop the clock after you run the form, or, it will try to open every 10 seconds
In other words, something like this:
private Timer tm;
private void Form1_Load(object sender, EventArgs e)
{
tm = new Timer();
tm.Interval = 10 * 1000; // 10 seconds
tm.Tick += new EventHandler(tm_Tick);
tm.Start();
}
private void tm_Tick(object sender, EventArgs e)
{
tm.Stop(); // so that we only fire the timer message once
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
Is will be good for your program something like that?
namespace Timer10Sec
{
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(After10Sec));
t.Start();
}
public static void After10Sec()
{
Thread.Sleep(10000);
while (true)
{
Console.WriteLine("qwerty");
}
}
}
}

Bring already opened winform application to front without API?

Hi,
Say that we got a WinForm application(app1) running in the background, now another application(app2)(the topmost active application) trigger a startProcess with the app1.
Now I need app1 to use the existing instance and bring it to topmost application(not only within the app1 application).
I have found this : http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
Is it true that its not possible to do this without API? I have looked att bringToFront, Activate and Focus but all these does seem to only effect within a application and not between applications?
I don't know what you mean "without API" or why that matters.
However the simplest way is via WindowsFormsApplicationBase. It gives you all you need, with just a few lines of code.
You need to add a reference to the Microsoft.VisualBasic assembly - but it can be used through C#.
Make this class:
public class SingleInstanceApplication : WindowsFormsApplicationBase
{
private SingleInstanceApplication()
{
IsSingleInstance = true;
}
public static void Run(Form form)
{
var app = new SingleInstanceApplication
{
MainForm = form
};
app.StartupNextInstance += (s, e) => e.BringToForeground = true;
app.Run(Environment.GetCommandLineArgs());
}
}
And in your Program.cs, change the run line to use it:
//Application.Run(new Form1());
SingleInstanceApplication.Run(new Form1());
You really need some sort of communications between 2 apps. In article link to you posted communications is through WinApi messages. Also you can do that through sockets or through files and FileWatchers.
UPD1:
Code to simulate minimize with timer simulation message from another app and maximize on that message:
public partial class Form1 : Form
{
private Timer _timer = null;
public Form1()
{
InitializeComponent();
this.Load += OnFormLoad;
}
private void OnFormLoad(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Hide and top most on timer";
btn.Width = 200;
btn.Click += OnButtonClick;
this.Controls.Add(btn);
}
private void OnButtonClick(object sender, EventArgs e)
{
//minimize app to task bar
WindowState = FormWindowState.Minimized;
//timer to simulate message from another app
_timer = new Timer();
//time after wich form will be maximize
_timer.Interval = 2000;
_timer.Tick += new EventHandler(OnTimerTick);
_timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
_timer.Stop();
//message from another app came - we should
WindowState = FormWindowState.Normal;
TopMost = true;
}
}

progressbar and Data loading

i have Windows Form in C# having Datagridview with large no. of records from database and some comboboxes,textbox and buttons.
so,i used another form having progressbar and backgroundworker so that data loading of mainform does not iritate enduser.
public partial class FirstForm : Form
{
MainForm mf;
public FirstForm()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mf = new MainForm(); //inside constructor,code of data loading in gridview
mf.Update();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (p1.Value < p1.Maximum) //p1 name for progressbar
p1.Value++;
else
{
timer1.Enabled = false;
this.Hide();
mf.Show();
}
}
}
but when main form is displayed,it is blank and after 2/3 seconds datagridview and other controls appear.
how to solve this..?
or suggest other ideas to solve this problem.
Remove your code in Firstform and write mine in
programs.cs
static void Main()
{
Application.EnableVisualStyles();
Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.SetCompatibleTextRenderingDefault(false);
System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
MainForm = new MainForm(); // creating main form
bw.RunWorkerAsync();
frm.Inittiate(); // Add this method to first form to loading and initiating
bw.CancelAsync(); // ending splashing
Application.Run(frm);
}
static void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
AFirstForm splashForm = new FirstForm();
splashForm.TopMost = true;
splashForm.Show();
while (!(sender as System.ComponentModel.BackgroundWorker).CancellationPending)
{
splashForm.Refresh();
}
splashForm.Close();
e.Result = splashForm;
}

Categories

Resources