因工作需要使用wpf做界面,而有个开发包依赖picturebox控件,上网研究了一下,总算弄通了。

首先在项目中添加引用System.Windows.Forms与WindowsFormsIntegration

 //在wpf主界面添加
xmlns:wfh="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wfc="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
 //添加winform控件
<Grid>
<WindowsFormsHost x:Name="form1" HorizontalAlignment="Left" Height="" Margin="10,65,0,0" VerticalAlignment="Top" Width="">
<wfc:FlowLayoutPanel x:Name="flowLayoutPanel1"> </wfc:FlowLayoutPanel>
</WindowsFormsHost>
</Grid>

获取句柄

             IntPtr flpHandle = flowLayoutPanel1.Handle;//仅限主界面代码段

动态创建picturebox放到flowLayoutPanel中

 PictureBox pb = new PictureBox
{
  Width = ,
  Height = ,
  Bounds = new System.Drawing.Rectangle(, , , ),
  Name = "PictureBox" + Convert.ToString(index)
}; PictureBox temp = pb;
Control flp = Control.FromHandle(flpHandle);
//考虑动态创建可能存在跨线程访问,添加判断
if (flp.InvokeRequired)
{
  flp.Invoke(new Action(
  () => { flp.Controls.Add(temp); picHandle = temp.Handle; }
  ));
}
else
{
20   flp.Controls.Add(pb);
}

注意在非主界面程序段,不要调用界面元素,不然会报错InvalidaOperationException

05-08 15:36