Search code examples
c#dll.net-assemblymessageboxloader

How do I call functions from a DLL in my resources?


So I have this DLL and this other thing which I think is refered to as a Injector / loader? It basically loads my DLL into the process of itself so it takes my DLL and loads it into the process of "Injector.exe" In the example down below it doesnt load it from resources but instead from the desktop, the same thing applies here.

Now sicne it's being loaded it doesnt really call any functions and this is where my problem comes in.

I would like to call some the Messagebox function when the DLL is being loaded.

As far as I know and the most logical way would be to do this in the btnAssemblyLoad_Click event so when the event happens it calls the functions in the DLL. The issue is I have no idea what this would be called, I read something about "Reflection" but im not sure this is what I would need.

How should I go on about this?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AssemblyLoader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                tbAssemblyLocation.Text = ofd.FileName;
            }
        }

        private void btnAssemblyLoad_Click(object sender, EventArgs e)
        {

            AssemblyName an = AssemblyName.GetAssemblyName(tbAssemblyLocation.Text);
            Assembly.Load(an);
        }
    }
}

DLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MSgBOxDllCS
{
    public class Funcs
    {
        public void CallMessageBox()
        {
            MessageBox.Show("Hello");

        }
    }
}

Solution

  • You would need to call instance method of the non-static class, see below.

    // Step 1: load assembly to memory
    var an = AssemblyName.GetAssemblyName(tbAssemblyLocation.Text);
    var assembly = Assembly.Load(an);
    
    // Step 2: get type from the assembly by name
    var type = assembly.GetType("MSgBOxDllCS.Funcs");
    
    // Step 3: get method of the type
    var method = type.GetMethod("CallMessageBox");
    
    // Step 4: create instance of the type
    var funcs = Activator.CreateInstance(type);
    
    // Step 5: invoke the instance method
    method.Invoke(funcs, null);
    

    Generally speaking what you are building is called Plug-In Framework and there is plenty of examples on internet of how it can be done, you may be able to leverage existing frameworks too depending on your requirements.