I have a simple WPF form, built as a dll file.
I have a winforms application.
In my MainForm.cs
constructor, I load Form2.cs
(which contains the ElementHost that calls the dll) to PanelTest
in MainForm.cs
When I build, i get this:
The calling Thread must be STA, because many UI components require this.
in the:
private void InitializeComponent()
{
this.elementHost3d = new System.Windows.Forms.Integration.ElementHost();
}
of my Form2.Designer.cs
Relevant code is:
Program.cs
public Program()
{
_formLauncher = new MainForm();
// Launch main UI as unique thread.
ThreadStart ts = new ThreadStart(InitUILauncher);
Thread tInitUILauncher = new Thread(ts);
tInitUILauncher.Start();
}
[STAThread]
protected void InitUILauncher()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(_formLauncher);
}
static void Main()
{
Program p = new Program();
}
MainForm.cs
public MainForm()
{
InitializeComponent();
InitPanels();
}
private void InitPanels()
{
PanelTest.Controls.Clear();
var Form2Var= new Form2();
PanelTest.Controls.Add(Form2Var);
}
}
Form2.cs
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate {
WPFUserControl.UserControl1 control = new WPFUserControl.UserControl1();
elementHost3d.Child = control;
});
}
I added the delagate code from here:
The calling thread must be STA, because many UI components require this
But I see the same issue. Reading around, I think I need to add an [STAThread]
somewhere, is this right? Where should it be?
Thank you.