因工作需要使用wpf做界面,而有个开发包依赖picturebox控件,上网研究了一下,总算弄通了。
首先在项目中添加引用System.Windows.Forms与WindowsFormsIntegration
1 //在wpf主界面添加 2 xmlns:wfh="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" 3 xmlns:wfc="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
1 //添加winform控件 2 <Grid> 3 <WindowsFormsHost x:Name="form1" HorizontalAlignment="Left" Height="500" Margin="10,65,0,0" VerticalAlignment="Top" Width="750"> 4 <wfc:FlowLayoutPanel x:Name="flowLayoutPanel1"> 5 6 </wfc:FlowLayoutPanel> 7 </WindowsFormsHost> 8 </Grid>
获取句柄
1 IntPtr flpHandle = flowLayoutPanel1.Handle;//仅限主界面代码段
动态创建picturebox放到flowLayoutPanel中
1 PictureBox pb = new PictureBox 2 { 3 Width = 500, 4 Height = 400, 5 Bounds = new System.Drawing.Rectangle(0, 0, 500, 400), 6 Name = "PictureBox" + Convert.ToString(index) 7 }; 8 9 PictureBox temp = pb; 10 Control flp = Control.FromHandle(flpHandle); 11 //考虑动态创建可能存在跨线程访问,添加判断 12 if (flp.InvokeRequired) 13 { 14 flp.Invoke(new Action( 15 () => { flp.Controls.Add(temp); picHandle = temp.Handle; } 16 )); 17 } 18 else 19 { 20 flp.Controls.Add(pb); 21 }
注意在非主界面程序段,不要调用界面元素,不然会报错InvalidaOperationException