当前位置:   article > 正文

C# WPF项目实战(经典)

wpf经典编程实例

目的:输出两台摄像头图像和两路设备图像,每一路设备截图6张

主要知识:

1. 通过SDK调取摄像头图像,并对图像进行剪裁;

2. WPF中定时器DispatcherTimer用法;

3. WPF中跨线程访问控件方法

  Dispatcher.Invoke((Action)delegate {});

区别于winform中

this.Invoke((Action)delegate {});

4.xml操作:

  1. XmlDocument xmlDoc = new XmlDocument();
  2. xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\config.xml");
  3. XmlNode settingNode = xmlDoc.DocumentElement;
  4. XmlElement e = settingNode.SelectSingleNode("DeviceType") as XmlElement;
  5. if (e == null)
  6. {
  7. deviceType = "tps2000";
  8. }
  9. else
  10. {
  11. deviceType = e.InnerText;
  12. }

5. 带多个参数的委托

  1. DP1 = new DataProcess(DeviceIP1, LocalPort1,0);
  2. DP1.ShowEvent1 = DrawControls1;
  3. DP1.Start();//启动线程

6.多线程操作

  1. Thread t1 = new Thread(new ThreadStart(DataRevThread)); //开启DataRevThread
  2. t1.Name = "DataRevThread"; //线程名字
  3. t1.Start();
  4. t1.IsBackground = true; //后台运行

7. UDP接收,解码;

8. emgucv使用;

9. 工厂模式:

  1. ModelFactory MF = new ModelFactory();
  2.    DM = MF.CreateDataModelFactory_v1(sNeed.ToString());

10.信号量线程间同步

  1. Semaphore TaskSemaphoreData = new Semaphore(0, 2560); //数据缓存队列缓存区
  2. TaskSemaphoreRev.WaitOne(); //等待接收队列

11.Bitmap转换为ImageSource

  1. [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  2. public static extern bool DeleteObject(IntPtr hObject);
  3. public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
  4. {
  5. IntPtr hBitmap = bitmap.GetHbitmap();
  6. ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
  7. hBitmap,
  8. IntPtr.Zero,
  9. Int32Rect.Empty,
  10. BitmapSizeOptions.FromEmptyOptions());
  11. if (!DeleteObject(hBitmap))
  12. {
  13. throw new System.ComponentModel.Win32Exception();
  14. }
  15. return wpfBitmap;
  16. }

12.Queue和list的操作

包括但是不限于以上内容

代码如下:

