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

Posted by Fusspawn on Stack Overflow See other posts from Stack Overflow or by Fusspawn
Published on 2009-07-22T16:32:40Z Indexed on 2010/04/25 4:43 UTC
Read the original article Hit count: 276

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#