C#相机采集小程序(参照pylon案例库实现)

1.找到pylon案例库中的PylonLiveView项目

我的项目路径:D:\Program Files\Basler\pylon 5\Development\Samples\C#\PylonC.NET\PylonLiveView
添加如下引用:D:\Program Files\Basler\pylon 5\Development\Samples\C#\PylonC.NET\PylonLiveView\bin\Debug\PylonC.NET.dll
D:\Program Files\Basler\pylon 5\Development\Samples\C#\PylonC.NET\bin\PylonC.NETSupportLibrary.dll
在工具箱中添加如下控件:
在这里插入图片描述
拷贝控件相关程序:

2.设计mypylon窗体

在这里插入图片描述

namespace basler_task
{
    partial class MyPylon
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.oneshot_button = new System.Windows.Forms.Button();
            this.stop_button = new System.Windows.Forms.Button();
            this.continous_shot_button = new System.Windows.Forms.Button();
            this.picture_Box = new System.Windows.Forms.PictureBox();
            this.list_device = new System.Windows.Forms.ListView();
            this.list_label = new System.Windows.Forms.Label();
            this.updateDeviceListTimer = new System.Windows.Forms.Timer(this.components);
            this.panel1 = new System.Windows.Forms.Panel();
            this.panel2 = new System.Windows.Forms.Panel();
            this.ExposureTimeRaw = new mySlider.SliderUserControl();
            this.GainRaw = new mySlider.SliderUserControl();
            this.panel3 = new System.Windows.Forms.Panel();
            this.panel6 = new System.Windows.Forms.Panel();
            this.panel4 = new System.Windows.Forms.Panel();
            this.splitter1 = new System.Windows.Forms.Splitter();
            ((System.ComponentModel.ISupportInitialize)(this.picture_Box)).BeginInit();
            this.panel1.SuspendLayout();
            this.panel2.SuspendLayout();
            this.panel3.SuspendLayout();
            this.panel6.SuspendLayout();
            this.panel4.SuspendLayout();
            this.SuspendLayout();
            // 
            // oneshot_button
            // 
            this.oneshot_button.BackColor = System.Drawing.SystemColors.Info;
            this.oneshot_button.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.oneshot_button.Location = new System.Drawing.Point(8, 13);
            this.oneshot_button.Name = "oneshot_button";
            this.oneshot_button.Size = new System.Drawing.Size(94, 40);
            this.oneshot_button.TabIndex = 0;
            this.oneshot_button.Text = "one shot";
            this.oneshot_button.UseVisualStyleBackColor = false;
            this.oneshot_button.Click += new System.EventHandler(this.One_Shot_Click);
            // 
            // stop_button
            // 
            this.stop_button.BackColor = System.Drawing.SystemColors.Info;
            this.stop_button.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.stop_button.Location = new System.Drawing.Point(241, 13);
            this.stop_button.Name = "stop_button";
            this.stop_button.Size = new System.Drawing.Size(98, 40);
            this.stop_button.TabIndex = 1;
            this.stop_button.Text = "stop";
            this.stop_button.UseVisualStyleBackColor = false;
            this.stop_button.Click += new System.EventHandler(this.Stop_Click);
            // 
            // continous_shot_button
            // 
            this.continous_shot_button.BackColor = System.Drawing.SystemColors.Info;
            this.continous_shot_button.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.continous_shot_button.Location = new System.Drawing.Point(123, 13);
            this.continous_shot_button.Name = "continous_shot_button";
            this.continous_shot_button.Size = new System.Drawing.Size(99, 40);
            this.continous_shot_button.TabIndex = 2;
            this.continous_shot_button.Text = "continous shot";
            this.continous_shot_button.UseVisualStyleBackColor = false;
            this.continous_shot_button.Click += new System.EventHandler(this.Conyinous_Shot_Click);
            // 
            // picture_Box
            // 
            this.picture_Box.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.picture_Box.Location = new System.Drawing.Point(26, 71);
            this.picture_Box.Name = "picture_Box";
            this.picture_Box.Size = new System.Drawing.Size(535, 398);
            this.picture_Box.TabIndex = 3;
            this.picture_Box.TabStop = false;
            // 
            // list_device
            // 
            this.list_device.Location = new System.Drawing.Point(6, 18);
            this.list_device.Name = "list_device";
            this.list_device.Size = new System.Drawing.Size(341, 230);
            this.list_device.TabIndex = 6;
            this.list_device.UseCompatibleStateImageBehavior = false;
            this.list_device.SelectedIndexChanged += new System.EventHandler(this.list_device_IndexSelected);
            // 
            // list_label
            // 
            this.list_label.AutoSize = true;
            this.list_label.BackColor = System.Drawing.SystemColors.ControlLight;
            this.list_label.Font = new System.Drawing.Font("宋体", 9F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.list_label.Location = new System.Drawing.Point(3, 3);
            this.list_label.Name = "list_label";
            this.list_label.Size = new System.Drawing.Size(295, 15);
            this.list_label.TabIndex = 7;
            this.list_label.Text = "device list(press F5 to update):";
            // 
            // updateDeviceListTimer
            // 
            this.updateDeviceListTimer.Enabled = true;
            this.updateDeviceListTimer.Interval = 5000;
            this.updateDeviceListTimer.Tick += new System.EventHandler(this.updateDeviceListTimer_Tick);
            // 
            // panel1
            // 
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel1.Controls.Add(this.list_device);
            this.panel1.Controls.Add(this.list_label);
            this.panel1.Location = new System.Drawing.Point(9, 83);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(354, 251);
            this.panel1.TabIndex = 8;
            // 
            // panel2
            // 
            this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel2.Controls.Add(this.ExposureTimeRaw);
            this.panel2.Controls.Add(this.GainRaw);
            this.panel2.Location = new System.Drawing.Point(9, 340);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(354, 188);
            this.panel2.TabIndex = 9;
            // 
            // ExposureTimeRaw
            // 
            this.ExposureTimeRaw.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.ExposureTimeRaw.BackColor = System.Drawing.Color.Honeydew;
            this.ExposureTimeRaw.Location = new System.Drawing.Point(18, 120);
            this.ExposureTimeRaw.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
            this.ExposureTimeRaw.MinimumSize = new System.Drawing.Size(300, 58);
            this.ExposureTimeRaw.Name = "ExposureTimeRaw";
            this.ExposureTimeRaw.NodeName = "ExposureTimeRaw";
            this.ExposureTimeRaw.Size = new System.Drawing.Size(312, 58);
            this.ExposureTimeRaw.TabIndex = 2;
            this.ExposureTimeRaw.Load += new System.EventHandler(this.ExposureTime_Load);
            // 
            // GainRaw
            // 
            this.GainRaw.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.GainRaw.BackColor = System.Drawing.Color.Honeydew;
            this.GainRaw.Location = new System.Drawing.Point(18, 22);
            this.GainRaw.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
            this.GainRaw.MaximumSize = new System.Drawing.Size(1167, 58);
            this.GainRaw.MinimumSize = new System.Drawing.Size(300, 58);
            this.GainRaw.Name = "GainRaw";
            this.GainRaw.NodeName = "GainRaw";
            this.GainRaw.Size = new System.Drawing.Size(312, 58);
            this.GainRaw.TabIndex = 1;
            this.GainRaw.Load += new System.EventHandler(this.Gain_Load);
            // 
            // panel3
            // 
            this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel3.Controls.Add(this.panel2);
            this.panel3.Controls.Add(this.panel1);
            this.panel3.Controls.Add(this.panel6);
            this.panel3.Controls.Add(this.panel4);
            this.panel3.Controls.Add(this.splitter1);
            this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel3.Location = new System.Drawing.Point(0, 0);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(974, 547);
            this.panel3.TabIndex = 10;
            // 
            // panel6
            // 
            this.panel6.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel6.Controls.Add(this.picture_Box);
            this.panel6.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel6.Location = new System.Drawing.Point(389, 0);
            this.panel6.Name = "panel6";
            this.panel6.Size = new System.Drawing.Size(581, 543);
            this.panel6.TabIndex = 4;
            // 
            // panel4
            // 
            this.panel4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel4.Controls.Add(this.continous_shot_button);
            this.panel4.Controls.Add(this.oneshot_button);
            this.panel4.Controls.Add(this.stop_button);
            this.panel4.Location = new System.Drawing.Point(9, 12);
            this.panel4.Name = "panel4";
            this.panel4.Size = new System.Drawing.Size(354, 65);
            this.panel4.TabIndex = 11;
            // 
            // splitter1
            // 
            this.splitter1.Location = new System.Drawing.Point(0, 0);
            this.splitter1.Name = "splitter1";
            this.splitter1.Size = new System.Drawing.Size(389, 543);
            this.splitter1.TabIndex = 12;
            this.splitter1.TabStop = false;
            // 
            // MyPylon
            // 
            this.ClientSize = new System.Drawing.Size(974, 547);
            this.Controls.Add(this.panel3);
            this.Name = "MyPylon";
            this.Text = "MyPylon";
            ((System.ComponentModel.ISupportInitialize)(this.picture_Box)).EndInit();
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.panel2.ResumeLayout(false);
            this.panel3.ResumeLayout(false);
            this.panel6.ResumeLayout(false);
            this.panel4.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        //private System.Windows.Forms.Button button1;
        //private System.Windows.Forms.Button button3;
        //private System.Windows.Forms.Button button2;
        //private System.Windows.Forms.PictureBox pictureBox1;
        //private System.Windows.Forms.Label label1;
       // private PylonC.NETSupportLibrary.SliderUserControl sliderUserControl1;
        //private PylonC.NETSupportLibrary.SliderUserControl sliderUserControl2;
        private System.Windows.Forms.Button oneshot_button;
        private System.Windows.Forms.Button stop_button;
        private System.Windows.Forms.Button continous_shot_button;
        private System.Windows.Forms.PictureBox picture_Box;
        private mySlider.SliderUserControl GainRaw;
        private mySlider.SliderUserControl ExposureTimeRaw;
        private System.Windows.Forms.ListView list_device;
        private System.Windows.Forms.Label list_label;
        private System.Windows.Forms.Timer updateDeviceListTimer;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.Panel panel4;
        private System.Windows.Forms.Panel panel6;
        private System.Windows.Forms.Splitter splitter1;
    }
}


