You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#跨窗体控制:如何在Form1中停止Form2启动的Timer

问题解决:在Form1中停止Form2启动的Timer

问题背景

已实现从Form2启动Timer并在Form1显示倒计时的功能,现需在Form1中停止该Timer。尝试过Form1.instance.Timer.Stop()但未成功。

原代码

Form1代码:

public static Form1 instance;
public Label tb1;
// public Timer tm1;
public Form1()
{
    InitializeComponent();
    instance = this;
    tb1 = labelCountdown;
}

private void buttonStopSTD_Click(object sender, EventArgs e) // Stops the Shutdown
{
    Process.Start("shutdown", "-a");
}

Form2代码:

private void button10m_Click(object sender, EventArgs e)
{
    seconds = Convert.ToInt32(600);
    timer1.Start();
    Process.Start("shutdown", "/s /t 600");
}

private void timer1_Tick(object sender, EventArgs e) // Timer
{
    string off = "Shutdown not set";
    if (seconds < 1) // If Timer hits 0 it turns the Timer off and prints "Shutdown not set"
    {
        timer1.Stop();
        labelCdown.Text = off;
        Form1.instance.tb1.Text = ("Shutdown not set");
    }
    else // If the Timer is above 0 it normally works
    {
        TimeSpan time = TimeSpan.FromSeconds(seconds--);
        string str = time.ToString(@"hh\:mm\:ss");
        labelCdown.Text = str;
        Form1.instance.tb1.Text = ("Shutdown in: " + str);
    }
}

问题原因

timer1是Form2的私有成员,Form1没有权限直接访问并调用其Stop()方法,这就是之前尝试失败的核心原因。

解决方案

方案1:封装停止方法(推荐,符合面向对象封装原则)

在Form2中添加一个公共方法,专门用来停止Timer并更新界面,避免直接暴露Timer实例:

  1. 修改Form2代码,添加公共方法并设置静态实例:
public static Form2 instance;
private int seconds;

public Form2()
{
    InitializeComponent();
    instance = this;
}

// 新增公共停止方法
public void StopCountdown()
{
    timer1.Stop();
    seconds = 0;
    string offText = "Shutdown not set";
    labelCdown.Text = offText;
    Form1.instance.tb1.Text = offText;
}

// 保留原有的button10m_Click和timer1_Tick方法
  1. 修改Form1的停止按钮事件,调用Form2的公共方法:
private void buttonStopSTD_Click(object sender, EventArgs e)
{
    Process.Start("shutdown", "-a");
    Form2.instance.StopCountdown();
}

方案2:将Timer设为公共成员(简单但不够封装)

如果追求快速实现,可以把Form2的timer1访问修饰符改为public:

  1. 修改Form2中timer1的定义(若为设计器生成,需在Form2.Designer.cs中调整):
public System.Windows.Forms.Timer timer1;
// 同时将seconds改为public,避免下次启动数值异常
public int seconds;
  1. 在Form1的停止按钮事件中直接调用:
private void buttonStopSTD_Click(object sender, EventArgs e)
{
    Process.Start("shutdown", "-a");
    Form2.instance.timer1.Stop();
    Form2.instance.seconds = 0;
    tb1.Text = "Shutdown not set";
}

内容的提问来源于stack exchange,提问作者Killer Skiller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:17:51