在表单中打开文件,ThreadStateException了未处理(Opening files in

2019-10-19 03:17发布

我有一个表格名称Form1.cs ,当我运行它,它有一个错误:ThreadStateException被unhanded。

我试图从希望的位置打开一个文件,那么后者就拥有它,因此文件将在屏幕上的一个文本框会自动加载。 我听说过这个[STAThread]但是很困惑如何添加它。 当我尝试在主要的方法来使用它,它出来作为“无效在此声明类型”。

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

该解决方案管理器:

Game1.cs是被它开始,我有一个函数调用女巫在表格上按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);
    }

Answer 1:

[STAThread]是标记的方法,在运行中的一个属性单线程单元 。 对于的WinForms程序你必须把这个属性上的Program.cs' Main方法,就像这样:

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

这是因为的WinForms直接与COM组件进行交互(UI部件大多还是COM,所以是Windows的窗口和文件系统)。



文章来源: Opening files in a form, ThreadStateException was unhandled