一效果
点击button1按钮后显示当前日期到 button1按钮上
二 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Thread MyThread = new Thread(() =>
{
if (button1.InvokeRequired)//button1控件是不是当前线程创建的,明显不是当前线程创建的,返回true
{
button1.Invoke(new Action(() => { button1.Text = DateTime.Now.ToString(); }));//调用Invoke函数进行跨线程访问
}
else
{
this.button1.Text = DateTime.Now.ToString();
}
});
MyThread.Start();
}
}
}