Opening files in a form, ThreadStateException was

2019-08-01 09:06发布

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:

enter image description here

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);
    }

1条回答
欢心
2楼-- · 2019-08-01 09:27

[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:

[STAThread]
static void Main()
{
    Form1 f = new Form1();
    Application.Run(f);
}

This is because WinForms interacts directly with COM components (the UI widgets are mostly still COM, and so is Windows' windowing and file system).

查看更多
登录 后发表回答