1、线程加载图片
using System;
using System.Drawing;
using System.Windows.Forms;
using HalconDotNet;
namespace zoao
{
public partial class Form1 : Form
{
private HTuple WindowID;
private HObject[] ImageArray = new HObject[8];
private int currentIndex = 0;
private bool isPlaying = false;
public Form1()
{
InitializeComponent();
// 创建 Halcon 窗口和加载图像
CreateHalconWindow();
LoadBatchImages();
// 将 Start_button_Click 和 Stop_button_Click 事件与按钮的 Click 事件绑定
Start_button.Click += Start_button_Click;
Stop_button.Click += Stop_button_Click;
}
private void CreateHalconWindow()
{
// 获取 Halcon 窗口的句柄并设置背景色
HTuple fatherWindow = DisplayVideo_pictureBox.Handle;
HOperatorSet.SetWindowAttr("background_color", "green");
HOperatorSet.OpenWindow(0, 0, DisplayVideo_pictureBox.Width, DisplayVideo_pictureBox.Height, fatherWindow, "visible", "", out WindowID);
}
private void LoadBatchImages()
{
for (int i = 0; i < 8; i++)
{
try
{
string imagePath = $"C:\\VisualStudioSetup文件项目\\C#模板\\A\\zoao\\bin\\Debug\\{i + 1}.bmp";
HOperatorSet.ReadImage(out ImageArray[i], imagePath);
}
catch (HalconDotNet.HOperatorException ex)
{
MessageBox.Show($"Failed to load image {i + 1}: {ex.Message}");
}
}
}
private void DisplayImage(HObject image)
{
// 在 Halcon 窗口中显示图像
HOperatorSet.DispObj(image, WindowID);
HTuple width, height;
HOperatorSet.GetImageSize(image, out width, out height);
HOperatorSet.SetPart(WindowID, 0, 0, height, width);
}
private void Start_button_Click(object sender, EventArgs e)
{
// 点击开始按钮时,启动图像播放
if (!isPlaying)
{
isPlaying = true;
currentIndex = 0;
timer1.Start(); // 启动定时器,定时触发显示下一张图像
}
}
private void Stop_button_Click(object sender, EventArgs e)
{
// 点击停止按钮时,停止图像播放
isPlaying = false;
timer1.Stop(); // 停止定时器
}
private void timer1_Tick(object sender, EventArgs e)
{
// 定时器触发,显示下一张图像
if (isPlaying)
{
DisplayImage(ImageArray[currentIndex]);
currentIndex = (currentIndex + 1) % ImageArray.Length; // 循环播放图像
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// 关闭窗体时释放 Halcon 窗口资源
HOperatorSet.CloseWindow(WindowID);
}
}
}