110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listp.Add(pictureBox1);
listp.Add(pictureBox2);
listp.Add(pictureBox3);
listp.Add(pictureBox4);
}
List<PictureBox> listp = new List<PictureBox>();
bool[] bRed = new bool[4];
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
if(bRed[i]==false)
{
listp[i].BackColor = Color.Blue;
bRed[i] = true;
}
else
{
listp[i].BackColor = Color.Red;
bRed[i] = false;
}
System.Threading.Thread.Sleep(200);
listp[i].Invalidate();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
var i = 0;
timer1.Tick += (s, arg) =>
{
label1.Text = "i=" + i.ToString();
++i;
if (i > 20)
{
label1.Text = "结束";
timer1.Stop();
}
};
label1.Text = "启动";
timer1.Interval = 200;
timer1.Start();
}
<script type="text/javascript">
let i = 0;
let x = setInterval(function() {
document.getElementById("xxx").innerText = "i=" + i.toString();
++i;
if (i > 20)
clearInterval(x);
}, 200);
</script>
其实设计模式是一样的。只是语法不用而已。
那么为什么网页程序员不会纠结这类问题,而写个 winform 或者 WPF 程序那么高达上的程序,要纠结呢?在 csdn 上还有真么多纠结得帖子呢?
我想说这是 winform、WPF 文章作者太垃圾,只知道抄人家 msdn 之类的介绍语法的文字,不知道从设计模式来讲问题的恶果。因为 javascript 的语法就是那样直接了当的,所以网页程序员很轻地掌握了定时器中操作 javascript 变量地方法,而winform 程序员竟然连在定时器中操作变量 i 都不会,这就是各种“7天学会XXXX”之类的书籍很容易出现的坑爹结果。private void Form1_Load(object sender, EventArgs e)
{
var i = 0;
timer1.Tick += (s, arg) =>
{
label1.Text = "i=" + i.ToString();
++i;
if (i > 20)
label1.Text = "结束";
};
label1.Text = "启动";
timer1.Interval = 200;
timer1.Start();
}
这就是使用 timer 的方法。
许多时候,你需要用代码来动态控制使用 timer。入门书上可能只有“拖鼠标、用vs设置timer参数”的教程,造成有些人不求甚解而不会用代码来编程使用 timer。