Q:我需要每隔n秒显示一张图片,并且这张图片会被其他程序(例如opencv)更新,怎么操作?
A:综合使用Timer控件与PictureBox控件。
下面的例子是以button作为触发控件:
PictureBoxSizeMode的选择参考:http://msdn.microsoft.com/zh-cn/library/system.windows.forms.pictureboxsizemode(v=vs.80).aspx
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="cpp">partial class Form1
{
<span style="white-space:pre"> </span>//...
<span style="white-space:pre"> </span>public static int timeflag = 0;
//...
}
<span style="font-family: Arial, Helvetica, sans-serif;">private void button1_Click(object sender, EventArgs e)</span>
{
<span style="white-space:pre"> </span>pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;//StretchImage;
timer1.Enabled = true;
timer1.Interval = 3000;<span style="white-space:pre"> </span>//第一次显示图片需等待3秒
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
<span style="white-space:pre"> </span>timer1.Interval = 100;<span style="white-space:pre"> </span>//每隔100毫秒刷新一次图片
<span style="white-space:pre"> </span>if (0 == timeflag)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>pictureBox1.Image = Image.FromFile("D:\\dy_code_work\\showwindow\\image-gray.jpg");
timeflag = 1;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>else
<span style="white-space:pre"> </span>{
pictureBox1.Image.Dispose();<span style="white-space:pre"> </span>//此语句是关键!使当前的picturebox控件释放图片文件,即允许其他程序对图片进行修改
//按需添加下语句:pictureBox2.Image=null;
timeflag = 0;
<span style="white-space:pre"> </span>}
}
参考链接:http://blog.sina.com.cn/s/blog_4d9b47930100a3qr.html