2016-11-08 41 views
3

我试图寻找这个异常之前被调用,但使用下面的代码来调用.NET应用程序我找不到我的情况下C#SetCompatibleTextRenderingDefault必须在第一

我'的任何解决方案:

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

将被调用的应用程序有一个表,并在应用程序的入口点:

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

SetCompatibleTextRenderingDefault必须在第一之前调用对象在应用程序中创建。

编辑:

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

你不能那样做。你可以尝试手动创建它的形式。 – SLaks

+0

我没有明白吗?你能解释一下吗? – Huster

回答

5

您应该创建跳过初始化的新方法。

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

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

然后用反射法来查看Run方法。但是Application.Run会阻止当前线程。如果你不想开始一个新的消息泵,你应该尝试用反射来查找Form类。


更新:

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[] { }); 
    } 
} 

而且载荷组件:

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

这个作品在这里!

+0

然后用Run方法的反射来看看? – Huster

+0

那就对了。问题在于,应用程序开始时只能称为视觉样式等。如果加载程序集(也适用于exefile程序集),它们将加载到同一个appdomain中。 –

+0

所以我基本上需要跳过EntryPoint Main()并直接创建运行方法的瞬间? – Huster

相关问题