C#未处理的异常'必须在创建第一个IWin32Window对象之前调用SetCompatibleTextRenderingDefault'

时间:2018-07-08 16:36:25

标签: c#

我试图用C#编写一个小的图像处理脚本,并且这样做是要打开一个图像文件,但是即使我解决了所有错误,当我尝试运行该脚本时,它也会给我一个“未处理的异常” 。我尝试将Application.Run(form1)移至单独的框,因为我认为它可能会尝试与“ form1”同时初始化SetCompatibleTextRenderingDefault,但这并没有改变问题

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{

static class Program
    {

    /// <summary>
    /// The main entry point for the application.
    /// </summary>

    [STAThread]
    static void Main()
    {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Start(); 

    }
    public static Form1 form1 = new Form1();

    public static void Start()   // <-- must be marked public!
    {
        Application.Run(form1);
    }
}
}

和form1的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openfile = new OpenFileDialog();
        openfile.Filter = "Image Files 
    (*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;*.bmp";
        if (openfile.ShowDialog() == DialogResult.OK)


        {
            Bitmap bit = new Bitmap(openfile.FileName);
            imgbefore.Image = bit;
        }

    }

    private void imgbefore_Click(object sender, EventArgs e)
    {

        }
}
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

public static Form1 form1 = new Form1();

此字段初始化程序在其包含的类中的所有代码(包括Main())之前运行。

您只能在调用new Form1()(后来在SetCompatibleTextRenderingDefault或单独的函数中)之后创建Main()

相关问题