I have a form name Form1.cs
and when I run it, it has an error: ThreadStateException was unhanded.
I am trying to open a file from a desired location, then latter on have it so the file will load automatically in a text box on screen. I have heard of this [STAThread]
but am confused on how to add it. When I try to use it in the main method it comes up as "not valid on this declaration type".
Form1.cs
:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = openFileDialog1.FileName;
MessageBox.Show(strfilename);
}
}
}
The Solution Explorer:
Game1.cs
is were it starts, I have a function witch calls on the form to pop up by pressing F1:
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (Keyboard.GetState().IsKeyDown(Keys.F1) && (!isForm1Open))
{
isForm1Open = true;
Form1 form1 = new Form1();
form1.FormClosed += new System.Windows.Forms.FormClosedEventHandler(
(s, e) => { isForm1Open = false; });
form1.ShowDialog();
}
base.Update(gameTime);
}
[STAThread]
is an attribute that marks your method as running in a single-threaded apartment. For WinForms programs you must put this attribute on the Program.cs'Main
method, like so:This is because WinForms interacts directly with COM components (the UI widgets are mostly still COM, and so is Windows' windowing and file system).