
C# 窗体上如何显示 类中的变量,我想在窗体textbox中显示 一个类中的变量,此变量每隔一秒变化一次怎么做
2个回答
展开全部
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//假设你要显示的变量是n
private int n;
//定义一个定时器
private System.Threading.Timer tm;
public Form1()
{
InitializeComponent();
n = 0;
//初始化定时器,每隔1000毫秒执行一个Exec方法
tm = new System.Threading.Timer(new System.Threading.TimerCallback(Exec), null, 0, 1000);
}
private void Exec(object state)
{
n++;
//在这里显示你的变量
SetLable(n.ToString());
}
#region 提示信息方法
private delegate void SetLableCallback(string str);
public void SetLable(string str)
{
if (IsDisposed)
return;
if (label1.IsDisposed)
return;
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (label1.InvokeRequired)
{
SetLableCallback o = new SetLableCallback(SetLable);
Invoke(o, new object[] { str });
}
else
{
label1.Text = str;
}
}
#endregion
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//假设你要显示的变量是n
private int n;
//定义一个定时器
private System.Threading.Timer tm;
public Form1()
{
InitializeComponent();
n = 0;
//初始化定时器,每隔1000毫秒执行一个Exec方法
tm = new System.Threading.Timer(new System.Threading.TimerCallback(Exec), null, 0, 1000);
}
private void Exec(object state)
{
n++;
//在这里显示你的变量
SetLable(n.ToString());
}
#region 提示信息方法
private delegate void SetLableCallback(string str);
public void SetLable(string str)
{
if (IsDisposed)
return;
if (label1.IsDisposed)
return;
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (label1.InvokeRequired)
{
SetLableCallback o = new SetLableCallback(SetLable);
Invoke(o, new object[] { str });
}
else
{
label1.Text = str;
}
}
#endregion
}
}
追问
定时器和变量都是在另一个类里面 ,不在窗体类 里面
追答
最简单的办法就是可以把你的定时器定义成公开属性
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询