using HalconDotNet; using System.Diagnostics; namespace LB_VisionControls { public delegate void Control_MouseDown(object sender, MouseEventArgs e); public delegate void Control_MouseDoubleClick(object sender, MouseEventArgs e); public partial class UserHSmartWindowControl : UserControl { public UserHSmartWindowControl() { InitializeComponent(); // 设置轮廓默认为绿色 HOperatorSet.SetColor(hWindowControl.HalconWindow, "green"); HOperatorSet.SetLineWidth(hWindowControl.HalconWindow, 5); color = "green"; // 背景色 hWindowControl.HalconWindow.SetWindowParam("background_color", "gray"); // 设置默认字体为 20号 mono字体加粗 set_display_font(this.hWindowControl.HalconWindow, 20, "mono", "true", "false"); } public event Control_MouseDown event_MouseDown; public event Control_MouseDoubleClick event_MouseDoubleClick; private void event_mouseDown(object sender, MouseEventArgs e) { if (event_MouseDown != null) { event_MouseDown(sender, e); } } private void event_mouseDoubleClick(object sender, MouseEventArgs e) { if (event_MouseDoubleClick != null) { event_MouseDoubleClick(sender, e); } } private void UserHSmartWindowControl_Load(object sender, EventArgs e) { // 启用双缓冲减少闪烁 this.DoubleBuffered = true; this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); this.UpdateStyles(); } /// /// 是否自动放大到适合图像 /// public bool bAutoSize = true; private HObject _hImage = null; /// /// 显示图片(异步) /// public HObject hImage { get { return _hImage; } set { if (value == null) { _hImage = null; //ShowHoImage(null, hWindowControl.HalconWindow, bAutoSize); ShowHoImageAsync(null, hWindowControl.HalconWindow, bAutoSize); return; } // 耗时操作加锁避免被释放 lock (value) { try { // 深拷贝图片避免被释放 //_hImage = value.CopyObj(1, -1); //ShowHoImage(_hImage, hWindowControl.HalconWindow, bAutoSize); ShowHoImageAsync(value, hWindowControl.HalconWindow, bAutoSize); } catch { } } } } /// /// 画图取消请求 /// CancellationTokenSource ctsDrawingTask = new CancellationTokenSource(); private bool _bAollowDraw = false; /// /// 启用绘画模式标记 /// public bool bAollowDraw { get { return _bAollowDraw; } set { _bAollowDraw = value; //启动绘画模式需要取消缩放 if (value) { //// 取消异步线程 //ctsDrawingTask.Cancel(); //Thread.Sleep(100); //// 创建新CancellationTokenSource避免无法重启 //ctsDrawingTask = new CancellationTokenSource(); //Task task = Task.Run(() => DrawObjectTaskAsync(ctsDrawingTask.Token, RoiType.None), ctsDrawingTask.Token); HTuple hv_imageWidth = 250; HTuple hv_imageHeight = 250; if (hImage != null && hImage.IsInitialized()) HOperatorSet.GetImageSize(hImage, out hv_imageWidth, out hv_imageHeight); switch (enumRoiType) { case RoiType.Rectangle2: if (hRoi == null) hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2 , hv_imageHeight / 2, hv_imageWidth / 2, 0, hv_imageWidth / 8, hv_imageHeight / 8); hWindowControl.HalconWindow.AttachDrawingObjectToWindow(hRoi); break; case RoiType.Circle: if (hRoi == null) hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE , hv_imageHeight / 2, hv_imageWidth / 2, hv_imageWidth / 8); hWindowControl.HalconWindow.AttachDrawingObjectToWindow(hRoi); break; case RoiType.Ellipse: if (hRoi == null) hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE_SECTOR , hv_imageHeight / 2, hv_imageWidth / 2, 0, hv_imageWidth / 8, 0, Math.PI / 2.0 * 3.0); hWindowControl.HalconWindow.AttachDrawingObjectToWindow(hRoi); break; case RoiType.Segment: if (hRoi == null) hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE , hv_imageHeight / 8.0 * 3.0, hv_imageHeight / 2, hv_imageHeight / 8.0 * 5.0, hv_imageHeight / 2); hWindowControl.HalconWindow.AttachDrawingObjectToWindow(hRoi); break; // 空和其他不进行绘制 case RoiType.None: default: if (hRoi != null) { hRoi.ClearDrawingObject(); hRoi.Dispose(); hRoi = null; } break; } } else { // 取消异步线程 //ctsDrawingTask.Cancel(); if (hRoi != null) { hRoi.ClearDrawingObject(); hRoi.Dispose(); hRoi = null; } Thread.Sleep(100); } } } string _color = "green"; string color { get { return _color; } set { _color = value; } } private RoiType enumRoiType = RoiType.None; HDrawingObject hRoi = null; public Object oRoi { get { if (hRoi == null) return null; switch (enumRoiType) { case RoiType.Rectangle2: { //获取矩形参数生成Roi string[] str = { "row", "column", "phi", "length1", "length2" }; HTuple val = hRoi.GetDrawingObjectParams(str); //注意参数顺序 return new HRectangle2(val[1].D, val[0].D, val[2].D, (val[3].D * 2), (val[4].D * 2)); } case RoiType.Circle: { //获取圆形参数生成Roi string[] str = { "row", "column", "radius" }; HTuple val = hRoi.GetDrawingObjectParams(str); //注意参数顺序 return new HCircle(val[1].D, val[0].D, val[2].D); } case RoiType.Ellipse: { //获取线段参数生成Roi(start_angle和end_angle都是弧度) //phi为前半轴的方向(以弧度为单位) string[] str = { "row", "column", "radius", "start_angle", "end_angle" }; HTuple val = hRoi.GetDrawingObjectParams(str); //Debug.WriteLine($"row:{val[0].D},column:{val[1].D},phi:{val[2].D}" + // $",radius1:{val[3].D},radius2:{val[4].D},start_phi:{val[5].D},end_phi:{val[6].D}"); //注意参数顺序 return new HEllipse(val[1].D, val[0], 0, val[2].D, val[2].D, val[3].D, val[4].D); } case RoiType.Segment: { //获取线段参数生成Roi string[] str = { "row1", "column1", "row2", "column2" }; HTuple val = hRoi.GetDrawingObjectParams(str); //注意参数顺序 return new HSegment(val[1].D, val[0].D, val[3].D, val[2].D); } case RoiType.None: default: return null; } } set { Type type = value?.GetType(); if (hRoi != null) { hRoi.ClearDrawingObject(); hRoi.Dispose(); hRoi = null; } if (typeof(HRectangle2) == type) { enumRoiType = RoiType.Rectangle2; hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2 , (HTuple)(((HRectangle2)value).Row), (HTuple)(((HRectangle2)value).Column), (HTuple)(((HRectangle2)value).Phi) , (HTuple)(((HRectangle2)value).SemiLength1), (HTuple)(((HRectangle2)value).SemiLength2)); } else if (typeof(HCircle) == type) { enumRoiType = RoiType.Circle; hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE , (HTuple)(((HCircle)value).Row), (HTuple)(((HCircle)value).Column), (HTuple)(((HCircle)value).Radius)); } else if (typeof(HEllipse) == type) { enumRoiType = RoiType.Ellipse; hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.CIRCLE_SECTOR , (HTuple)(((HEllipse)value).Row), (HTuple)(((HEllipse)value).Column), (HTuple)(((HEllipse)value).Radius1) , (HTuple)(((HEllipse)value).StartAngle), (HTuple)(((HEllipse)value).EndAngle)); } else if (typeof(HSegment) == type) { enumRoiType = RoiType.Segment; hRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE , (HTuple)(((HSegment)value).BeginRow), (HTuple)(((HSegment)value).BeginColumn) , (HTuple)(((HSegment)value).EndRow), (HTuple)(((HSegment)value).EndColumn)); } else { enumRoiType = RoiType.None; if (hRoi != null) { hRoi.ClearDrawingObject(); hRoi.Dispose(); hRoi = null; } } if (hRoi != null && bAollowDraw) { //把绘制对象重新显示到halcon窗口上 hWindowControl.HalconWindow.AttachDrawingObjectToWindow(hRoi); } } } static int winRow, winCol, winWidth, winHeight, partWidth, partHeight; static HTuple imgWidth, imgHeight; /// /// 显示图片(异步) /// /// /// /// public async void ShowHoImageAsync(HObject ho_image, HWindow hWindow, bool autoSize = true) { if (ho_image == null || !ho_image.IsInitialized()) { if (hWindow != null && hWindow.IsInitialized()) { HOperatorSet.ClearWindow(hWindow); } } else { await ShowImageAsync(hWindow, ho_image, autoSize); } } /// /// 显示图片(同步) /// /// /// public void ShowHoImage(HObject ho_image, bool autoSize = true) { _hImage = ho_image; if (hWindowControl != null && hWindowControl.IsAccessible) { HOperatorSet.ClearWindow(hWindowControl.HalconWindow); } if (ho_image == null) { return; } try { if (autoSize && bAutoSize) { HOperatorSet.GetImageSize(ho_image, out HTuple imgWidth, out HTuple imgHeight); if (imgWidth.Length > 0) { hWindowControl.HalconWindow.GetWindowExtents(out int winRow, out int winCol, out int winWidth, out int winHeight); double partWidth, partHeight; if (winWidth < winHeight) { partWidth = imgWidth; partHeight = imgWidth * winHeight / winWidth; } else { partWidth = imgHeight * winWidth / winHeight; partHeight = imgHeight; } //计算比例 double scale = Math.Max(1.0 * imgWidth.D / winWidth, 1.0 * imgHeight.D / winHeight); double w = winWidth * scale; double h = winHeight * scale; double row1 = -(h - imgHeight.D) / 2; double col1 = -(w - imgWidth.D) / 2; double row2 = imgHeight.D + (h - imgHeight.D) / 2; double col2 = imgWidth.D + (w - imgWidth.D) / 2; //居中等比例 hWindowControl.HalconWindow.SetPart(row1, col1, row2, col2); } } HOperatorSet.DispObj(ho_image, hWindowControl.HalconWindow); } catch (HOperatorException ex) { Debug.WriteLine($"【{DateTime.Now:HH:mm:ss.fff}】错误消息: {ex.Message}"); Debug.WriteLine($"【{DateTime.Now:HH:mm:ss.fff}】错误代码: {ex.GetErrorCode()}"); } catch (Exception ex) { Debug.WriteLine($"【{DateTime.Now:HH:mm:ss.fff}】Error displaying image: {ex.Message}"); } return; } private async Task ShowImageAsync(HWindow hWindow, HObject ho_image, bool autoSize = true) { return await Task.Run(() => { if (ho_image == null || !ho_image.IsInitialized()) { try { if (hWindow != null && hWindow.IsInitialized()) { HOperatorSet.ClearWindow(hWindow); } } catch { return false; } return true; } try { if (hWindow != null && hWindow.IsInitialized()) { HOperatorSet.ClearWindow(hWindow); } if (autoSize) { HOperatorSet.GetImageSize(ho_image, out HTuple imgWidth, out HTuple imgHeight); if (imgWidth.Length > 0) { hWindow.GetWindowExtents(out int winRow, out int winCol, out int winWidth, out int winHeight); double partWidth, partHeight; if (winWidth < winHeight) { partWidth = imgWidth; partHeight = imgWidth * winHeight / winWidth; } else { partWidth = imgHeight * winWidth / winHeight; partHeight = imgHeight; } //计算比例 double scale = Math.Max(1.0 * imgWidth.D / winWidth, 1.0 * imgHeight.D / winHeight); double w = winWidth * scale; double h = winHeight * scale; double row1 = -(h - imgHeight.D) / 2; double col1 = -(w - imgWidth.D) / 2; double row2 = imgHeight.D + (h - imgHeight.D) / 2; double col2 = imgWidth.D + (w - imgWidth.D) / 2; //居中等比例 hWindow.SetPart(row1, col1, row2, col2); } } HOperatorSet.DispObj(ho_image, hWindow); } catch { return false; } return true; }); } public HWindow GetHalconWindow() { return this.hWindowControl.HalconWindow; } public void ClearObj() { try { if (this.hWindowControl != null && hWindowControl.IsAccessible) { HOperatorSet.ClearWindow(hWindowControl.HalconWindow); } } catch { } } public void ShowObj(HObject ho_object) { try { if (ho_object != null && ho_object.IsInitialized()) { HOperatorSet.DispObj(ho_object, this.hWindowControl.HalconWindow); } } catch { } } public void DispObj(HObject ho_object, string color) { try { if (ho_object != null && ho_object.IsInitialized()) { SetColor(color); HOperatorSet.DispObj(ho_object, this.hWindowControl.HalconWindow); } } catch { } } public void DispObj(HObject ho_object, bool result = true) { try { if (ho_object != null && ho_object.IsInitialized()) { string color = result ? "green" : "red"; SetColor(color); HOperatorSet.DispObj(ho_object, this.hWindowControl.HalconWindow); } } catch { } } public void ShowMsg(string msg, double x = 0, double y = 0, string color = "green") { try { SetColor(color); disp_message(this.hWindowControl.HalconWindow, msg, "image", (HTuple)y, (HTuple)x, color, "true"); } catch { } } public void ShowMsg(string msg, bool result, double x = 0, double y = 0, int size = 0) { try { if (size > 0) set_display_font(this.hWindowControl.HalconWindow, size, "mono", "true", "false"); string color = result ? "green" : "red"; SetColor(color); disp_message(this.hWindowControl.HalconWindow, msg, "image", (HTuple)y, (HTuple)x, result ? "green" : "red", "true"); } catch { } } public void SetColor(string color = "") { try { if (color.TrimEnd() == "") { color = GetRandomColor(); //color = this.color; } if (this.color != color) { HOperatorSet.SetColor(this.hWindowControl.HalconWindow, color); this.color = color; } } catch { } } /// /// 生成Halcon随机颜色 /// /// public string GetRandomColor() { // 获取当前时间的毫秒数作为种子 int seed = DateTime.Now.Millisecond; // 使用种子创建 Random 实例 Random random = new Random(seed); // 生成随机数 int randomNumber = random.Next(0, 18); // 延时随机时间变更随机种子 Thread.Sleep(randomNumber); string[] strsColors = new string[] { "red", "green","blue", "cyan", "magenta", "yellow", "dim gray", "gray","light gray", "medium slate blue", "coral", "slate blue", "spring green", "orange red", "orange", "dark olive green","pink", "forest green", "cadet blue" }; if (randomNumber <= strsColors.Length) { return strsColors[randomNumber]; } else { return strsColors[0]; } } public void SetFont(HTuple hv_Size, string hv_Font = "mono", string hv_Bold = "true", string hv_Slant = "false") { set_display_font(this.hWindowControl.HalconWindow, hv_Size, hv_Font, hv_Bold, hv_Slant); } /// /// 设置符号大小 /// /// /// /// /// /// public static void set_display_font(HTuple hv_WindowHandle, HTuple hv_Size, string hv_Font = "mono", string hv_Bold = "true", string hv_Slant = "false") { // Local iconic variables // Local control variables HTuple hv_OS = new HTuple(), hv_Fonts = new HTuple(); HTuple hv_Style = new HTuple(), hv_Exception = new HTuple(); HTuple hv_AvailableFonts = new HTuple(), hv_Fdx = new HTuple(); HTuple hv_Indices = new HTuple(); HTuple hv_Font_COPY_INP_TMP = new HTuple(hv_Font); HTuple hv_Size_COPY_INP_TMP = new HTuple(hv_Size); // Initialize local and output iconic variables try { //This procedure sets the text font of the current window with //the specified attributes. // //Input parameters: //WindowHandle: The graphics window for which the font will be set //Size: The font size. If Size=-1, the default of 16 is used. //Bold: If set to 'true', a bold font is used //Slant: If set to 'true', a slanted font is used // hv_OS.Dispose(); HOperatorSet.GetSystem("operating_system", out hv_OS); if ((int)((new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr( new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(-1)))) != 0) { hv_Size_COPY_INP_TMP.Dispose(); hv_Size_COPY_INP_TMP = 16; } if ((int)(new HTuple(((hv_OS.TupleSubstr(0, 2))).TupleEqual("Win"))) != 0) { //Restore previous behaviour using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Size = ((1.13677 * hv_Size_COPY_INP_TMP)).TupleInt() ; hv_Size_COPY_INP_TMP.Dispose(); hv_Size_COPY_INP_TMP = ExpTmpLocalVar_Size; } } } else { using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Size = hv_Size_COPY_INP_TMP.TupleInt() ; hv_Size_COPY_INP_TMP.Dispose(); hv_Size_COPY_INP_TMP = ExpTmpLocalVar_Size; } } } if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("Courier"))) != 0) { hv_Fonts.Dispose(); hv_Fonts = new HTuple(); hv_Fonts[0] = "Courier"; hv_Fonts[1] = "Courier 10 Pitch"; hv_Fonts[2] = "Courier New"; hv_Fonts[3] = "CourierNew"; hv_Fonts[4] = "Liberation Mono"; } else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("mono"))) != 0) { hv_Fonts.Dispose(); hv_Fonts = new HTuple(); hv_Fonts[0] = "Consolas"; hv_Fonts[1] = "Menlo"; hv_Fonts[2] = "Courier"; hv_Fonts[3] = "Courier 10 Pitch"; hv_Fonts[4] = "FreeMono"; hv_Fonts[5] = "Liberation Mono"; } else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("sans"))) != 0) { hv_Fonts.Dispose(); hv_Fonts = new HTuple(); hv_Fonts[0] = "Luxi Sans"; hv_Fonts[1] = "DejaVu Sans"; hv_Fonts[2] = "FreeSans"; hv_Fonts[3] = "Arial"; hv_Fonts[4] = "Liberation Sans"; } else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("serif"))) != 0) { hv_Fonts.Dispose(); hv_Fonts = new HTuple(); hv_Fonts[0] = "Times New Roman"; hv_Fonts[1] = "Luxi Serif"; hv_Fonts[2] = "DejaVu Serif"; hv_Fonts[3] = "FreeSerif"; hv_Fonts[4] = "Utopia"; hv_Fonts[5] = "Liberation Serif"; } else { hv_Fonts.Dispose(); hv_Fonts = new HTuple(hv_Font_COPY_INP_TMP); } hv_Style.Dispose(); hv_Style = ""; if ((int)(new HTuple(((HTuple)hv_Bold).TupleEqual("true"))) != 0) { using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Style = hv_Style + "Bold"; hv_Style.Dispose(); hv_Style = ExpTmpLocalVar_Style; } } } else if ((int)(new HTuple(((HTuple)hv_Bold).TupleNotEqual("false"))) != 0) { hv_Exception.Dispose(); hv_Exception = "Wrong value of control parameter Bold"; throw new HalconException(hv_Exception); } if ((int)(new HTuple(((HTuple)hv_Slant).TupleEqual("true"))) != 0) { using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Style = hv_Style + "Italic"; hv_Style.Dispose(); hv_Style = ExpTmpLocalVar_Style; } } } else if ((int)(new HTuple(((HTuple)hv_Slant).TupleNotEqual("false"))) != 0) { hv_Exception.Dispose(); hv_Exception = "Wrong value of control parameter Slant"; throw new HalconException(hv_Exception); } if ((int)(new HTuple(hv_Style.TupleEqual(""))) != 0) { hv_Style.Dispose(); hv_Style = "Normal"; } hv_AvailableFonts.Dispose(); HOperatorSet.QueryFont(hv_WindowHandle, out hv_AvailableFonts); hv_Font_COPY_INP_TMP.Dispose(); hv_Font_COPY_INP_TMP = ""; for (hv_Fdx = 0; (int)hv_Fdx <= (int)((new HTuple(hv_Fonts.TupleLength())) - 1); hv_Fdx = (int)hv_Fdx + 1) { hv_Indices.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_Indices = hv_AvailableFonts.TupleFind( hv_Fonts.TupleSelect(hv_Fdx)); } if ((int)(new HTuple((new HTuple(hv_Indices.TupleLength())).TupleGreater( 0))) != 0) { if ((int)(new HTuple(((hv_Indices.TupleSelect(0))).TupleGreaterEqual(0))) != 0) { hv_Font_COPY_INP_TMP.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_Font_COPY_INP_TMP = hv_Fonts.TupleSelect( hv_Fdx); } break; } } } if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual(""))) != 0) { throw new HalconException("Wrong value of control parameter Font"); } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Font = (((hv_Font_COPY_INP_TMP + "-") + hv_Style) + "-") + hv_Size_COPY_INP_TMP; hv_Font_COPY_INP_TMP.Dispose(); hv_Font_COPY_INP_TMP = ExpTmpLocalVar_Font; } } HOperatorSet.SetFont(hv_WindowHandle, hv_Font_COPY_INP_TMP); hv_Font_COPY_INP_TMP.Dispose(); hv_Size_COPY_INP_TMP.Dispose(); hv_OS.Dispose(); hv_Fonts.Dispose(); hv_Style.Dispose(); hv_Exception.Dispose(); hv_AvailableFonts.Dispose(); hv_Fdx.Dispose(); hv_Indices.Dispose(); return; } catch (HalconException HDevExpDefaultException) { hv_Font_COPY_INP_TMP.Dispose(); hv_Size_COPY_INP_TMP.Dispose(); hv_OS.Dispose(); hv_Fonts.Dispose(); hv_Style.Dispose(); hv_Exception.Dispose(); hv_AvailableFonts.Dispose(); hv_Fdx.Dispose(); hv_Indices.Dispose(); throw HDevExpDefaultException; } } public static void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem, HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box) { // Local iconic variables // Local control variables HTuple hv_GenParamName = new HTuple(), hv_GenParamValue = new HTuple(); HTuple hv_Color_COPY_INP_TMP = new HTuple(hv_Color); HTuple hv_Column_COPY_INP_TMP = new HTuple(hv_Column); HTuple hv_CoordSystem_COPY_INP_TMP = new HTuple(hv_CoordSystem); HTuple hv_Row_COPY_INP_TMP = new HTuple(hv_Row); try { if ((int)((new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr( new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(new HTuple())))) != 0) { hv_Color_COPY_INP_TMP.Dispose(); hv_Column_COPY_INP_TMP.Dispose(); hv_CoordSystem_COPY_INP_TMP.Dispose(); hv_Row_COPY_INP_TMP.Dispose(); hv_GenParamName.Dispose(); hv_GenParamValue.Dispose(); return; } if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0) { hv_Row_COPY_INP_TMP.Dispose(); hv_Row_COPY_INP_TMP = 12; } if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0) { hv_Column_COPY_INP_TMP.Dispose(); hv_Column_COPY_INP_TMP = 12; } // //Convert the parameter Box to generic parameters. hv_GenParamName.Dispose(); hv_GenParamName = new HTuple(); hv_GenParamValue.Dispose(); hv_GenParamValue = new HTuple(); if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(0))) != 0) { if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleEqual("false"))) != 0) { //Display no box using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat( "box"); hv_GenParamName.Dispose(); hv_GenParamName = ExpTmpLocalVar_GenParamName; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat( "false"); hv_GenParamValue.Dispose(); hv_GenParamValue = ExpTmpLocalVar_GenParamValue; } } } else if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleNotEqual( "true"))) != 0) { //Set a color other than the default. using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat( "box_color"); hv_GenParamName.Dispose(); hv_GenParamName = ExpTmpLocalVar_GenParamName; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat( hv_Box.TupleSelect(0)); hv_GenParamValue.Dispose(); hv_GenParamValue = ExpTmpLocalVar_GenParamValue; } } } } if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(1))) != 0) { if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleEqual("false"))) != 0) { //Display no shadow. using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat( "shadow"); hv_GenParamName.Dispose(); hv_GenParamName = ExpTmpLocalVar_GenParamName; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat( "false"); hv_GenParamValue.Dispose(); hv_GenParamValue = ExpTmpLocalVar_GenParamValue; } } } else if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleNotEqual( "true"))) != 0) { //Set a shadow color other than the default. using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamName = hv_GenParamName.TupleConcat( "shadow_color"); hv_GenParamName.Dispose(); hv_GenParamName = ExpTmpLocalVar_GenParamName; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_GenParamValue = hv_GenParamValue.TupleConcat( hv_Box.TupleSelect(1)); hv_GenParamValue.Dispose(); hv_GenParamValue = ExpTmpLocalVar_GenParamValue; } } } } //Restore default CoordSystem behavior. if ((int)(new HTuple(hv_CoordSystem_COPY_INP_TMP.TupleNotEqual("window"))) != 0) { hv_CoordSystem_COPY_INP_TMP.Dispose(); hv_CoordSystem_COPY_INP_TMP = "image"; } // if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(""))) != 0) { //disp_text does not accept an empty string for Color. hv_Color_COPY_INP_TMP.Dispose(); hv_Color_COPY_INP_TMP = new HTuple(); } // //HOperatorSet.DispText(hv_WindowHandle, hv_String, hv_CoordSystem_COPY_INP_TMP, // hv_Row_COPY_INP_TMP, hv_Column_COPY_INP_TMP, hv_Color_COPY_INP_TMP, hv_GenParamName,hv_GenParamValue); HOperatorSet.SetTposition(hv_WindowHandle, hv_Row_COPY_INP_TMP, hv_Column_COPY_INP_TMP); HOperatorSet.WriteString(hv_WindowHandle, hv_String); hv_Color_COPY_INP_TMP.Dispose(); hv_Column_COPY_INP_TMP.Dispose(); hv_CoordSystem_COPY_INP_TMP.Dispose(); hv_Row_COPY_INP_TMP.Dispose(); hv_GenParamName.Dispose(); hv_GenParamValue.Dispose(); return; } catch (HalconException HDevExpDefaultException) { hv_Color_COPY_INP_TMP.Dispose(); hv_Column_COPY_INP_TMP.Dispose(); hv_CoordSystem_COPY_INP_TMP.Dispose(); hv_Row_COPY_INP_TMP.Dispose(); hv_GenParamName.Dispose(); hv_GenParamValue.Dispose(); throw HDevExpDefaultException; } } // 记录控件运行状态 private bool bMouseOnLeftButton = false, bMouseOnRightButton = false; private void hWindowControl_HMouseDown(object sender, HMouseEventArgs e) { try { switch (e.Button) { case MouseButtons.Left: bMouseOnLeftButton = true; break; case MouseButtons.Right: bMouseOnRightButton = true; break; case MouseButtons.Middle: break; default: break; } MouseEventArgs mouseEventArgs = new MouseEventArgs(e.Button, e.Clicks, (int)e.X, (int)e.Y, e.Delta); event_mouseDown(sender, mouseEventArgs); } catch { } } private void hWindowControl_HMouseUp(object sender, HMouseEventArgs e) { try { switch (e.Button) { case MouseButtons.Left: bMouseOnLeftButton = false; break; case MouseButtons.Right: bMouseOnRightButton = false; break; case MouseButtons.Middle: break; default: break; } } catch { } } HTuple positionRow = new HTuple(); HTuple positionColumn = new HTuple(); private void hWindowControl_HMouseMove(object sender, HMouseEventArgs e) { if (hImage == null) { return; } if (mouseIndexStripMenuItem.Checked) { //this.BeginInvoke(new Action(() => //{ try { HOperatorSet.GetMposition(hWindowControl.HalconWindow, out HTuple positionRow, out HTuple positionColumn, out HTuple button_state); if (this.positionRow.Length == 0 || this.positionColumn.Length == 0) { this.positionRow = positionRow; this.positionColumn = positionColumn; } if (this.positionRow.D != positionRow.D || this.positionColumn.D != positionColumn.D) { this.positionRow = positionRow; this.positionColumn = positionColumn; } //启动绘画模式需要取消缩放 if (bGetIndex) { // 创建新CancellationTokenSource避免无法重启 ctsIndexTask = new CancellationTokenSource(); Task.Run(() => GetIndexTaskAsync(ctsIndexTask.Token), ctsIndexTask.Token); } else { ctsIndexTask.Cancel(); } } catch { } //})); } } private static readonly object _lock = new object(); /// /// 鼠标索引取消请求 /// CancellationTokenSource ctsIndexTask = new CancellationTokenSource(); public bool _bGetIndex = false; /// /// 启用鼠标索引模式标记 /// public bool bGetIndex { get { return _bGetIndex; } set { _bGetIndex = value; ////启动绘画模式需要取消缩放 //if (bGetIndex) //{ // // 创建新CancellationTokenSource避免无法重启 // ctsIndexTask = new CancellationTokenSource(); // Task.Run(() => GetIndexTaskAsync(ctsIndexTask.Token), ctsIndexTask.Token); //} //else //{ // ctsIndexTask.Cancel(); //} } } private void GetIndexTaskAsync(CancellationToken token) { if (!_bGetIndex || ctsIndexTask.IsCancellationRequested) { if (this.StatusLabel.Text != string.Empty) this.StatusLabel.Text = string.Empty; return; } if (hImage != null) { try { lock (_lock) { // 判断是否为灰度图 using (HDevDisposeHelper dh = new HDevDisposeHelper()) { HOperatorSet.CountChannels(hImage, out HTuple hv_Channels); if (hv_Channels.TupleInt() != 1) { HOperatorSet.Rgb1ToGray(hImage, out HObject ho_ImageGray); HOperatorSet.Decompose3(hImage, out HObject ho_ImageR, out HObject ho_ImageG, out HObject ho_ImageB); HOperatorSet.TransFromRgb(ho_ImageR, ho_ImageG, ho_ImageB, out HObject ho_ImageH, out HObject ho_ImageS, out HObject ho_ImageV, "hsv"); try { if (positionRow.Length > 0 && positionRow.D > 0 && positionColumn.D > 0) { HOperatorSet.GetGrayval(ho_ImageGray, positionRow, positionColumn, out HTuple GrayValue); HOperatorSet.GetGrayval(ho_ImageR, positionRow, positionColumn, out HTuple RValue); HOperatorSet.GetGrayval(ho_ImageG, positionRow, positionColumn, out HTuple GValue); HOperatorSet.GetGrayval(ho_ImageB, positionRow, positionColumn, out HTuple BValue); HOperatorSet.GetGrayval(ho_ImageH, positionRow, positionColumn, out HTuple HValue); HOperatorSet.GetGrayval(ho_ImageS, positionRow, positionColumn, out HTuple SValue); HOperatorSet.GetGrayval(ho_ImageV, positionRow, positionColumn, out HTuple VValue); this.Invoke(new Action(() => { if (positionRow.Length > 0) { this.StatusLabel.ForeColor = Color.White; this.StatusLabel.Text = $"Row:{positionRow},Column:{positionColumn},灰度值{GrayValue.D:F0}," + $"RGB({RValue.D:F0},{GValue.D:F0},{BValue.D:F0})," + $"HSV({HValue.D:F0},{SValue.D:F0},{VValue.D:F0})"; } })); } } catch { } ho_ImageR.Dispose(); ho_ImageG.Dispose(); ho_ImageB.Dispose(); ho_ImageH.Dispose(); ho_ImageS.Dispose(); ho_ImageV.Dispose(); ho_ImageGray.Dispose(); } else { HOperatorSet.Rgb1ToGray(hImage, out HObject ho_ImageGray); try { if (positionRow.Length > 0) { HOperatorSet.GetGrayval(ho_ImageGray, positionRow, positionColumn, out HTuple GrayValue); //HOperatorSet.GenRectangle1(out HObject ho_Rectangle, positionRow - 5, positionColumn - 5, positionRow + 5, positionColumn + 5); //HOperatorSet.Intensity(ho_Rectangle, ho_ImageGray, out HTuple GrayValue, out HTuple hv_Deviation); this.Invoke(new Action(() => { if (positionRow.Length > 0) { this.StatusLabel.ForeColor = Color.White; this.StatusLabel.Text = $"Row:{positionRow},Column:{positionColumn},灰度值{GrayValue.D:F0}"; } })); } } catch { } ho_ImageGray.Dispose(); } } } } catch { } } //while (true) //{ // // 等待一段时间后再次检查 // System.Threading.Thread.Sleep(500); // 0.5秒钟 // if (!_bGetIndex || ctsIndexTask.IsCancellationRequested) // { // if (this.StatusLabel.Text != string.Empty) // this.StatusLabel.Text = string.Empty; // return; // } // if (hImage != null) // { // try // { // lock (_lock) // { // // 判断是否为灰度图 // using (HDevDisposeHelper dh = new HDevDisposeHelper()) // { // HOperatorSet.CountChannels(hImage, out HTuple hv_Channels); // if (hv_Channels.TupleInt() != 1) // { // HOperatorSet.Rgb1ToGray(hImage, out HObject ho_ImageGray); // HOperatorSet.Decompose3(hImage, out HObject ho_ImageR, out HObject ho_ImageG, out HObject ho_ImageB); // HOperatorSet.TransFromRgb(ho_ImageR, ho_ImageG, ho_ImageB, out HObject ho_ImageH, out HObject ho_ImageS, out HObject ho_ImageV, "hsv"); // try // { // if (positionRow.Length > 0) // { // HOperatorSet.GetGrayval(ho_ImageGray, positionRow, positionColumn, out HTuple GrayValue); // HOperatorSet.GetGrayval(ho_ImageR, positionRow, positionColumn, out HTuple RValue); // HOperatorSet.GetGrayval(ho_ImageG, positionRow, positionColumn, out HTuple GValue); // HOperatorSet.GetGrayval(ho_ImageB, positionRow, positionColumn, out HTuple BValue); // HOperatorSet.GetGrayval(ho_ImageH, positionRow, positionColumn, out HTuple HValue); // HOperatorSet.GetGrayval(ho_ImageS, positionRow, positionColumn, out HTuple SValue); // HOperatorSet.GetGrayval(ho_ImageV, positionRow, positionColumn, out HTuple VValue); // this.BeginInvoke(new Action(() => // { // if (positionRow.Length > 0) // { // this.StatusLabel.ForeColor = Color.White; // this.StatusLabel.Text = $"Row:{positionRow},Column:{positionColumn},灰度值{GrayValue.D:F0}," + // $"RGB({RValue.D:F0},{GValue.D:F0},{BValue.D:F0})," + // $"HSV({HValue.D:F0},{SValue.D:F0},{VValue.D:F0})"; // } // })); // } // } // catch { } // ho_ImageR.Dispose(); ho_ImageG.Dispose(); ho_ImageB.Dispose(); // ho_ImageH.Dispose(); ho_ImageS.Dispose(); ho_ImageV.Dispose(); // ho_ImageGray.Dispose(); // } // else // { // HOperatorSet.Rgb1ToGray(hImage, out HObject ho_ImageGray); // try // { // if (positionRow.Length > 0) // { // HOperatorSet.GetGrayval(ho_ImageGray, positionRow, positionColumn, out HTuple GrayValue); // //HOperatorSet.GenRectangle1(out HObject ho_Rectangle, positionRow - 5, positionColumn - 5, positionRow + 5, positionColumn + 5); // //HOperatorSet.Intensity(ho_Rectangle, ho_ImageGray, out HTuple GrayValue, out HTuple hv_Deviation); // this.BeginInvoke(new Action(() => // { // if (positionRow.Length > 0) // this.StatusLabel.Text = $"Row:{positionRow},Column:{positionColumn},灰度值{GrayValue.D:F0}"; // })); // } // } // catch { } // ho_ImageGray.Dispose(); // } // } // } // } // catch { } // } //} } private void UserHSmartWindowControl_HMouseWheel(object sender, MouseEventArgs e) { hWindowControl.HSmartWindowControl_MouseWheel(sender, e); } private void UserHSmartWindowControl_SizeChanged(object sender, EventArgs e) { try { if (imgWidth == null || imgHeight == null || imgWidth.Length == 0 || imgHeight.Length == 0) return; } catch { } } private void autoSizeStripMenuItem_Click(object sender, EventArgs e) { autoSizeStripMenuItem.Checked = !autoSizeStripMenuItem.Checked; bAutoSize = !bAutoSize; } private void mouseIndexStripMenuItem_Click(object sender, EventArgs e) { mouseIndexStripMenuItem.Checked = !mouseIndexStripMenuItem.Checked; bGetIndex = !bGetIndex; } private void resizeImageStripMenuItem_Click(object sender, EventArgs e) { ShowHoImage(hImage); } private void hWindowControl_HMouseDoubleClick(object sender, HMouseEventArgs e) { MouseEventArgs mouseEventArgs = new MouseEventArgs(e.Button, e.Clicks, (int)e.X, (int)e.Y, e.Delta); event_mouseDoubleClick(sender, mouseEventArgs); } } }