在c#中按下按钮时获得异常

本文关键字:异常 按钮 | 更新日期: 2023-09-27 18:14:42

我用c#制作了一个按钮,用于从windows浏览文件和文件夹。我的示例代码如下所示。问题是:当我单击浏览按钮时,我在以下代码的注释中标记的行中出现了以下异常:

An unhandled exception of type 'System.Threading.ThreadStateException'   occurred in System.Windows.Forms.dll
我的示例代码:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
public class Form1 : Form
{
    public Form1()
    {
        Size = new Size(400, 380);
        Button browse = new Button();
        browse.Parent = this;
        browse.Text = "Browse";
        browse.Location = new Point(220, 52);
        browse.Size = new Size(6 * Font.Height, 2 * Font.Height);
        browse.Click += new EventHandler(ButtonbrowseOnClick);
    }
    public void ButtonbrowseOnClick(object sender, EventArgs e)
    {
         int size = -1;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();  
        DialogResult result = openFileDialog1.ShowDialog();  //getting exception in this line
        if (result == DialogResult.OK) 
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                size = text.Length;
            }
            catch (IOException)
            {
            }
        }
        Console.WriteLine(size); 
        Console.WriteLine(result);   
    }
    public static void Main()
    {
        Application.Run(new Form1());
    }
}

代码有什么问题吗?

在c#中按下按钮时获得异常

Main方法的顶部使用[STAThread]属性,应该可以解决问题。

[STAThread]          //   <--------Add this
public static void Main()
{
    Application.Run(new Form1());
}