ShowVisionRender.xaml.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ImageFile;
  3. using Cognex.VisionPro3D;
  4. using log4net.Core;
  5. using MahApps.Metro.Controls;
  6. using Prism.Events;
  7. using Prism.Ioc;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Forms.Integration;
  17. using System.Windows.Interop;
  18. using TeamAAS_VP;
  19. using TeamAAS_VP.Core;
  20. using TeamAAS_VP.Enums;
  21. using TeamAAS_VP.Events;
  22. using TeamAAS_VP.Interfaces;
  23. using TeamAAS_VP.Models;
  24. using TeamAAS_VP.Resources.Languages;
  25. using TeamAAS_VP.ViewModels;
  26. using TeamAAS_VP.ViewModels.Home;
  27. //using static MaterialDesignThemes.Wtf.ToolBar;
  28. namespace TeamAAS_VP.Views.Home
  29. {
  30. /// <summary>
  31. /// Interaction logic for ShowVisionRender
  32. /// </summary>
  33. public partial class ShowVisionRender : UserControl
  34. {
  35. private const string Render2DKeySuffix = ":2D";
  36. private const string Render3DKeySuffix = ":3D";
  37. private static string Get2DKey(Guid id) => id.ToString() + Render2DKeySuffix;
  38. private static string Get3DKey(Guid id) => id.ToString() + Render3DKeySuffix;
  39. ShowVisionRenderViewModel viewModel;
  40. Dictionary<string, WindowsFormsHost> vmRenders;
  41. Dictionary<Guid, TextBlock> Titles;
  42. IEventAggregator _eventAggregator;
  43. private readonly IProductService _productService;
  44. private readonly Prism.Services.Dialogs.IDialogService _dialogService;
  45. private CancellationTokenSource _saveImageCts = new CancellationTokenSource();
  46. private readonly SemaphoreSlim _saveSemaphore = new SemaphoreSlim(5, 5);
  47. private List<Models.DelaySaveImage> delaySaveImages = new List<Models.DelaySaveImage>();
  48. public ShowVisionRender()
  49. {
  50. InitializeComponent();
  51. vmRenders = new Dictionary<string, WindowsFormsHost>();
  52. Titles = new Dictionary<Guid, TextBlock>();
  53. viewModel = DataContext as ShowVisionRenderViewModel;
  54. _eventAggregator = viewModel._eventAggregator;
  55. _productService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<IProductService>();
  56. // 新增:DialogService
  57. _dialogService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<Prism.Services.Dialogs.IDialogService>();
  58. viewModel.UpdateLayout += ViewModel_UpdateLayout;
  59. // ThreadOption.BackgroundThread:让订阅者在后台线程执行,Publish() 立即返回,
  60. // 图像处理流程不再等待 UI 更新和保存完成才回复完成信号
  61. _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(
  62. UpdateRenderModuleSource,
  63. ThreadOption.BackgroundThread);
  64. _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
  65. _eventAggregator.GetEvent<DelaySaveImageNotification>().Subscribe(UpdateDelaySaveImage);
  66. }
  67. private bool GetView3DUse()
  68. {
  69. try
  70. {
  71. var configService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<IConfigService>();
  72. if(configService.GetSystemConfiguration().PickPointNum==0)
  73. {
  74. return false;
  75. }
  76. else
  77. {
  78. return true;
  79. }
  80. //return true;
  81. }
  82. catch
  83. {
  84. return false;
  85. }
  86. }
  87. private void UpdateRenderModuleSource(ShowRender render)
  88. {
  89. if (render == null)
  90. return;
  91. // 【关键】在后台线程深拷贝 ICogImage,防止下一次视觉流程运行覆盖像素数据
  92. ICogImage imageCopy = null;
  93. try
  94. {
  95. imageCopy = render.Image?.CopyBase(CogImageCopyModeConstants.CopyPixels);
  96. }
  97. catch (Exception ex)
  98. {
  99. LogHelper.WriteLogError("深拷贝 ICogImage 失败", ex);
  100. }
  101. // ICogRecord 和 Graphic 通常每次运行新创建,引用不会被覆盖,无需深拷贝
  102. var graphic = render.Graphic;
  103. var record = render.Record;
  104. var rangeImage = render.RangeImage;
  105. var greyImage = render.GreyImage;
  106. // 派发 UI 更新到 WPF UI 线程(fire-and-forget,不等待完成)
  107. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  108. {
  109. if (render.Is3DModel == true && GetView3DUse() == true)
  110. {
  111. if (!vmRenders.TryGetValue(Get3DKey(render.Id), out var host3D))
  112. return;
  113. var display3D = host3D.Child as Cognex.VisionPro3D.Cog3DDisplayV2WF;
  114. if (display3D == null)
  115. return;
  116. try
  117. {
  118. display3D.Clear();
  119. if (rangeImage == null || greyImage == null)
  120. return;
  121. var rImgG = new Cog3DRangeImageGraphic(rangeImage, greyImage);
  122. display3D.Add(rImgG, "__default");
  123. display3D.FitView();
  124. }
  125. catch (System.Windows.Forms.AxHost.InvalidActiveXStateException)
  126. {
  127. }
  128. }
  129. if (!vmRenders.TryGetValue(Get2DKey(render.Id), out var host2D))
  130. return;
  131. var recordDisplay = host2D.Child as Cognex.VisionPro.CogRecordDisplay;
  132. if (recordDisplay == null)
  133. return;
  134. try
  135. {
  136. recordDisplay.Record = null;
  137. recordDisplay.Image = imageCopy; // ✅ 深拷贝,安全
  138. recordDisplay.StaticGraphics.Clear();
  139. if (graphic != null)
  140. recordDisplay.StaticGraphics.AddList(graphic, "");
  141. if (record != null)
  142. recordDisplay.Record = record;
  143. if (render.IsSaveImage)
  144. {
  145. // 传递深拷贝后的图像引用给保存逻辑
  146. var renderForSave = new ShowRender
  147. {
  148. Id = render.Id,
  149. Image = imageCopy,
  150. Record = record,
  151. Graphic = graphic,
  152. Result = render.Result,
  153. IsSaveImage = render.IsSaveImage,
  154. SaveImageModel = render.SaveImageModel,
  155. SaveImagePathModel = render.SaveImagePathModel,
  156. SavePath = render.SavePath,
  157. IsCompress = render.IsCompress,
  158. IsDelaySaveImage = render.IsDelaySaveImage,
  159. ImageFileName = render.ImageFileName,
  160. ProceductName = render.ProceductName,
  161. Is3DModel = render.Is3DModel,
  162. };
  163. RequestSaveImage(renderForSave, recordDisplay);
  164. }
  165. }
  166. catch (System.Windows.Forms.AxHost.InvalidActiveXStateException)
  167. {
  168. }
  169. }));
  170. }
  171. private void AddRenderPair(Guid id, string displayName)
  172. {
  173. // 2D
  174. var display2D = new Cognex.VisionPro.CogRecordDisplay() { Tag = displayName };
  175. display2D.HandleCreated += (s, e) =>
  176. {
  177. try
  178. {
  179. display2D.HorizontalScrollBar = false;
  180. display2D.VerticalScrollBar = false;
  181. display2D.AutoFit = true;
  182. display2D.BackColor = System.Drawing.SystemColors.ActiveCaption;
  183. }
  184. catch (System.Windows.Forms.AxHost.InvalidActiveXStateException)
  185. {
  186. }
  187. };
  188. // 绑定双击:弹出预览窗口
  189. display2D.DoubleClick += (s, e) => OnDisplayDoubleClick(display2D);
  190. vmRenders.Add(Get2DKey(id), new WindowsFormsHost() { Tag = displayName, Child = display2D });
  191. // 3D:按配置创建
  192. if (!GetView3DUse())
  193. return;
  194. // 3D
  195. var display3D = new Cognex.VisionPro3D.Cog3DDisplayV2WF() { Tag = displayName };
  196. display3D.HandleCreated += (s, e) =>
  197. {
  198. try
  199. {
  200. display3D.BackColor = System.Drawing.SystemColors.ActiveCaption;
  201. }
  202. catch (System.Windows.Forms.AxHost.InvalidActiveXStateException)
  203. {
  204. }
  205. };
  206. vmRenders.Add(Get3DKey(id), new WindowsFormsHost() { Tag = displayName, Child = display3D });
  207. }
  208. private Grid CreateCellGrid(Guid id, string displayName, System.Windows.Media.FontFamily font)
  209. {
  210. var is3DEnabled = GetView3DUse();
  211. var cell = new Grid();
  212. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
  213. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  214. var title = new TextBlock()
  215. {
  216. Text = displayName,
  217. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  218. FontWeight = FontWeights.Bold,
  219. FontFamily = font,
  220. FontSize = 12,
  221. Foreground = System.Windows.Media.Brushes.Black
  222. };
  223. Titles[id] = title;
  224. var content = new Grid();
  225. if(is3DEnabled)
  226. {
  227. content.ColumnDefinitions.Add(new ColumnDefinition()); // 2D
  228. content.ColumnDefinitions.Add(new ColumnDefinition()); // 3D
  229. content.Children.Add(vmRenders[Get2DKey(id)]);
  230. content.Children.Add(vmRenders[Get3DKey(id)]);
  231. Grid.SetColumn(vmRenders[Get2DKey(id)], 0);
  232. Grid.SetColumn(vmRenders[Get3DKey(id)], 1);
  233. }
  234. else
  235. {
  236. content.ColumnDefinitions.Add(new ColumnDefinition()); // 仅 2D
  237. content.Children.Add(vmRenders[Get2DKey(id)]);
  238. Grid.SetColumn(vmRenders[Get2DKey(id)], 0);
  239. }
  240. cell.Children.Add(title);
  241. cell.Children.Add(content);
  242. Grid.SetRow(title, 0);
  243. Grid.SetRow(content, 1);
  244. return cell;
  245. }
  246. Grid grid1 = new Grid();
  247. Grid grid2 = new Grid();
  248. Grid grid3 = new Grid();
  249. Grid grid4 = new Grid();
  250. Grid grid5 = new Grid();
  251. Grid grid6 = new Grid();
  252. Grid grid7 = new Grid();
  253. Grid grid8 = new Grid();
  254. Grid grid9 = new Grid();
  255. Grid grid10 = new Grid();
  256. Grid grid11 = new Grid();
  257. Grid grid12 = new Grid();
  258. Grid grid13 = new Grid();
  259. Grid grid14 = new Grid();
  260. Grid grid15 = new Grid();
  261. Grid grid16 = new Grid();
  262. Grid grid17 = new Grid();
  263. Grid grid18 = new Grid();
  264. Grid grid19 = new Grid();
  265. Grid grid20 = new Grid();
  266. private void ViewModel_UpdateLayout(System.Collections.ObjectModel.ObservableCollection<Models.ShowRender> obj)
  267. {
  268. System.Windows.Media.FontFamily font = Application.Current.Resources["DefaultFont"] as System.Windows.Media.FontFamily;
  269. if (vmRenders.Count > 0)
  270. {
  271. foreach (var render in vmRenders)
  272. {
  273. render.Value.Dispose();
  274. }
  275. }
  276. vmRenders.Clear();
  277. gridRender.Children.Clear();
  278. gridRender.RowDefinitions.Clear();
  279. gridRender.ColumnDefinitions.Clear();
  280. Titles.Clear();
  281. if (obj == null || obj.Count == 0)
  282. return;
  283. // 先创建所有相机的 2D/3D 对
  284. for (int i = 0; i < obj.Count; i++)
  285. AddRenderPair(obj[i].Id, obj[i].DisplayName);
  286. switch (obj.Count)
  287. {
  288. case 1:
  289. {
  290. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  291. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  292. var cell = CreateCellGrid(obj[0].Id, obj[0].DisplayName, font);
  293. gridRender.Children.Add(cell);
  294. Grid.SetRow(cell, 0);
  295. Grid.SetColumn(cell, 0);
  296. gridRender.ShowGridLines = false;
  297. break;
  298. }
  299. case 2:
  300. {
  301. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  302. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  303. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  304. gridRender.ShowGridLines = true;
  305. var cell0 = CreateCellGrid(obj[0].Id, obj[0].DisplayName, font);
  306. var cell1 = CreateCellGrid(obj[1].Id, obj[1].DisplayName, font);
  307. gridRender.Children.Add(cell0);
  308. gridRender.Children.Add(cell1);
  309. Grid.SetRow(cell0, 0);
  310. Grid.SetColumn(cell0, 0);
  311. Grid.SetRow(cell1, 0);
  312. Grid.SetColumn(cell1, 1);
  313. break;
  314. }
  315. case 3:
  316. {
  317. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  318. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  319. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  320. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  321. gridRender.ShowGridLines = true;
  322. var cell0 = CreateCellGrid(obj[0].Id, obj[0].DisplayName, font);
  323. var cell1 = CreateCellGrid(obj[1].Id, obj[1].DisplayName, font);
  324. var cell2 = CreateCellGrid(obj[2].Id, obj[2].DisplayName, font);
  325. gridRender.Children.Add(cell0);
  326. gridRender.Children.Add(cell1);
  327. gridRender.Children.Add(cell2);
  328. Grid.SetRow(cell0, 0);
  329. Grid.SetColumn(cell0, 0);
  330. Grid.SetRow(cell1, 0);
  331. Grid.SetColumn(cell1, 1);
  332. Grid.SetRow(cell2, 1);
  333. Grid.SetColumn(cell2, 0);
  334. Grid.SetColumnSpan(cell2, 2);
  335. break;
  336. }
  337. case 4:
  338. {
  339. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  340. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  341. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  342. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  343. gridRender.ShowGridLines = true;
  344. for (int i = 0; i < 4; i++)
  345. {
  346. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  347. gridRender.Children.Add(cell);
  348. Grid.SetRow(cell, i / 2);
  349. Grid.SetColumn(cell, i % 2);
  350. }
  351. break;
  352. }
  353. case 5:
  354. {
  355. // 你的原布局:上面2个,下面3个(通过嵌套grid6)
  356. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  357. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  358. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  359. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  360. gridRender.ShowGridLines = true;
  361. var top0 = CreateCellGrid(obj[0].Id, obj[0].DisplayName, font);
  362. var top1 = CreateCellGrid(obj[1].Id, obj[1].DisplayName, font);
  363. var bottom = new Grid();
  364. bottom.ColumnDefinitions.Add(new ColumnDefinition());
  365. bottom.ColumnDefinitions.Add(new ColumnDefinition());
  366. bottom.ColumnDefinitions.Add(new ColumnDefinition());
  367. var b0 = CreateCellGrid(obj[2].Id, obj[2].DisplayName, font);
  368. var b1 = CreateCellGrid(obj[3].Id, obj[3].DisplayName, font);
  369. var b2 = CreateCellGrid(obj[4].Id, obj[4].DisplayName, font);
  370. bottom.Children.Add(b0);
  371. bottom.Children.Add(b1);
  372. bottom.Children.Add(b2);
  373. Grid.SetColumn(b0, 0);
  374. Grid.SetColumn(b1, 1);
  375. Grid.SetColumn(b2, 2);
  376. gridRender.Children.Add(top0);
  377. gridRender.Children.Add(top1);
  378. gridRender.Children.Add(bottom);
  379. Grid.SetRow(top0, 0);
  380. Grid.SetColumn(top0, 0);
  381. Grid.SetRow(top1, 0);
  382. Grid.SetColumn(top1, 1);
  383. Grid.SetRow(bottom, 1);
  384. Grid.SetColumn(bottom, 0);
  385. Grid.SetColumnSpan(bottom, 2);
  386. break;
  387. }
  388. case 6:
  389. {
  390. // 你的原布局:2行3列
  391. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  392. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  393. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  394. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  395. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  396. gridRender.ShowGridLines = true;
  397. for (int i = 0; i < 6; i++)
  398. {
  399. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  400. gridRender.Children.Add(cell);
  401. Grid.SetRow(cell, i / 3);
  402. Grid.SetColumn(cell, i % 3);
  403. }
  404. break;
  405. }
  406. case 7:
  407. {
  408. // 你的原布局:第一行4个,第二行3个(但原来只放到 col 0/1/2)
  409. // 这里保持原样:第一行4列,第二行3列(第4列留空)
  410. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  411. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  412. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  413. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  414. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  415. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  416. gridRender.ShowGridLines = true;
  417. for (int i = 0; i < 7; i++)
  418. {
  419. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  420. gridRender.Children.Add(cell);
  421. if (i < 4)
  422. {
  423. Grid.SetRow(cell, 0);
  424. Grid.SetColumn(cell, i);
  425. }
  426. else
  427. {
  428. Grid.SetRow(cell, 1);
  429. Grid.SetColumn(cell, i - 4);
  430. }
  431. }
  432. break;
  433. }
  434. case 8:
  435. {
  436. // 2行4列
  437. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  438. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  439. for (int i = 0; i < 4; i++)
  440. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  441. gridRender.ShowGridLines = true;
  442. for (int i = 0; i < 8; i++)
  443. {
  444. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  445. gridRender.Children.Add(cell);
  446. Grid.SetRow(cell, i / 4);
  447. Grid.SetColumn(cell, i % 4);
  448. }
  449. break;
  450. }
  451. case 9:
  452. {
  453. // 3行3列
  454. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  455. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  456. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  457. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  458. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  459. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  460. gridRender.ShowGridLines = true;
  461. for (int i = 0; i < 9; i++)
  462. {
  463. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  464. gridRender.Children.Add(cell);
  465. Grid.SetRow(cell, i / 3);
  466. Grid.SetColumn(cell, i % 3);
  467. }
  468. break;
  469. }
  470. case 12:
  471. {
  472. // 3行4列
  473. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  474. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  475. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  476. for (int i = 0; i < 4; i++)
  477. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  478. gridRender.ShowGridLines = true;
  479. for (int i = 0; i < 12; i++)
  480. {
  481. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  482. gridRender.Children.Add(cell);
  483. Grid.SetRow(cell, i / 4);
  484. Grid.SetColumn(cell, i % 4);
  485. }
  486. break;
  487. }
  488. case 16:
  489. {
  490. // 4行4列
  491. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  492. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  493. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  494. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  495. for (int i = 0; i < 4; i++)
  496. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  497. gridRender.ShowGridLines = true;
  498. for (int i = 0; i < 16; i++)
  499. {
  500. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  501. gridRender.Children.Add(cell);
  502. Grid.SetRow(cell, i / 4);
  503. Grid.SetColumn(cell, i % 4);
  504. }
  505. break;
  506. }
  507. case 20:
  508. {
  509. // 5行4列
  510. for (int r = 0; r < 5; r++)
  511. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  512. for (int c = 0; c < 4; c++)
  513. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  514. gridRender.ShowGridLines = true;
  515. for (int i = 0; i < 20; i++)
  516. {
  517. var cell = CreateCellGrid(obj[i].Id, obj[i].DisplayName, font);
  518. gridRender.Children.Add(cell);
  519. Grid.SetRow(cell, i / 4);
  520. Grid.SetColumn(cell, i % 4);
  521. }
  522. break;
  523. }
  524. default:
  525. {
  526. // 未覆盖的数量:先用简单的 1列多行兜底(避免空白)
  527. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  528. gridRender.ColumnDefinitions.Add(new ColumnDefinition());
  529. gridRender.ShowGridLines = false;
  530. var cell = CreateCellGrid(obj[0].Id, obj[0].DisplayName, font);
  531. gridRender.Children.Add(cell);
  532. Grid.SetRow(cell, 0);
  533. Grid.SetColumn(cell, 0);
  534. break;
  535. }
  536. }
  537. }
  538. /// <summary>
  539. /// 请求保存图像(在 WinForms 消息循环线程截图,然后派发到后台线程保存)
  540. /// 使用 SemaphoreSlim 控制并发,支持 CancellationToken 取消
  541. /// </summary>
  542. private void RequestSaveImage(ShowRender render, Cognex.VisionPro.CogRecordDisplay disp)
  543. {
  544. if (render == null) return;
  545. if (disp == null) return;
  546. if (!render.IsSaveImage) return;
  547. bool needRecordedBitmap =
  548. render.SaveImageModel == ProcedureSaveImageModel.Recorded ||
  549. render.SaveImageModel == ProcedureSaveImageModel.OriginalAndRecorded;
  550. var token = _saveImageCts.Token;
  551. disp.BeginInvoke(new Action(() =>
  552. {
  553. Bitmap clonedBitmap = null;
  554. try
  555. {
  556. if (token.IsCancellationRequested) return;
  557. if (needRecordedBitmap)
  558. {
  559. if (disp.IsDisposed || !disp.IsHandleCreated) return;
  560. Bitmap uiBitmap = (Bitmap)disp.CreateContentBitmap(
  561. Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  562. clonedBitmap = (Bitmap)uiBitmap.Clone();
  563. uiBitmap.Dispose();
  564. }
  565. var capturedBitmap = clonedBitmap;
  566. var capturedRender = render;
  567. Task.Run(async () =>
  568. {
  569. await _saveSemaphore.WaitAsync(token);
  570. try
  571. {
  572. if (token.IsCancellationRequested) return;
  573. if (capturedRender.IsDelaySaveImage)
  574. {
  575. // 延迟保存:存入列表,等 DelaySaveImageNotification 时统一写入
  576. ICogImage imageDeepCopy = null;
  577. try
  578. {
  579. imageDeepCopy = capturedRender.Image?
  580. .CopyBase(CogImageCopyModeConstants.CopyPixels);
  581. }
  582. catch (Exception ex)
  583. {
  584. LogHelper.WriteLogError("延迟保存深拷贝 ICogImage 失败", ex);
  585. }
  586. var delayItem = new Models.DelaySaveImage()
  587. {
  588. SaveImageModel = capturedRender.SaveImageModel,
  589. SaveImagePathModel = capturedRender.SaveImagePathModel,
  590. SavePath = capturedRender.SavePath,
  591. Image = imageDeepCopy,
  592. clonedBitmap = capturedBitmap != null
  593. ? (Bitmap)capturedBitmap.Clone() : null,
  594. Result = capturedRender.Result,
  595. IsCompress = capturedRender.IsCompress,
  596. ImageFileName = capturedRender.ImageFileName,
  597. Is3DModel = capturedRender.Is3DModel,
  598. };
  599. lock (delaySaveImages)
  600. {
  601. delaySaveImages.Add(delayItem);
  602. }
  603. }
  604. else
  605. {
  606. if (string.IsNullOrEmpty(_productService.CurrentProductCode))
  607. {
  608. _eventAggregator.GetEvent<TaskMessageNotification>()
  609. .Publish(new MessageStruct()
  610. {
  611. Message = "当前产品SN不存在,无法保存图片!",
  612. level = MessageLevel.Alarm
  613. });
  614. return;
  615. }
  616. LogHelper.WriteLogInfo("开始异步保存图像");
  617. await SaveImageAsync(
  618. capturedRender.SaveImageModel,
  619. capturedRender.SaveImagePathModel,
  620. capturedRender.SavePath,
  621. capturedRender.Image,
  622. capturedBitmap,
  623. capturedRender.Result,
  624. capturedRender.IsCompress,
  625. capturedRender.ImageFileName,
  626. capturedRender.Is3DModel,
  627. token
  628. );
  629. }
  630. }
  631. catch (OperationCanceledException) { }
  632. catch (Exception ex)
  633. {
  634. LogHelper.WriteLogError("后台保存图像任务出错!", ex);
  635. }
  636. finally
  637. {
  638. try { capturedBitmap?.Dispose(); } catch { }
  639. _saveSemaphore.Release();
  640. }
  641. }, token);
  642. }
  643. catch (Exception ex)
  644. {
  645. LogHelper.WriteLogError("RequestSaveImage(UI截图阶段) 出错!", ex);
  646. try { clonedBitmap?.Dispose(); } catch { }
  647. }
  648. }));
  649. }
  650. /// <summary>
  651. /// 异步保存图像(调用者已在后台线程,不再嵌套 Task.Run;通过 CancellationToken 支持取消)
  652. /// </summary>
  653. private async Task SaveImageAsync(
  654. ProcedureSaveImageModel saveImageModel,
  655. ProcedureSaveImagePathModel saveImagePathModel,
  656. string path, ICogImage image, Bitmap reimage,
  657. bool result, bool isCompress, string imageFileName,
  658. bool is3Dmodel, CancellationToken cancellationToken)
  659. {
  660. if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
  661. {
  662. _eventAggregator.GetEvent<TaskMessageNotification>()
  663. .Publish(new Models.MessageStruct() { Message = "保存图像路径为无效的路径!", level = MessageLevel.Alarm });
  664. return;
  665. }
  666. try
  667. {
  668. cancellationToken.ThrowIfCancellationRequested();
  669. DateTime now = DateTime.Now;
  670. //图片名
  671. string imgName = now.ToString("yyyy-MM-dd HH_mm_ss");
  672. if (!string.IsNullOrEmpty(imageFileName))
  673. {
  674. imgName = imageFileName;
  675. }
  676. if (saveImageModel == ProcedureSaveImageModel.Original)
  677. {
  678. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  679. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  680. {
  681. Originalpath = result
  682. ? $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
  683. : $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  684. }
  685. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  686. {
  687. if (result)
  688. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  689. else
  690. return;
  691. }
  692. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  693. {
  694. if (!result)
  695. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  696. else
  697. return;
  698. }
  699. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  700. {
  701. // 当前产品配方名(过滤非法字符)
  702. string formulaName = _productService.GetCurrentProduct().Name;
  703. foreach (char c in Path.GetInvalidFileNameChars())
  704. formulaName = formulaName.Replace(c, '_');
  705. // 产品SN(过滤非法字符)
  706. string productSN = _productService.CurrentProductCode;
  707. foreach (char c in Path.GetInvalidFileNameChars())
  708. productSN = productSN.Replace(c, '_');
  709. string resultStr = result ? "OK" : "NG";
  710. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  711. }
  712. cancellationToken.ThrowIfCancellationRequested();
  713. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  714. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  715. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  716. {
  717. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  718. _cogImageFileTool.Append(image);
  719. _cogImageFileTool.Close();
  720. }
  721. }
  722. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  723. {
  724. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  725. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  726. {
  727. Recordedpath = result
  728. ? $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
  729. : $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  730. }
  731. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  732. {
  733. if (result)
  734. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  735. else
  736. return;
  737. }
  738. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  739. {
  740. if (!result)
  741. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  742. else
  743. return;
  744. }
  745. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  746. {
  747. string formulaName = _productService.GetCurrentProduct().Name;
  748. foreach (char c in Path.GetInvalidFileNameChars())
  749. formulaName = formulaName.Replace(c, '_');
  750. string productSN = _productService.CurrentProductCode;
  751. foreach (char c in Path.GetInvalidFileNameChars())
  752. productSN = productSN.Replace(c, '_');
  753. string resultStr = result ? "OK" : "NG";
  754. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  755. }
  756. cancellationToken.ThrowIfCancellationRequested();
  757. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  758. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  759. if (isCompress)
  760. {
  761. ImageHelper.CompressImage(reimage, Recordedpath, 20);
  762. }
  763. else
  764. {
  765. reimage.Save(Recordedpath);
  766. }
  767. }
  768. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  769. {
  770. string Originalpath = "";
  771. if (is3Dmodel == true)
  772. {
  773. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.idb";
  774. }
  775. else
  776. {
  777. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  778. }
  779. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  780. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  781. {
  782. if (result)
  783. {
  784. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  785. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  786. }
  787. else
  788. {
  789. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  790. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  791. }
  792. }
  793. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  794. {
  795. if (result)
  796. {
  797. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  798. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  799. }
  800. else
  801. {
  802. return;
  803. }
  804. }
  805. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  806. {
  807. if (!result)
  808. {
  809. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  810. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  811. }
  812. else
  813. {
  814. return;
  815. }
  816. }
  817. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  818. {
  819. string formulaName = _productService.GetCurrentProduct().Name;
  820. foreach (char c in Path.GetInvalidFileNameChars())
  821. formulaName = formulaName.Replace(c, '_');
  822. string productSN = _productService.CurrentProductCode;
  823. if (productSN != null)
  824. {
  825. foreach (char c in Path.GetInvalidFileNameChars())
  826. productSN = productSN.Replace(c, '_');
  827. }
  828. string resultStr = result ? "OK" : "NG";
  829. if (is3Dmodel == true)
  830. {
  831. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.idb";
  832. }
  833. else
  834. {
  835. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  836. }
  837. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  838. }
  839. cancellationToken.ThrowIfCancellationRequested();
  840. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  841. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  842. using (CogImageFile _cogImageFileTool = new CogImageFile())
  843. {
  844. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  845. _cogImageFileTool.Append(image);
  846. _cogImageFileTool.Close();
  847. }
  848. cancellationToken.ThrowIfCancellationRequested();
  849. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  850. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  851. if (isCompress)
  852. {
  853. ImageHelper.CompressImage(reimage, Recordedpath, 20);
  854. }
  855. else
  856. {
  857. reimage.Save(Recordedpath);
  858. }
  859. }
  860. }
  861. catch (OperationCanceledException) { }
  862. catch (Exception ex)
  863. {
  864. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  865. }
  866. finally
  867. {
  868. try { reimage?.Dispose(); } catch { }
  869. }
  870. }
  871. /// <summary>
  872. /// 延迟保存图像处理:isSave=true 时批量保存所有待保存项;false 时丢弃并清理
  873. /// </summary>
  874. private async void UpdateDelaySaveImage(bool isSave)
  875. {
  876. if (!isSave)
  877. {
  878. lock (delaySaveImages)
  879. {
  880. foreach (var item in delaySaveImages)
  881. {
  882. try { item.clonedBitmap?.Dispose(); } catch { }
  883. try { item.Image = null; } catch { }
  884. }
  885. delaySaveImages.Clear();
  886. }
  887. return;
  888. }
  889. List<Models.DelaySaveImage> itemsToSave;
  890. lock (delaySaveImages)
  891. {
  892. itemsToSave = new List<Models.DelaySaveImage>(delaySaveImages);
  893. delaySaveImages.Clear();
  894. }
  895. var token = _saveImageCts.Token;
  896. foreach (var item in itemsToSave)
  897. {
  898. try
  899. {
  900. if (token.IsCancellationRequested) break;
  901. if (string.IsNullOrEmpty(_productService.CurrentProductCode))
  902. {
  903. _eventAggregator.GetEvent<TaskMessageNotification>()
  904. .Publish(new MessageStruct()
  905. {
  906. Message = "当前产品SN不存在,无法保存图片!",
  907. level = MessageLevel.Alarm
  908. });
  909. break;
  910. }
  911. LogHelper.WriteLogInfo("开始异步保存延迟图像");
  912. await SaveImageAsync(
  913. item.SaveImageModel,
  914. item.SaveImagePathModel,
  915. item.SavePath,
  916. item.Image,
  917. item.clonedBitmap,
  918. item.Result,
  919. item.IsCompress,
  920. item.ImageFileName,
  921. item.Is3DModel,
  922. token
  923. );
  924. }
  925. catch (OperationCanceledException) { break; }
  926. catch (Exception ex)
  927. {
  928. LogHelper.WriteLogError("延迟保存图像任务出错!", ex);
  929. }
  930. finally
  931. {
  932. try { item.clonedBitmap?.Dispose(); } catch { }
  933. try { item.Image = null; } catch { }
  934. }
  935. }
  936. }
  937. private void ShowVisionRender_Unloaded(object sender, RoutedEventArgs e)
  938. {
  939. try { _saveImageCts.Cancel(); _saveImageCts.Dispose(); } catch { }
  940. // 释放延迟保存列表中的 Bitmap 资源
  941. lock (delaySaveImages)
  942. {
  943. foreach (var item in delaySaveImages)
  944. {
  945. try { item.clonedBitmap?.Dispose(); } catch { }
  946. try { item.Image = null; } catch { }
  947. }
  948. delaySaveImages.Clear();
  949. }
  950. }
  951. private void ProductChanged(ProductModel product)
  952. {
  953. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  954. {
  955. var is3DEnabled = GetView3DUse();
  956. foreach (var item in vmRenders)
  957. {
  958. try
  959. {
  960. // 2D:永远清理
  961. var display2D = item.Value.Child as Cognex.VisionPro.CogRecordDisplay;
  962. if (display2D != null)
  963. {
  964. display2D.Record = null;
  965. display2D.Image = null;
  966. display2D.StaticGraphics.Clear();
  967. continue;
  968. }
  969. // 3D:仅在启用 3D 时清理
  970. if (!is3DEnabled)
  971. continue;
  972. var display3D = item.Value.Child as Cognex.VisionPro3D.Cog3DDisplayV2WF;
  973. if (display3D != null)
  974. {
  975. display3D.Clear();
  976. }
  977. }
  978. catch (System.Windows.Forms.AxHost.InvalidActiveXStateException)
  979. {
  980. // 控件句柄/ActiveX 未就绪时忽略
  981. }
  982. catch (Exception ex)
  983. {
  984. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  985. }
  986. }
  987. }));
  988. }
  989. private void OnDisplayDoubleClick(CogRecordDisplay disp)
  990. {
  991. if (disp == null)
  992. return;
  993. try
  994. {
  995. // 直接把当前 CogRecordDisplay 传给对话框 VM(VM 内部读取 Image/Record)
  996. var parameters = new Prism.Services.Dialogs.DialogParameters
  997. {
  998. { "Cog", disp }
  999. };
  1000. // Prism Dialog 必须在 WPF UI 线程调用
  1001. Dispatcher.BeginInvoke(new Action(() =>
  1002. {
  1003. try
  1004. {
  1005. _dialogService.ShowDialog("ImagePreviewWindow", parameters, r => { });
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. LogHelper.WriteLogError("打开 ImagePreviewWindow 失败", ex);
  1010. }
  1011. }));
  1012. }
  1013. catch (Exception ex)
  1014. {
  1015. LogHelper.WriteLogError("双击打开预览窗口失败", ex);
  1016. }
  1017. }
  1018. }
  1019. }