2

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.'
catalin00
  • 31
  • 1
  • 4
  • Did you manage to solve this? – ULI-R0 Dec 23 '18 at 21:55
  • No, unfortunately, and I don't know why no one is replying. I feel like I asked a stupid question. – catalin00 Dec 24 '18 at 11:17
  • There is no stupid question, try wrapping `GetSystemMethod` inside `method.Module.Import()` see if it works, like so: `method.Body.Instructions.Add(dnlib.DotNet.Emit.OpCodes.Call.ToInstruction(method.Module.Import(GetSystemMethod(typeof(MessageBox), "Show", new Type[] { typeof(string)}))));` – ULI-R0 Dec 25 '18 at 17:45

0 Answers0