C # SetCompatibleTextRenderingDefault must be called before the first

I tried to find this exception, but could not find a solution on my case

I am using the code below to call a .NET application:

        Assembly assem = Assembly.Load(Data);
        MethodInfo method = assem.EntryPoint;           
        var o = Activator.CreateInstance(method.DeclaringType);            
        method.Invoke(o, null);

The application that will be called has the form in the EntryPoint application:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false); //Exception
        Application.Run(new Form1());
    }

SetCompatibleTextRenderingDefaultmust be called before the first IWin32Windowobject is created in the application .

EDIT:

        Assembly a = Assembly.Load(Data);
        MethodInfo method = a.GetType().GetMethod("Start");
        var o = Activator.CreateInstance(method.DeclaringType);            
        method.Invoke(o, null);
+4
source share
1 answer

You should create a new method that skips initialization.

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false); //Exception
    Run();
}

public static void Run()
{
    Application.Run(new Form1());
}

And look with reflection for the Run method. But Application.Run blocks the current thread. If you do not want to start a new message pump, you should try to find the reflection class of the form.


Update:

class Program
{
    static void Main(string[] args)
    {
        var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        var filename = Path.Combine(path, "WindowsFormsApplication1.exe");
        var assembly = Assembly.LoadFile(filename);
        var programType = assembly.GetTypes().FirstOrDefault(c => c.Name == "Program"); // <-- if you don't know the full namespace and when it is unique.
        var method = programType.GetMethod("Start", BindingFlags.Public | BindingFlags.Static);
        method.Invoke(null, new object[] { });
    }
}

And boot assembly:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Start();
    }


    public static void Start()   // <-- must be marked public!
    {
        MessageBox.Show("Start");
        Application.Run(new Form1());
    }
}

It works here!

+5
source

Source: https://habr.com/ru/post/1660199/


All Articles