Skip to main content
 首页 » 编程设计

c#之在表单中打开文件,未处理 ThreadStateException

2024年02月13日34EasonJim

我有一个名为 Form1.cs 的表单,当我运行它时,它出现错误:ThreadStateException was unhanded。

我正在尝试从所需位置打开一个文件,然后打开它,以便文件将自动加载到屏幕上的文本框中。我听说过这个 [STAThread] 但不知道如何添加它。当我尝试在 main 方法中使用它时,它显示为“在此声明类型上无效”。

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

请您参考如下方法:

[STAThread] 是一个将您的方法标记为在 single-threaded apartment 中运行的属性.对于 WinForms 程序,您必须将此属性放在 Program.cs 的 Main 方法中,如下所示:

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

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