问题
A label in form is displaying the count of timer. Now i want to stop,start and reset it using form 2. How can i do this.plz help
回答1:
Forms are just classes, and the timer on Form 2 is an object inside that class.
You can change the Modifiers
property of your timer to public, and then instantiate Form 2 inside Form 1, call the Show()
method of Form 2, and then access your timer object which is now public.
So you have a project with 2 forms like so:
Create a button in Form 1 like so:
Place a timer object on Form 2 and change the access modifier like so:
Then put the following code under your button in form one:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.timer1.Enabled = true;
}
Now you can launch form 2 and access all of the properties on the timer on form 2 from form 1.
Does this help?
回答2:
If the timer object resides in Form1, then create a public property for it:
public Timer Form1Timer { get { return timer1; } }
Then you can access this timer by having a reference to Form 1 in Form 2. You can do this by passing it in to the constructor, or having a set property on Form2. Once you have a reference to Form1, you can simply call methods on the timer:
Form1.Form1Timer.Start();
You can always create a singleton out of Form1 if you cannot pass a reference of it to Form2.
Declare your singleton:
private static Form1 _singleton
Initialize your singleton if it isnt already, and return it:
public static Form1 Singleton
{
get { _singleton ?? (_singleton = new Form1()); }
}
For best practices, make your Form1 constructor private. This of course will not work if Form1 does not have a default constructor (parameterless).
Then in Form2:
Form1.Singleton.Form1Timer.Start();
回答3:
Do this
static Form1 _frmObj;
public static Form1 frmObj
{
get { return _frmObj; }
set { _frmObj = value; }
}
On Form load
private void Form1_Load(object sender, EventArgs e)
{
frmObj= this;
}
Access form and it's controls from another form
Form1.frmObj.timer1.Stop();
来源:https://stackoverflow.com/questions/11364032/control-timer-in-form-1-from-form-2-c-sharp