展示结果:
下面附上界面中所有控件的Name,只需照着红字设置对应的控件Name即可
下面附上小编主界面的全部代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using MvCameraControl;namespace MVC
{public partial class Form1 : Form{// ch:枚举的相机类型 | en:TLayerType for enumerate devicesreadonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();IDevice device = null;bool isGrabbing = false; //是否正在取图Thread receiveThread = null; //接收图像线程Thread receiveImage = null;IntPtr pictureBoxHandle = IntPtr.Zero; //显示图像的控件句柄public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){//初始化SDKSDKSystem.Initialize();//枚举设备RefreshDeviceList();}/// <summary>/// ch:显示错误信息 | en:Show error message/// </summary>private void ShowErrorMsg(string message, int errorCode){string errorMsg;if (errorCode == 0){errorMsg = message;}else{errorMsg = message + ": Error =" + String.Format("{0:X}", errorCode);}switch (errorCode){case MvError.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;case MvError.MV_E_SUPPORT: errorMsg += " Not supported function "; break;case MvError.MV_E_BUFOVER: errorMsg += " Cache is full "; break;case MvError.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;case MvError.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;case MvError.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;case MvError.MV_E_NODATA: errorMsg += " No data "; break;case MvError.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;case MvError.MV_E_VERSION: errorMsg += " Version mismatches "; break;case MvError.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;case MvError.MV_E_UNKNOW: errorMsg += " Unknown error "; break;case MvError.MV_E_GC_GENERIC: errorMsg += " General error "; break;case MvError.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;case MvError.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;case MvError.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;case MvError.MV_E_NETER: errorMsg += " Network error "; break;}MessageBox.Show(errorMsg, "PROMPT");}private void RefreshDeviceList(){//创建设备列表cbDeviceList.Items.Clear();int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);if (nRet != MvError.MV_OK){ShowErrorMsg("Enumerate devices fail !", nRet);return;}//在窗体列表中显示设备名for (int i = 0; i < deviceInfoList.Count; i++){IDeviceInfo deviceInfo = deviceInfoList[i];if (deviceInfo.UserDefinedName != ""){cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.UserDefinedName + " (" + deviceInfo.SerialNumber + ")");}else{cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.ManufacturerName + " " + deviceInfo.ModelName + " (" + deviceInfo.SerialNumber + ")");}}//选择第一项if (deviceInfoList.Count != 0){cbDeviceList.SelectedIndex = 0;}}private void bnClose_Click(object sender, EventArgs e){//取流标志位清零if (isGrabbing == true){bnStopGrab_Click(sender, e);}//关闭设备if (device != null){device.Close();device.Dispose();}//控件操作SetCtrlWhenClose();}private void SetCtrlWhenClose(){bnOpen.Enabled = true;bnClose.Enabled = false;bnStartGrab.Enabled = false;bnStopGrab.Enabled = false;bnContinuesMode.Enabled = false;bnTriggerMode.Enabled = false;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;tbExposure.Enabled = false;tbGain.Enabled = false;tbFrameRate.Enabled = false;bnGetParam.Enabled = false;bnSetParam.Enabled = false;}private void bnEnum_Click(object sender, EventArgs e){RefreshDeviceList();}private void bnOpen_Click(object sender, EventArgs e){if (deviceInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1){ShowErrorMsg("No device, please select", 0);return;}//获取选择的设备信息IDeviceInfo deviceInfo = deviceInfoList[cbDeviceList.SelectedIndex];try{//打开设备device = DeviceFactory.CreateDevice(deviceInfo);}catch (Exception ex){MessageBox.Show("Create Device fail !" + ex.Message);return;}int result = device.Open();if (result != MvError.MV_OK){ShowErrorMsg("Open Device fail", result);return;}//判断是否为gige设备if (device is IGigEDevice){//转换为gige设备IGigEDevice gigEDevice = device as IGigEDevice;//探测网络最佳包大小int optionPacketSize;result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);if (result != MvError.MV_OK){ShowErrorMsg("Waring: Get packet Size failed !", result);}else{result = device.Parameters.SetIntValue("GevSCPSPPacketSize", (long)optionPacketSize);if (result != MvError.MV_OK){ShowErrorMsg("Waring: Set Packet Size failed", result);}}}//设置采集卡连续模式device.Parameters.SetEnumValueByString("AcauisitionMode", "Continuous");device.Parameters.SetEnumValueByString("TriggerMode", "Off");//关闭触发模式//控件操作SetCtrlWhenOpen();//获取参数bnGetParam_Click(null, null);}private void SetCtrlWhenOpen(){bnOpen.Enabled = false;bnClose.Enabled = true;bnStartGrab.Enabled = true;bnStopGrab.Enabled = false;bnContinuesMode.Enabled = true;bnContinuesMode.Checked = true;//bnContinuesMode_CheckedChanged(null,null);bnTriggerMode.Enabled = true;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;tbExposure.Enabled = true;tbGain.Enabled = true;tbFrameRate.Enabled = true;bnGetParam.Enabled = true;bnSetParam.Enabled = true;}private void GetTriggerMode(){IEnumValue enumValue;int result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);if (result == MvError.MV_OK){if (enumValue.CurEnumEntry.Symbolic == "On"){bnTriggerMode.Checked = true;bnContinuesMode.Checked = false;result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);if (result == MvError.MV_OK){if (enumValue.CurEnumEntry.Symbolic == "TriggerSoftware"){cbSoftTrigger.Enabled = true;cbSoftTrigger.Checked = true;if (isGrabbing){bnTriggerExec.Enabled = true;}}}}else{bnContinuesMode.Checked = true;bnTriggerMode.Checked = false;}}}private void bnGetParam_Click(object sender, EventArgs e){GetTriggerMode();IFloatValue floatValue;int result = device.Parameters.GetFloatValue("ExposureTime", out floatValue);if (result == MvError.MV_OK){tbExposure.Text = floatValue.CurValue.ToString("F1");}result = device.Parameters.GetFloatValue("Gain", out floatValue);if (result == MvError.MV_OK){tbGain.Text = floatValue.CurValue.ToString("F1");}result = device.Parameters.GetFloatValue("ResultingFrameRate", out floatValue);if (result == MvError.MV_OK){tbFrameRate.Text = floatValue.CurValue.ToString("F1");}IEnumValue enumValue;result = device.Parameters.GetEnumValue("PixelFormat", out enumValue);if (result == MvError.MV_OK){tbPixelFormat.Text = enumValue.CurEnumEntry.Symbolic;}}private void bnSetParam_Click(object sender, EventArgs e){try{float.Parse(tbExposure.Text);float.Parse(tbGain.Text);float.Parse(tbFrameRate.Text);}catch{ShowErrorMsg("Please enter correct type !", 0);return;}device.Parameters.SetEnumValue("ExposureAuto", 0);int result = device.Parameters.SetFloatValue("ExposureTime", float.Parse(tbExposure.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Gain Fail", result);}device.Parameters.SetEnumValue("GainAuto", 0);result = device.Parameters.SetFloatValue("Gain", float.Parse(tbGain.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Gain Fail !", result);}result = device.Parameters.SetBoolValue("AcquisitionFrameRateEnable", true);if (result != MvError.MV_OK){ShowErrorMsg("Set AcquisitionFrameRateEnable Fail !", result);}else{result = device.Parameters.SetFloatValue("AcquisitionFrameRate", float.Parse(tbFrameRate.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Frame Rate Fail !", result);}}}private void bnStopGrab_Click(object sender, EventArgs e){//标志位设为falseisGrabbing = false;receiveThread.Join();//停止采集int result = device.StreamGrabber.StopGrabbing();if (result != MvError.MV_OK){ShowErrorMsg("Stop Grabbing Fail !", result);}//控件操作SetCtrlWhenStopGrab();}private void SetCtrlWhenStopGrab(){bnStartGrab.Enabled = true;bnStopGrab.Enabled = false;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;}private void bnTriggerExec_Click(object sender, EventArgs e){//触发命令int result = device.Parameters.SetCommandValue("TriggerSoftware");if (result != MvError.MV_OK){ShowErrorMsg("Trigger Software Fail !", result);}}private void cbSoftTrigger_CheckedChanged(object sender, EventArgs e){//触发源设为软触发if (cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Software");if (isGrabbing){bnTriggerExec.Enabled = true;}}if (!cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Line0");bnTriggerExec.Enabled = false;}}private void Form1_FormClosing(object sender, FormClosingEventArgs e){bnClose_Click(null, null);//反初始化SDKSystem.Finalize();}private void bnContinuesMode_CheckedChanged(object sender, EventArgs e){if (bnContinuesMode.Checked){device.Parameters.SetEnumValueByString("TriggerMode", "Off");cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;}}private void bnTriggerMode_CheckedChanged(object sender, EventArgs e){if (bnTriggerMode.Checked){//打开触发模式device.Parameters.SetEnumValueByString("TriggerMode", "On");if ((bool)cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Software");if (isGrabbing){bnTriggerExec.Enabled = true;}}else{device.Parameters.SetEnumValueByString("TriggerSource", "Line0");}cbSoftTrigger.Enabled = true;cbSoftTrigger.Checked = true;}}public void ReciveThreadProcess(){IFrameOut frameOut = null;int result = MvError.MV_OK;while (isGrabbing){result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);if (result == MvError.MV_OK){device.ImageRender.DisplayOneFrame(pictureBoxHandle, frameOut.Image);device.StreamGrabber.FreeImageBuffer(frameOut);}}}public void ReciveThreadImage(){IFrameOut frameOut = null;int result = MvError.MV_OK;int windowWidth = hWindowControl1.Width;int windowHeight = hWindowControl1.Height;double windowAspect = (double)windowWidth / windowHeight;while (isGrabbing){result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);if (result == MvError.MV_OK){IImage image = frameOut.Image;int width = (int)image.Width;int height = (int)image.Height;double imageAspect = (double)width / height;int row1, col1, row2, col2;if (imageAspect > windowAspect){col1 = 0;col2 = width - 1;int newHeight = (int)(width / windowAspect);row1 = (width - newHeight) / 2;row2 = row1 + newHeight - 1;}else{row1 = 0;row2 = height - 1;int newWidth = (int)(height * windowAspect);col1 = (width - newWidth)/2;col2 = col1 + newWidth - 1;}hWindowControl1.HalconWindow.SetPart(row1, col1, row2, col2);IntPtr imagePtr = image.PixelDataPtr;Console.WriteLine(image.PixelType);if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_BayerBG8){HImage hImage = new HImage("byte",width,height,imagePtr);HObject rgbImage;HOperatorSet.CfaToRgb(hImage, out rgbImage, "bayer_bg", "bilinear");HOperatorSet.DispObj(rgbImage, hWindowControl1.HalconWindow);hImage.Dispose();rgbImage.Dispose();}}}}private void bnStartGrab_Click(object sender, EventArgs e){try{isGrabbing = true;pictureBoxHandle = displayArea.Handle;receiveThread = new Thread(ReciveThreadProcess);receiveThread.Start();receiveImage = new Thread(ReciveThreadImage);receiveImage.Start();}catch (Exception ex){MessageBox.Show("Start thread failed !" + ex.Message);return;}//开始采集int result = device.StreamGrabber.StartGrabbing();if (result != MvError.MV_OK){isGrabbing = false;receiveThread.Join();ShowErrorMsg("Start Grabbing Fail !", result);return;}SetCtrlWhenStartGrab();}private void SetCtrlWhenStartGrab(){bnStartGrab.Enabled = false;bnStopGrab.Enabled = true;if ((bool)bnTriggerMode.Checked){cbSoftTrigger.Enabled = true;if ((bool)cbSoftTrigger.Checked){bnTriggerExec.Enabled = true;}}}}
}