0
我有WPF用戶控件需要在Windows窗體中託管MTAThread。解決方案應該與STAThread和MTAThread一起工作。在技術上,沒有選擇在生產環境中更改公寓狀態。ElementHost無法在MTAThread中工作
的Program.cs
[MTAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(() =>{
host = new ElementHost();
host.Dock = DockStyle.Fill;
uc = new UserControl1();
host.Child = uc;
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
MessageBox.Show(this.Controls.Count.ToString());
//if (this.InvokeRequired)
//{
// this.Invoke((Action)(() => { this.Controls.Add(host); }));
//}
//else
{
this.Controls.Add(host);
}
MessageBox.Show(this.Controls.Count.ToString());
}
在這種情況下,現在主機添加到控制,有增加數量,並沒有扔在MTAThread任何異常。但WPF用戶控件不是呈現。然而,在STAThread中,它拋出一個異常「調用線程無法訪問此對象....」
Anyhelp在這將不勝感激。
感謝您的快速響應。但是,更改爲STAThread可能無法實現,因爲此COM組件被主機系統稱爲「代理進程」。然而,我編輯我的代碼,現在elementhost被添加到窗體控件,但它不是呈現... – Saqwes