I am trying to get a window to open in plain C#.
I've created, for this, a window constructor (SGFWindow) extending the Window class from System.Windows :
namespace SGF
{
public partial class SGFWindow : Window
{
public SGFWindow()
{
this.Title = "SGF Window";
this.Width = 200;
this.Height = 200;
}
}
}
I've then created a WindowTest class to test it :
namespace SGF
{
public class WindowTest
{
public static void Main(string[] args)
{
SGFWindow window = new SGFWindow();
window.Show();
}
}
}
The problem is, I get a "The calling thread must be STA, because many UI components require this." error ; excepting that this is not a thread (or not one I've created?).
I searched about it but it was always about a thread and I can't find how to fix this error. I've also saw something about [STAThread] but it apparently wasn't appropriate to it.
Thanks in advance, Marceau.
There is a thread, actually, because threads are required to execute code. In fact, there will always be at least one: the operating system will create one for you to execute the
Mainmethod, and that one is referred to as the "main thread". WhenMainreturns, that thread exits.By default, that thread is created as MTA, but this is not appropriate for WinForms and WPF, hence why you get that error. The solution is to put the
STAThreadattribute over yourMainto change this:This attribute is only used to change the threading model of the main thread. For a thread you've created yourself, use
Thread.SetApartmentState.