您的位置:首页 > 编程语言 > C#

C# 定时执行函数(winForm)

2009-02-17 09:43 501 查看
需要使用timer 定时器控件

timer1.Interval 设置时间间隔

timer1.Tick 到达时间间隔时触发事件

test_tick 时间处理函数

timer1.Tick += new System.EventHandler(test_Tick);
委托以处理事件 ,一般可以在Form 的构造函数 InitializeComponent构造界面组件函数中添加以上代码以注册test_Tick处理函数;

当然,你也可以不用这么麻烦,再窗体视图中直接双击timer控件,系统就会自动帮你生成一个类似于test_Tick的处理函数

通常要执行需要使用 timer1.Start();//启动定时器 timer1.Stop();.//关闭定时器方法

一般代码过程如下:

private void Form_Load(object sender, EventArgs e)

{

timer1.Interval = 1000;

timer1.Start();

}

private void test_Tick(...)

{

//每隔一秒需要执行的函数体,timer start后每隔一秒就会执行该函数

}

以下是一些扩展应用:

(1)WinForm自動定時截取螢幕畫面,並存成圖片檔

public partial class screenshots : Form
{
private static Bitmap bmpScreenshot;

private static Graphics gfxScreenshot;

public screenshots()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

gfxScreenshot = Graphics.FromImage(bmpScreenshot);

gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

bmpScreenshot.Save(string.Format(@"c:/temp/{0}.jpg", DateTime.Now.Ticks.ToString()), System.Drawing.Imaging.ImageFormat.Png);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: