Search code examples
c#.netaopcode-injectionruntimemodification

How to Inject code in c# method calls from a separate app


I was curious if anyone knew of a way of monitoring a .Net application's runtime info (what method is being called and such)

and injecting extra code to be run on certain methods from a separate running process.

say i have two applications:

app1.exe that for simplicity's sake could be

class Program
{
    static void Main(string[] args)
    {
      while(true){
        Somefunc();
      }
    }

    static void Somefunc()
    {
       Console.WriteLine("Hello World");
    }
} 

and I have a second application that I wish to be able to detect when Somefunc() from application 1 is running and inject its own code,

 class Program
 {
     static void Main(string[] args)
     {
       while(true){
          if(App1.SomeFuncIsCalled)
             InjectCode();
         }
     }

    static void InjectCode()
    {
       App1.Console.WriteLine("Hello World Injected");
    }
 } 

So The result would be Application one would show

Hello World
Hello World Injected 

I understand its not going to be this simple ( By a long shot ) but I have no idea if it's even possible and if it is where to even start.

Any suggestions ?

I've seen similar done in java, But never in c#.

EDIT: To clarify, the usage of this would be to add a plugin system to a .Net based game that I do not have access to the source code of.


Solution

  • It might be worth looking into Mono.Cecil for code injection. It won't work online the way you described in your question, but I believe it may do what you want offline (be able to find a given method, add code to it, and write out the modified assembly). http://www.codeproject.com/KB/dotnet/MonoCecilChapter1.aspx