我有两个WinForms NET应用程序“Test.exe”,资源“WindowsFormsApplication1.exe”。资源被标记为“嵌入式”。程序资源 - 空白项目Winforms(只有表单和没有处理程序的按钮)。使用“Test.exe”中的常用代码:
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
RunInternalExe("WindowsFormsApplication1.exe");
}
private static void RunInternalExe(string exeName)
{
//Get the current assembly
Assembly assembly = Assembly.GetExecutingAssembly();
//Get the assembly's root name
string rootName = assembly.GetName().Name;
//Get the resource stream
Stream resourceStream = assembly.GetManifestResourceStream(rootName + "." + exeName);
//Verify the internal exe exists
if (resourceStream == null)
return;
//Read the raw bytes of the resource
byte[] resourcesBuffer = new byte[resourceStream.Length];
resourceStream.Read(resourcesBuffer, 0, resourcesBuffer.Length);
resourceStream.Close();
//Load the bytes as an assembly
Assembly exeAssembly = Assembly.Load(resourcesBuffer);
//Execute the assembly
exeAssembly.EntryPoint.Invoke(null, null); //no parameters
}
当尝试从资源运行EXE时出现错误: 行上的“TargetInvocationException”:
exeAssembly.EntryPoint.Invoke(null, null);
答案 0 :(得分:0)
我找到了解决方案。资源程序中的表单是在同一个线程中创建的。在这种情况下,我需要使用这样的代码:
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Thread t = new Thread(new ParameterizedThreadStart(RunInternalExe));
t.Start("RunCodeFromDll.exe");
//RunInternalExe("RunCodeFromDll.exe");
}
static void RunInternalExe(object tempName)
{
string exeName = tempName.ToString();
//Get the current assembly
Assembly assembly = Assembly.GetExecutingAssembly();
//Get the assembly's root name
string rootName = assembly.GetName().Name;
//Get the resource stream
Stream resourceStream = assembly.GetManifestResourceStream(rootName + "." + exeName);
//Verify the internal exe exists
if (resourceStream == null)
return;
//Read the raw bytes of the resource
byte[] resourcesBuffer = new byte[resourceStream.Length];
resourceStream.Read(resourcesBuffer, 0, resourcesBuffer.Length);
resourceStream.Close();
//Load the bytes as an assembly
Assembly exeAssembly = Assembly.Load(resourcesBuffer);
//Execute the assembly
exeAssembly.EntryPoint.Invoke(null, null); //.EntryPoint.Invoke(null, null); //no parameters
}
我应该更加小心。 )))