MainWindow.xaml:

  1. <Fluent:RibbonWindow x:Class="thzSoftware.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:Fluent="urn:fluent-ribbon"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  7. xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
  8. xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
  9. xmlns:local="clr-namespace:thzSoftware"
  10. mc:Ignorable="d"
  11. Title="MainWindow" Height="600" Width="800" WindowStartupLocation="CenterScreen" WindowState="Maximized" Background="LightBlue" Closing="RibbonWindow_Closing">
  12. <Grid ShowGridLines="True" >
  13. <Grid.RowDefinitions>
  14. <RowDefinition Height="*"></RowDefinition>
  15. <RowDefinition Height="10*"></RowDefinition>
  16. <RowDefinition Height="*"></RowDefinition>
  17. <RowDefinition Height="10*"></RowDefinition>
  18. </Grid.RowDefinitions>
  19. <Grid.ColumnDefinitions>
  20. <ColumnDefinition Width="*"/>
  21. <ColumnDefinition Width="*"/>
  22. <ColumnDefinition Width="*"/>
  23. <ColumnDefinition Width="*"/>
  24. <ColumnDefinition Width="*"/>
  25. <ColumnDefinition Width="*"/>
  26. <ColumnDefinition Width="*"/>
  27. <ColumnDefinition Width="*"/>
  28. </Grid.ColumnDefinitions>
  29. <Label Grid.Row="0" Grid.Column="0" Name="labelCamera1Status" Content="摄像头连接状态" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="LightCyan"/>
  30. <wfi:WindowsFormsHost Grid.Row="1" Grid.Column="0" Background="LightGray">
  31. <wf:PictureBox x:Name="Cam1" />
  32. </wfi:WindowsFormsHost>
  33. <Label Grid.Row="2" Grid.Column="0" Name="labelCamera2Status" Content="摄像头连接状态" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="LightCyan"/>
  34. <wfi:WindowsFormsHost Grid.Row="3" Grid.Column="0" Background="LightGray">
  35. <wf:PictureBox x:Name="Cam2" />
  36. </wfi:WindowsFormsHost>
  37. <Label Grid.Row="0" Grid.Column="1" Name="labelThz1Status" Content="太赫兹连接状态" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="LightCyan"/>
  38. <Image Grid.Row="1" Grid.Column="1" Name="Thz1" />
  39. <Label Grid.Row="2" Grid.Column="1" Name="labelThz2Status" Content="太赫兹连接状态" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="LightCyan"/>
  40. <Image Grid.Row="3" Grid.Column="1" Name="Thz2" />
  41. <Image Grid.Row="1" Grid.Column="2" Name="Thz1Image1" />
  42. <Image Grid.Row="1" Grid.Column="3" Name="Thz1Image2" />
  43. <Image Grid.Row="1" Grid.Column="4" Name="Thz1Image3" />
  44. <Image Grid.Row="1" Grid.Column="5" Name="Thz1Image4" />
  45. <Image Grid.Row="1" Grid.Column="6" Name="Thz1Image5" />
  46. <Image Grid.Row="1" Grid.Column="7" Name="Thz1Image6" />
  47. <Image Grid.Row="3" Grid.Column="2" Name="Thz2Image1" />
  48. <Image Grid.Row="3" Grid.Column="3" Name="Thz2Image2" />
  49. <Image Grid.Row="3" Grid.Column="4" Name="Thz2Image3" />
  50. <Image Grid.Row="3" Grid.Column="5" Name="Thz2Image4" />
  51. <Image Grid.Row="3" Grid.Column="6" Name="Thz2Image5" />
  52. <Image Grid.Row="3" Grid.Column="7" Name="Thz2Image6" />
  53. </Grid>
  54. </Fluent:RibbonWindow>

