【问题标题】:Updating a WinForm label value from code without buttons从没有按钮的代码更新 WinForm 标签值
【发布时间】:2015-10-23 02:30:16
【问题描述】:

我有一个简单的问题,但在任何地方都找不到直接的答案

我有一个 C# 程序,它在用户按下“开始”按钮后执行计数器。所以 1、2、3 等,但增量是在随意不同的持续时间内执行的,即

1 -> [4 秒后] 2 -> [7 秒后] 3 -> 等等

每毫秒检查一次程序

我想在 GUI 上显示一个指示,让用户知道达到的人数

我正在考虑使用“计数器:”一词的标签来获取它

// CounterLabel
// 
this.CounterLabel.Anchor = ((System.Windows.Forms.AnchorStyles)
    ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.CounterLabel.AutoSize = true;
this.CounterLabel.Location = new System.Drawing.Point(1090, 35);
this.CounterLabel.Name = "CounterLabel";
this.CounterLabel.Size = new System.Drawing.Size(58, 17);
this.CounterLabel.TabIndex = 52;
this.CounterLabel.Text = "Counter:";

但是我有两个问题:
1)我是否需要一个只读文本框来承载变化的数字

// 
// CounterValue
//
this.CounterValue.Anchor = ((System.Windows.Forms.AnchorStyles)
    ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.CounterValue.BackColor = System.Drawing.SystemColors.Control;
this.CounterValue.Location = new System.Drawing.Point(1149, 32);
this.CounterValue.Name = "CounterValue";
this.CounterValue.Size = new System.Drawing.Size(84, 22);
this.CounterValue.TabIndex = 53;
this.CounterValue.ReadOnly = true;
//this.CounterValue.Text += this.GetCounterValue();

或者有办法只使用标签吗?
2)如何执行控件来查看是否要更新UI?我的意思是,每毫秒检查一次要显示的值,我希望界面也每毫秒更新一次[不使用“更新”按钮要求显示达到的值]

提前感谢那些愿意提供帮助的人

【问题讨论】:

  • 如果文本Counter: 10 没问题,那么标签就足以控制任务。检查此链接:How to: Use a Background Worker
  • @Fabio:非常感谢您的建议,我不想使用后台工作人员来完成此类任务,但我很欣赏这个建议
  • 对于需要从非 UI 线程更新 UI 控件的任务来说,背景主要是正确的方法。背景可以取消正在运行的任务或其他一些工作人员

标签: c# .net winforms label windows-forms-designer


【解决方案1】:

1) 是的,您需要标签旁边的只读文本框。

2) 向表单添加方法如下:

void UpdateCounter()
{
    if (InvokeRequired)
    {
        BeginInvoke(new MethodInvoker(UpdateCounter));
        return;
    }
    CounterValue.Text = Counter.ToString();
}

3) 每次更改计数器时调用此方法。

或者您可以使用计时器来调用 UpdateCounter 函数。

【讨论】:

    【解决方案2】:

    另一种选择是使用定时器控制它会自动改变值

     timer1.star();
    private void timer1_Tick(object sender, EventArgs e)
    {
    //Your code
    }
    

    【讨论】:

    • 非常感谢您向我展示了另一种可能的方法,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多