How to add call to MessageBox.Show() with dnlib?

842 Views Asked by At

I am trying to make a call to MessageBox.Show from dnlib. I have this function that finds the Show method:

MethodDef GetSystemMethod(Type DeclaringType, string Methodname, Type[] MethodParams)
    {
        var filename = DeclaringType.Module.FullyQualifiedName;
        var mod = ModuleDefMD.Load(filename);
        TypeDef[] types = mod.GetTypes().ToArray();
        foreach(TypeDef t in types)
        {
            if(t.Name==DeclaringType.Name)
            {
                foreach(var m in t.Methods)
                {
                    bool ok = true;
                    int i = 0;
                    foreach(var p in m.Parameters)
                    {
                        if (p.Type.TypeName != MethodParams[i].Name) ok = false;
                    }
                    if(ok)
                    {
                        return m;
                    }
                }
            }
        }
        throw new Exception("System Method not found!");
    }

And this is how I use it:

method.Body.Instructions.Clear();
                    method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Nop.ToInstruction());
                    method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Ldstr.ToInstruction("changed method here!"));
                    method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Call.ToInstruction(GetSystemMethod(typeof(MessageBox), "Show", new Type[] { typeof(string)})));
                    method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Pop.ToInstruction());
                    method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Ret.ToInstruction());
                    module.Write(Path.GetDirectoryName(file) + "\\changed-" + Path.GetFileName(file));

When I run it, I get this exception when it tries to write the module to file. Can anyone please take a look and explain what I am doing wrong?

dnlib.DotNet.Writer.ModuleWriterException: 'Method System.Windows.Forms.HelpInfo System.Windows.Forms.MessageBox::get_HelpInfo() (06002BE3) is not defined in this module (TestProj.exe). A method was removed that is still referenced by this module.'
0

There are 0 best solutions below