MainWindow.xaml.cs

  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Windows.Forms;
  4. using System.Windows.Threading;
  5. using MessageBox = System.Windows.MessageBox;
  6. using thzModel;
  7. using System.Drawing;
  8. using System.Windows;
  9. using System.Windows.Media.Imaging;
  10. using System.Windows.Media;
  11. using System.Xml;
  12. using Emgu.CV;
  13. using Emgu.CV.Structure;
  14. using System.Threading;
  15. using System.Drawing.Imaging;
  16. using System.Collections.Generic;
  17. using System.Windows.Controls;
  18. using Image = System.Windows.Controls.Image;
  19. namespace thzSoftware
  20. {
  21. /// <summary>
  22. /// MainWindow.xaml 的交互逻辑
  23. /// </summary>
  24. public partial class MainWindow : Fluent.RibbonWindow
  25. {
  26. DispatcherTimer Cam1ReconnectTimer, Cam2ReconnectTimer;
  27. public MainWindow()
  28. {
  29. try
  30. {
  31. InitializeComponent();
  32. Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  33. init();
  34. }
  35. catch (Exception ex)
  36. {
  37. MessageBox.Show(ex.StackTrace + ex.Message);
  38. LogWrite.logWrite(ex.Message, ex.StackTrace);
  39. }
  40. }
  41. public IntPtr PictureDev1Cam { get { return Cam1.Handle; } }
  42. public IntPtr PictureDev2Cam { get { return Cam2.Handle; } }
  43. IntPtr Cam1Handle = IntPtr.Zero;
  44. IntPtr Cam2Handle = IntPtr.Zero;
  45. Camera Camera1 = new Camera();
  46. Camera Camera2 = new Camera();
  47. static private string Cam1IP = "192.168.1.64";
  48. static private string Cam2IP = "192.168.1.61";
  49. DataProcess DP1 = null, DP2 = null;
  50. object ThreadLockBitmap = new object();
  51. List<ImageSource> thzBitmapList1 = new List<ImageSource>();
  52. List<ImageSource> thzBitmapList2 = new List<ImageSource>();
  53. int snapFlag1 = 0, snapFlag2 = 0;
  54. static public String DeviceType
  55. {
  56. get
  57. {
  58. return deviceType;
  59. }
  60. set
  61. {
  62. deviceType = value;
  63. }
  64. }
  65. static private string deviceType = "tps2000";
  66. void init()
  67. {
  68. ReadConfigXML();
  69. Cam1Handle = PictureDev1Cam;
  70. Cam2Handle = PictureDev2Cam;
  71. Cam1.SizeMode = PictureBoxSizeMode.Zoom;
  72. Cam2.SizeMode = PictureBoxSizeMode.Zoom;
  73. Cam1ReconnectTimer = new DispatcherTimer();
  74. Cam1ReconnectTimer.Interval = new TimeSpan(0, 0, 3);//定时间隔3秒
  75. Cam1ReconnectTimer.Tick += Cam1ReconnectTimer_Tick;//加载事件,敲tab键事件框架可以自己出来
  76. Cam1ReconnectTimer.Start();
  77. Cam2ReconnectTimer = new DispatcherTimer();
  78. Cam2ReconnectTimer.Interval = new TimeSpan(0, 0, 3);//定时间隔3秒
  79. Cam2ReconnectTimer.Tick += Cam2ReconnectTimer_Tick;//加载事件,敲tab键事件框架可以自己出来
  80. Cam2ReconnectTimer.Start();
  81. thzModel.Command.CommandUp(8);//发送启动指令
  82. string DeviceIP1 = "192.168.1.110";
  83. int LocalPort1 = 8007;
  84. DP1 = new DataProcess(DeviceIP1, LocalPort1,0);
  85. DP1.ShowEvent1 = DrawControls1;
  86. DP1.Start();//启动线程
  87. string DeviceIP2 = "192.168.1.120";
  88. int LocalPort2 = 8009;
  89. DP2 = new DataProcess(DeviceIP2, LocalPort2, 1);
  90. DP2.ShowEvent2 = DrawControls2;
  91. DP2.Start();//启动线程
  92. }
  93. private void DrawControls1(Bitmap image, bool isWarning, bool isBlack)
  94. {
  95. Image[] iSource = { Thz1Image1, Thz1Image2, Thz1Image3, Thz1Image4, Thz1Image5, Thz1Image6 };
  96. Dispatcher.Invoke((Action)delegate
  97. {
  98. labelThz1Status.Content = "太赫兹连接成功";
  99. Thz1.Source = ChangeBitmapToImageSource(image);
  100. snapFlag1++;
  101. thzBitmapList1.Add(Thz1.Source);
  102. if (thzBitmapList1.Count > 6)
  103. thzBitmapList1.RemoveAt(0);
  104. if (snapFlag1 > 8)
  105. {
  106. snapFlag1 = 0;
  107. for (int i = 0; i < thzBitmapList1.Count; i++)
  108. {
  109. iSource[i].Source = thzBitmapList1[i];
  110. }
  111. }
  112. });
  113. }
  114. [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  115. public static extern bool DeleteObject(IntPtr hObject);
  116. public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
  117. {
  118. IntPtr hBitmap = bitmap.GetHbitmap();
  119. ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
  120. hBitmap,
  121. IntPtr.Zero,
  122. Int32Rect.Empty,
  123. BitmapSizeOptions.FromEmptyOptions());
  124. if (!DeleteObject(hBitmap))
  125. {
  126. throw new System.ComponentModel.Win32Exception();
  127. }
  128. return wpfBitmap;
  129. }
  130. private void DrawControls2(Bitmap image, bool isWarning, bool isBlack)
  131. {
  132. Image[] iSource = { Thz2Image1, Thz2Image2, Thz2Image3, Thz2Image4, Thz2Image5, Thz2Image6 };
  133. Dispatcher.Invoke((Action)delegate
  134. {
  135. labelThz2Status.Content = "太赫兹连接成功";
  136. Thz2.Source = ChangeBitmapToImageSource(image);
  137. snapFlag2++;
  138. thzBitmapList2.Add(Thz2.Source);
  139. if (thzBitmapList2.Count > 6)
  140. thzBitmapList2.RemoveAt(0);
  141. if (snapFlag2 > 8)
  142. {
  143. snapFlag2 = 0;
  144. for (int i = 0; i < thzBitmapList2.Count; i++)
  145. {
  146. iSource[i].Source = thzBitmapList2[i];
  147. }
  148. }
  149. });
  150. }
  151. private void ReadConfigXML()
  152. {
  153. try
  154. {
  155. XmlDocument xmlDoc = new XmlDocument();
  156. xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\config.xml");
  157. XmlNode settingNode = xmlDoc.DocumentElement;
  158. XmlElement e = settingNode.SelectSingleNode("DeviceType") as XmlElement;
  159. if (e == null)
  160. {
  161. deviceType = "tps2000";
  162. }
  163. else
  164. {
  165. deviceType = e.InnerText;
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. LogWrite.logWrite(ex.Message, ex.StackTrace);
  171. }
  172. }
  173. private void ConnectCamera(int whitch)
  174. {
  175. try
  176. {
  177. string userName = "admin";
  178. string password = "a123456.";
  179. int PortCamera = 8000;
  180. if (whitch == 1)
  181. {
  182. labelCamera1Status.Content = "摄像头连接中...";
  183. Task.Run(() =>
  184. {
  185. if (!Camera1.ConnectCamera(Cam1IP, PortCamera, userName, password))
  186. {
  187. Dispatcher.Invoke((Action)delegate { labelCamera1Status.Content = "摄像头连接失败"; });
  188. }
  189. else
  190. {
  191. Dispatcher.Invoke((Action)delegate { labelCamera1Status.Content = "摄像头连接成功"; });
  192. Camera1.Preview(Cam1Handle);
  193. Camera1.AdjustMirrorPara(1);
  194. Cam1ReconnectTimer.Stop();
  195. }
  196. });
  197. }
  198. else
  199. {
  200. labelCamera2Status.Content = "摄像头连接中...";
  201. Task.Run(() =>
  202. {
  203. if (!Camera2.ConnectCamera(Cam2IP, PortCamera, userName, password))
  204. {
  205. Dispatcher.Invoke((Action)delegate { labelCamera2Status.Content = "摄像头连接失败"; });
  206. }
  207. else
  208. {
  209. Dispatcher.Invoke((Action)delegate { labelCamera2Status.Content = "摄像头连接成功"; });
  210. Camera2.Preview(Cam2Handle);
  211. Camera2.AdjustMirrorPara(1);
  212. Cam2ReconnectTimer.Stop();
  213. }
  214. });
  215. }
  216. }
  217. catch (Exception ex)
  218. {
  219. MessageBox.Show(ex.StackTrace + ex.Message);
  220. LogWrite.logWrite(ex.Message, ex.StackTrace);
  221. }
  222. }
  223. private void Cam1ReconnectTimer_Tick(object sender, EventArgs e)
  224. {
  225. ConnectCamera(1);
  226. }
  227. private void RibbonWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  228. {
  229. thzModel.Command.CommandUp(0);//发送停止指令
  230. //Application.Exit();
  231. }
  232. private void Cam2ReconnectTimer_Tick(object sender, EventArgs e)
  233. {
  234. ConnectCamera(2);
  235. }
  236. }
  237. }

其余部分代码太长,不贴了,需要的话自己下载:百度网盘

链接:https://pan.baidu.com/s/1k2F0C-0gXX-tK_32m_ksOA

提取码:abs5

欢迎关注公众号: dotnet编程大全

技术群: 需要进技术群的添加小编微信mm1552923,备注:加群;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/169857
推荐阅读
相关标签
  

闽ICP备14008679号