gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:22 25 4
gpt4 key购买 nike

我有一个名为 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);
}
}
}

解决方案浏览器:

enter image description here

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 的窗口和文件系统也是如此)。

关于c# - 在表单中打开文件,未处理 ThreadStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com