I try to open an wpf window in my c# test application.
But when I open the window, it is immediately closed again.
Whats wrong in my code?
Main.cs (also available here):
namespace Project1
{
class TestClass
{
public static MainWindow _mainWindow = null;
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.SetApartmentState(ApartmentState.STA);
t.Start();
while (true)
{
System.Threading.Thread.Sleep(1000);
_mainWindow.ToString();
}
}
public static void ThreadProc()
{
TestClass2 testClass = new TestClass2();
testClass.Open();
}
}
class TestClass2
{
public void Open()
{
TestClass._mainWindow = new MainWindow();
TestClass._mainWindow.Show();
Console.WriteLine("=)");
}
}
}
MainWindow.xaml:
Your code is doing some strange things for which there is no apparent reason:
.ToString()on yourWindow, which additionally is owned by a different thread? (I ‘m not sure if this would cause your program to crash due to the ownership issue like most other operations would, but it’s probable).Furthermore, you do not create a message loop anywhere so even if the program worked it would be completely unresponsive to user input. After creating your
Window, in whatever thread you do it, you should call