以未打开的形式打开文件ThreadStateException [英] Opening files in a form, ThreadStateException was unhandled

查看:85
本文介绍了以未打开的形式打开文件ThreadStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单名称Form1.cs,运行它时出现错误:ThreadStateException未使用.

I have a form name Form1.cs and when I run it, it has an error: ThreadStateException was unhanded.

我试图从所需位置打开文件,然后打开文件,以便该文件将自动加载到屏幕上的文本框中.我听说过[STAThread],但是对如何添加它感到困惑.当我尝试在主要方法中使用它时,它显示为在此声明类型上无效".

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

解决方案资源管理器:

Game1.cs是开始的时候,我有一个函数,通过按F1在窗体上调用女巫:

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]是一个属性,用于将您的方法标记为在

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

这是因为WinForms直接与COM组件进行交互(UI小部件大多仍是COM,Windows的窗口和文件系统也是如此).

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

这篇关于以未打开的形式打开文件ThreadStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