3.mypylon窗体中控件的监听事件

using PylonC.NETSupportLibrary;
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;
using mySlider;

namespace basler_task
{
    public partial class MyPylon : Form
    {
        /*ImageProvider负责打开和关闭设备,它负责抓取和缓冲区处理,它通过事件通知用户状态变化,并提供对设备的GenICam参数节点的访问。
        抓取是在内部线程中完成的。抓取图像后,抓取线程将触发图像就绪事件。可以使用GetCurrentImage()获取图像。图像经过处理后,可以通过ReleaseImage发布。
        然后将图像排队等待下一次抓取。
        ImageProvider内部定义的实体类如下:
            Image类:用来存储图像数据
            GrabResult类:用于在内部对Grab结果进行排队。
         */
        private ImageProvider my_imageProvider = new ImageProvider(); 
        /* 位图对象 */
        private Bitmap m_bitmap = null; 

        public MyPylon()
        {
            InitializeComponent();

            /* 初始化winform窗体时,对ImageProvider的一些事件与相关的委托对象绑定 */
            my_imageProvider.GrabErrorEvent += new ImageProvider.GrabErrorEventHandler(OnGrabErrorEventCallback);
            my_imageProvider.DeviceRemovedEvent += new ImageProvider.DeviceRemovedEventHandler(OnDeviceRemovedEventCallback);
            my_imageProvider.DeviceOpenedEvent += new ImageProvider.DeviceOpenedEventHandler(OnDeviceOpenedEventCallback);
            my_imageProvider.DeviceClosedEvent += new ImageProvider.DeviceClosedEventHandler(OnDeviceClosedEventCallback);
            my_imageProvider.GrabbingStartedEvent += new ImageProvider.GrabbingStartedEventHandler(OnGrabbingStartedEventCallback);
            my_imageProvider.ImageReadyEvent += new ImageProvider.ImageReadyEventHandler(OnImageReadyEventCallback);
            my_imageProvider.GrabbingStoppedEvent += new ImageProvider.GrabbingStoppedEventHandler(OnGrabbingStoppedEventCallback);

            /*为slide控件提供对ImageProvider对象。*/
            GainRaw.MyImageProvider = my_imageProvider;
            ExposureTimeRaw.MyImageProvider = my_imageProvider;

            /*更新设备列表*/
            UpdateDeviceList();

            /*根据图像提供程序的状态启用按钮。*/
            EnableButtons(my_imageProvider.IsOpen, false);

        }
        /***********************************************************开始、关闭、停止相机的处理程序*********************************************************/
        /*停止ImageProvider并处理异常*/
        private void Stop()
        {
            /* Stop the grabbing. */
            try
            {
                my_imageProvider.Stop();
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }
        /*关闭ImageProvider并处理异常。*/
        private void CloseTheImageProvider()
        {
            try
            {
                my_imageProvider.Close();
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }
        /*开始抓取一幅图像并处理异常*/
        private void OneShot()
        {
            try
            {
                my_imageProvider.OneShot(); /*抓取一张图像*/
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }
        /*连续抓取图像并处理异常*/
        private void ContinuousShot()
        {
            try
            {
                my_imageProvider.ContinuousShot(); /* 抓取连续图像 */
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }
        /*************************************************************************************************************************************************************/
        /**附加处理功能:显示异常信息、winform关闭时的处理程序、更新设备列表、F5更新
        设备列表、计时器回调检查设备是否连接、ImageProvide状态决定按钮状态、从列表中选择设备**/
        /*在消息框中显示异常*/
        private void ShowException(Exception e, string additionalErrorMessage)
        {
            string more = "\n\nLast error message (may not belong to the exception):\n" + additionalErrorMessage;
            MessageBox.Show("Exception caught:\n" + e.Message + (additionalErrorMessage.Length > 0 ? more : ""), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /*当窗口关闭时,关闭ImageProvider。*/
        private void MainForm_FormClosing(object sender, FormClosingEventArgs ev)
        {
            Stop();
            CloseTheImageProvider();
        }

        /*更新设备列表*/
        private void UpdateDeviceList()
        {
            try
            {
                List<DeviceEnumerator.Device> list = DeviceEnumerator.EnumerateDevices();/*设备列表*/

                ListView.ListViewItemCollection items = list_device.Items;/*视图列表*/

                /* 向设备列表中添加一个新的设备 */
                foreach (DeviceEnumerator.Device device in list)
                {
                    bool newitem = true;/*是否向列表中添加新设备的标志*/
                    /* 检查当前列表视图中是否存在当前设备 */
                    foreach (ListViewItem item in items)
                    {
                        /* 从列表视图中检索设备 */
                        DeviceEnumerator.Device tag = item.Tag as DeviceEnumerator.Device;

                        if (tag.FullName == device.FullName)/*若存在,更新设备索引,不需要像列表视图中添加设备*/
                        {        
                            tag.Index = device.Index;
                            newitem = false;
                            break;
                        }
                    }

                    /* 如果设备不在列表视图中,向列表视图中添加设备 */
                    if (newitem)
                    {
                        ListViewItem item = new ListViewItem(device.Name);
                        if (device.Tooltip.Length > 0)
                        {
                            item.ToolTipText = device.Tooltip;
                        }
                        item.Tag = device;

                        /* Attach the device data. */
                        list_device.Items.Add(item);
                    }
                }

                /* 删除被移除的设备 */
                foreach (ListViewItem item in items)
                {
                    bool exists = false;

                    /*对设备列表的每个设备判断是否存在与视图列表中 */
                    foreach (DeviceEnumerator.Device device in list)
                    {
                        if (((DeviceEnumerator.Device)item.Tag).FullName == device.FullName)
                        {
                            exists = true;
                            break;
                        }
                    }
                    /*,如果不存在,删除视图列表中对应设备 */
                    if (!exists)
                    {
                        list_device.Items.Remove(item);
                    }
                }
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }

        /*如果按下了F5键,则更新设备列表。*/
        private void deviceList_Update(object sender, KeyEventArgs ev)
        {
            if (ev.KeyCode == Keys.F5)
            {
                ev.Handled = true;
                /* 更新列表 */
                UpdateDeviceList();
            }
        }

        /*计时器回调用于定期检查显示的设备是否仍连接到PC,并更新列表。 */
        private void updateDeviceListTimer_Tick(object sender, EventArgs e)
        {
            UpdateDeviceList();
        }

        /*从列表框中选择摄像机。关闭当前打开的设备,打开第一个选定的设备。*/
        private void list_device_IndexSelected(object sender, EventArgs ev)
        {
            /* 停止抓取图像,并关闭imageprovider */
            Stop();
            CloseTheImageProvider();

            /* 打开第一个选定的imageprovider. */
            if (list_device.SelectedItems.Count > 0)
            {
                /* 获得第一个被选择的设备 */
                ListViewItem item = list_device.SelectedItems[0];
                DeviceEnumerator.Device device = item.Tag as DeviceEnumerator.Device;
                try
                {
                    /* Open the image provider using the index from the device data. */
                    my_imageProvider.Open(device.Index);
                }
                catch (Exception e)
                {
                    ShowException(e, my_imageProvider.GetLastErrorMessage());
                }
            }
        }

        /*根据ImageProvider的状态是否激活按钮*/
        private void EnableButtons(bool canGrab, bool canStop)
        {
            oneshot_button.Enabled = canGrab;
            continous_shot_button.Enabled = canGrab;
            stop_button.Enabled = canStop;
        }

        /**********************************************对应MyForm()中事件委托的一些处理方法**********************************************************/
        private void OnGrabbingStoppedEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.GrabbingStoppedEventHandler(OnGrabbingStoppedEventCallback));
                return;
            }

            /* 再次启用设备列表更新 */
            updateDeviceListTimer.Start();

            /* The image provider stopped grabbing. Enable the grab buttons. Disable the stop button. */
            EnableButtons(my_imageProvider.IsOpen, false);
        }

        private void OnImageReadyEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.ImageReadyEventHandler(OnImageReadyEventCallback));
                return;
            }

            try
            {
                /* 从imageprovider获取图像. 仅显示最新的图像。相机获取图像的速度可能比显示图像的速度快*/
                ImageProvider.Image image = my_imageProvider.GetLatestImage();

                /* 检查图像是否已被删除 */
                if (image != null)
                {
                    /* 检查图像是否与当前使用的位图兼容。 */
                    if (BitmapFactory.IsCompatible(m_bitmap, image.Width, image.Height, image.Color))
                    {
                        /* 将图像存入位图中. */
                        BitmapFactory.UpdateBitmap(m_bitmap, image.Buffer, image.Width, image.Height, image.Color);
                        /* To show the new image, request the display control to update itself. */
                        picture_Box.Refresh();
                    }
                    else /* 根据图像大小请求新的位图 */
                    {
                        BitmapFactory.CreateBitmap(out m_bitmap, image.Width, image.Height, image.Color);
                        BitmapFactory.UpdateBitmap(m_bitmap, image.Buffer, image.Width, image.Height, image.Color);                     
                        Bitmap bitmap = picture_Box.Image as Bitmap;                     
                        picture_Box.Image = m_bitmap;
                        if (bitmap != null)
                        {
                            /* Dispose the bitmap. */
                            bitmap.Dispose();
                        }
                    }
                    /* 释放图像缓冲区,用来存放下一张抓取的图 */
                    my_imageProvider.ReleaseImage();
                }
            }
            catch (Exception e)
            {
                ShowException(e, my_imageProvider.GetLastErrorMessage());
            }
        }

        private void OnGrabbingStartedEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.GrabbingStartedEventHandler(OnGrabbingStartedEventCallback));
                return;
            }

