給C#程序加殼(C# 調用嵌入資源的EXE文件方法)


本來想把一個EXE程序變成我的窗口的一部分,試了很久沒有成功,也不能說沒有收獲,這是一個對c#的EXE程序加殼的程序。

代碼復制如下:

1. 我們有一個test.exe的WinForm程序,這是我們要加殼的目標程序。
2. 新建一個WinForm工程,刪除Form1,然后新建一個類。如下。
3. 將test.exe 拷貝到該工程目錄,作為嵌入式資源using System;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;
using System.IO;
namespace test
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Stream stream = Assembly. GetExecutingAssembly_r(). GetManifestResourceStream_r("test.Code.exe");
            byte[] bs = new byte[stream.Length];
            stream.Read(bs, 0, (int)stream.Length);
            Assembly asm = Assembly.Load(bs);
            MethodInfo info = asm.EntryPoint;
            ParameterInfo[] parameters = info. GetParameters_r();
            if ((parameters != null) && (parameters.Length > 0))
                info.Invoke(null, (object[])args);
            else
                info.Invoke(null, null);
        }
    }
}

這是一個錯漏百出的程序,參見參考文獻4,以至於我弄了很久沒有沒有結果。

最后弄出來了,總結一下:

1.要加殼的一定是c#程序,我用其他類型程序試過,不可行。

2.必須是嵌入式資源,有關這個解釋可以參考文獻1和2.

3.我在執行“Stream stream = Assembly. GetExecutingAssembly_r(). GetManifestResourceStream_r("test.Code.exe");”的時候總是得到為null,在參考了文獻3以后可以正確獲取了值。

最后正確的代碼應該是這樣的:

using System;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;
using System.IO;

namespace MyNamespace
{
    public class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            String projectName = Assembly.GetExecutingAssembly().GetName().Name.ToString();
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(projectName + ".test.exe");
            byte[] bs = new byte[stream.Length];
            stream.Read(bs, 0, (int)stream.Length);
            Assembly asm = Assembly.Load(bs);

            MethodInfo info = asm.EntryPoint;
            ParameterInfo[] parameters = info.GetParameters();
            if ((parameters != null) && (parameters.Length > 0))
                info.Invoke(null, (object[])args);
            else
                info.Invoke(null, null);

        }
    }
}

 

 

 

參考文獻:

1.http://zch448.blog.163.com/blog/static/73706910201231902712864/

2.http://www.cnblogs.com/zhangjun1130/archive/2011/04/11/2012566.html

3.http://www.cnblogs.com/lonelyDog/archive/2012/02/16/2354407.html

4.http://www.cnblogs.com/huangcong/archive/2010/03/23/1693293.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM