【问题标题】:Is there a way to make a button press recursive in C# (press itself again)? [duplicate]有没有办法在 C# 中使按钮按下递归(再次按下自身)? [复制]
【发布时间】:2019-09-18 22:01:03
【问题描述】:

我想让一个按钮运行一些代码,然后在 Windows 窗体中再次按下它自己。

当我调用按钮本身时出现错误:

 System.StackOverflowException
       HResult=0x800703E9
       Source=<Cannot evaluate the exception source>
       StackTrace:
     <Cannot evaluate the exception stack trace>

我想制作一个资源监控程序来熟悉C#。现在我被困在字符串处理和显示不断变化的字符串上。 我使用随机生成的数字作为占位符,我想永久显示和更改它,模仿真实的数据拉取。

我的代码:

public void Start_Click(object sender, EventArgs e){
      var usage =new CpuUsage(); //placeholder class for getting the CPU use data
      usage.setCPU(); //gets a random number
      this.CPU.Text = usage.cpuUsage; //show the usage data on a textbox
      Start_Click(null, EventArgs.Empty); //call this button again here
}

我想要得到的东西看起来像:

  1. 获取数据
  2. 使用文本框显示数据
  3. 重做这个

【问题讨论】:

  • 这不是一个好主意。如果您想获取重复的随机数据来更新表单上的字段,请查看this answer 了解更多信息
  • 轮询是术语,而不是拉动。并且按钮不是正确的工具。使用计时器。理想情况下是 Windows 窗体计时器。一键点击启动计时器。 Anotehr 阻止了它。每一个滴答声,你都在做你的工作。只要你把invervall至少保持在两位数,而且这个过程快了一半,就没什么好担心的了。

标签: c# recursion button windows-forms-designer


【解决方案1】:

我认为您正在寻找的是Timer 控件。您可以将其设置为以某个时间间隔运行,并定义以该时间间隔运行的代码。如果您只想在按下按钮时启动它,您还可以控制定时器的启动和停止。

例如,在表单上放置一个Timer 控件并尝试以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    // Set the interval to how often you want it to execute
    timer1.Interval = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
    // Set a method to run on every interval
    timer1.Tick += Timer1_Tick;
}

public void Start_Click(object sender, EventArgs e)
{
    // start or stop the timer
    timer1.Enabled = !timer1.Enabled;

    // Above we are just flipping the 'Enabled' property, but
    // you could also call timer1.Start() (which is the same as 
    // setting 'Enabled = true') or timer1.Stop() (which is
    // the same as setting 'Enabled = false')
}

// Put code in this method that should execute when the timer interval is reached
private void Timer1_Tick(object sender, EventArgs e)
{
    var usage = new CpuUsage(); //placeholder class for getting the CPU use data
    usage.setCPU(); //gets a random number
    this.CPU.Text = usage.cpuUsage; //show the usage data on a textbox
}

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2019-10-04
    • 2020-06-08
    相关资源
    最近更新 更多