            /* 抓取时不要更新设备列表,以避免抖动,因为枚举时GUI线程被短时间阻塞。 */
            updateDeviceListTimer.Stop();

            /* imageprovide正在抓取。禁用抓取按钮。启用停止按钮。 */
            EnableButtons(false, true);
        }

        private void OnDeviceClosedEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.DeviceClosedEventHandler(OnDeviceClosedEventCallback));
                return;
            }
            /* imageprovider被关闭. 禁用所有按钮 */
            EnableButtons(false, false);
        }

        private void OnDeviceOpenedEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.DeviceOpenedEventHandler(OnDeviceOpenedEventCallback));
                return;
            }
            /* imageprovider准备抓取. 启用抓取按钮 */
            EnableButtons(true, false);
        }

        private void OnDeviceRemovedEventCallback()
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.DeviceRemovedEventHandler(OnDeviceRemovedEventCallback));
                return;
            }
            /* 禁用所有按钮 */
            EnableButtons(false, false);
            /* 停止抓取图像 */
            Stop();
            /* 关闭imageprovider */
            CloseTheImageProvider();
            /* 更新设备列表 */
            UpdateDeviceList();
        }

        private void OnGrabErrorEventCallback(Exception grabException, string additionalErrorMessage)
        {
            if (InvokeRequired)
            {
                /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
                BeginInvoke(new ImageProvider.GrabErrorEventHandler(OnGrabErrorEventCallback), grabException, additionalErrorMessage);
                return;
            }
            ShowException(grabException, additionalErrorMessage);
        }
        /****************************************************************winform组件的触发事件***********************************************************/
        private void Gain_Load(object sender, EventArgs e)
        {

        }

        private void ExposureTime_Load(object sender, EventArgs e)
        {

        }

        private void Conyinous_Shot_Click(object sender, EventArgs e)
        {
            ContinuousShot();
        }

        private void One_Shot_Click(object sender, EventArgs e)
        {
            OneShot();
        }

        private void Stop_Click(object sender, EventArgs e)
        {
            Stop(); 
        }
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用C#调用Basler相机SDK时,您可以写一个相机库,并在其中包含触发采集的功能。下面是一个示例代码,展示了如何修改相机库以支持触发采集: ```csharp using Basler.Pylon; public class CameraLibrary { private Camera camera; private bool isTriggered = false; public void Initialize() { // 初始化相机 camera = new Camera(); camera.Open(); // 设置触发模式 camera.CameraOpened += ConfigureTriggerMode; } private void ConfigureTriggerMode(object sender, EventArgs e) { if (camera != null && camera.Parameters[PLCamera.TriggerSelector].IsWritable) { // 设置触发模式为硬件触发 camera.Parameters[PLCamera.TriggerSelector].TrySetValue(PLCamera.TriggerSelector.FrameStart); camera.Parameters[PLCamera.TriggerMode].TrySetValue(PLCamera.TriggerMode.On); // 设置触发源为上升沿触发 camera.Parameters[PLCamera.TriggerSource].TrySetValue(PLCamera.TriggerSource.Line1); camera.Parameters[PLCamera.TriggerActivation].TrySetValue(PLCamera.TriggerActivation.RisingEdge); } } public void StartAcquisition() { // 启动图像采集 if (isTriggered) { // 仅在触发模式下启动图像采集 camera.StreamGrabber.Start(); } } public void StopAcquisition() { // 停止图像采集 camera.StreamGrabber.Stop(); } public BitmapImage CaptureImage() { // 捕获图像 if (!isTriggered) { // 如果不是触发模式,则直接采集图像 camera.StreamGrabber.Start(1, GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber); } IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (grabResult) { if (grabResult.GrabSucceeded) { BitmapImage image = ConvertToBitmapImage(grabResult); return image; } else { throw new Exception("Failed to grab image"); } } } private BitmapImage ConvertToBitmapImage(IGrabResult grabResult) { // 将图像转换为BitmapImage PixelDataConverter converter = new PixelDataConverter(); converter.OutputPixelFormat = PixelType.BGRA8packed; BitmapImage image = new BitmapImage(); image.BeginInit(); image.Width = grabResult.Width; image.Height = grabResult.Height; image.StreamSource = new MemoryStream(converter.ConvertToRgb8(grabResult)); image.EndInit(); return image; } public void Close() { // 关闭相机 camera.Close(); } } ``` 在上述代码中,我们添加了一个`isTriggered`变量来标识是否处于触发模式。在初始化相机时,我们订阅了`CameraOpened`事件,并在事件处理程序中配置了触发模式。在`StartAcquisition`方法中,我们检查`isTriggered`变量,仅在触发模式下启动图像采集。如果不是触发模式,则在`CaptureImage`方法中直接采集图像。 请确保在使用相机库之前,正确初始化并配置相机,并根据您的需求设置触发模式和触发源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值