Loading/Injecting .Net Assembly into existing .net process?

前端 未结 1 1881
名媛妹妹
名媛妹妹 2021-02-06 07:40

In my situation i want to load a custom .net assembly into a running .net process\'s domain, for example Windows Explorer, What i have tried already is just injecti

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 08:09

    As another option you can use existing library - ManagedInjector - https://github.com/cplotts/snoopwpf/tree/master/ManagedInjector . There is a tool snoopwpf that can show details of any WPF process, and it uses process injection for that. I used it some time ago and it worked well.

    You need to build it, add to your project as reference and call like this:

    Injector.Launch(someProcess.MainWindowHandle, 
                      typeof(Loader).Assembly.Location, 
                      typeof(Loader).FullName, 
                      "Inject");
    

    Loader is name of type that will be loaded into process and Inject is a static method that will be executed. In my case i had:

    public class Loader
    {
    
        public static void Inject()
        {
              // i did CBT Hook on main window here 
              // and also displayed sample message box for debugging purposes
              MessageBox.Show("Hello from another process");
        }
    }
    

    That ManagedInjector is written in Managed C++ code. Basically it hooks own unmanaged C++ method as MessageHookProc and it will start specified assembly after injection and run specified method. It should work fine for both managed and unmanaged programs. In my case i used it for unmanaged program.

    UPDATE

    I tested it locally and it successfully injects my message box into explorer process under Windows 8.1 x64. I compiled ManagedInjector64-4.0 and my sample console project also has x64 in platform selection. Here is my working code:

    class Program
    {
        static void Main(string[] args)
        {
            var proc = Process.GetProcessesByName("explorer").FirstOrDefault();
            Injector.Launch(proc.MainWindowHandle, typeof(Loader).Assembly.Location, typeof(Loader).FullName, "Inject");
        }
    }
    
    public class Loader
    {
        public static void Inject()
        {
            MessageBox.Show("Hello");
            Task.Run(() =>
            {
                Thread.Sleep(3000);
                MessageBox.Show("Hello again");
                Thread.Sleep(5000);
                MessageBox.Show("Hello again again");
            });
        }
    }
    

    0 讨论(0)
提交回复
热议问题