【发布时间】:2017-02-21 20:50:35
【问题描述】:
这是我的第一堂课:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*_enemy = new Class1(this);
int y = Class1.MyMethod(0);
textBox1.Text = Convert.ToString (y);*/
}
private Class1 _enemy;
private void button1_Click(object sender, EventArgs e)
{
_enemy = new Class1(this);
int y = Class1.MyMethod();
textBox1.Text = Convert.ToString(y);
}
}
}
这是我的第二堂课:
namespace WindowsFormsApplication2
{
public class Class1
{
public Class1( Form1 form )
{
_form1 = form;
}
public static int MyMethod()
{
int i = 0;
for (int j = 1; j <= 20; j++)
{
i = j;
//Thread.Sleep(100);
}
return i;
}
}
// DON'T initialize this with new Form1();
private Form1 _form1;
}
程序运行正常,我在TextBox 中只得到了 20 个输出。我想要的是每次循环运行时的输出。
点赞1,2,3,.........20 并停止。
也许像一个柜台。我也尝试过使用Timer,但做不到。
编辑:
@Mong Zhu 我已经交叉检查了代码,仍然得到异常。
以下是完整代码供您参考:
Form1.cpp
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Class1 MyCounterClass;
private void Form1_Load(object sender, EventArgs e)
{
MyCounterClass = new Class1();
// register the event. The method on the right hand side
// will be called when the event is fired
MyCounterClass.CountEvent += MyCounterClass_CountEvent;
}
private void MyCounterClass_CountEvent(int c)
{
if (textBox1.InvokeRequired)
{
textBox1.BeginInvoke(new Action(() => textBox1.Text = c.ToString()));
}
else
{
textBox1.Text = c.ToString();
}
}
public Form1()
{
InitializeComponent();
}
private Class1 _enemy;
private void button1_Click(object sender, EventArgs e)
{
MyCounterClass.MyCountMethod(300, 0, 10);
}
}
}
和class1.cpp
namespace WindowsFormsApplication2
{
public class Class1
{
public delegate void Counter(int c); // this delegate allows you to transmit an integer
public event Counter CountEvent;
public Class1()
{
}
public void MyCountMethod(int interval_msec, int start, int end)
{
System.Threading.Thread t = new System.Threading.Thread(() =>
{
for (int i = start; i <= end; i++)
{
// Check whether some other class has registered to the event
if (CountEvent != null)
{
// fire the event to transmit the counting data
CountEvent(i);
System.Threading.Thread.Sleep(interval_msec);
}
}
});
// start the thread
t.Start();
}
// DON'T initialize this with new Form1();
private Form1 _form1;
}
}
【问题讨论】:
-
您在寻找IProgress吗?
-
不知道是什么?你能详细说明一下吗?
-
@Default 你能帮帮我吗? (带代码)。我需要的是 class1 中的一个逻辑,它将为计数器创建一个循环。我需要通过单击文本框内的按钮在 form1 中调用该 class1。但它可能不一定是一个文本框,它可能是一个进度条或其他任何东西。基本上我不想从 class1 转移任何 GUI。
-
你检查了链接吗?我的建议在这两个链接中都有详细的解释。如果那不能回答您的问题,那么不,我无法帮助您编写代码。如果那是您正在寻找的东西,那么可以肯定,我可以添加一个答案。但请先阅读链接!