Skip to content

Instantly share code, notes, and snippets.

@NaxAlpha
Created July 25, 2016 07:07
Show Gist options
  • Save NaxAlpha/639c17079d38361599547828adf304fd to your computer and use it in GitHub Desktop.
Save NaxAlpha/639c17079d38361599547828adf304fd to your computer and use it in GitHub Desktop.
Managed Dll Injection with C#
using System.Diagnostics;
using System.Windows.Forms;
namespace Loader {
public static class Library
{
[DllExport]
static void ShowMessage() {
using(var p = Process.GetCurrentProcess()) {
// Add System.Windows.Forms reference
MessageBox.Show("Hello From " + p.ProcessName);
}
}
}
}
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program {
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
static void Main(string[] args) {
// Get our process
using (var p = Process.GetProcessesByName("notepad++")[0]) {
// Must give full path of library
// Or relative to target process
var path = @"c:\fakepath\Loader.dll";
var ptr = p.LoadLibrary(path);
// In order to get function address
// we must load library in our process
var lib = LoadLibrary(path);
var addr = GetProcAddress(lib, "ShowMessage");
// Lets call target function
p.Call(addr, IntPtr.Zero);
}
}
}
@GaneshKurcheti
Copy link

Could you define call a process. loadlibrary functions

@roboserg
Copy link

roboserg commented Nov 4, 2017

Cant build, it says "c# 'Process' does not contain a definition for 'LoadLibrary'"

@NaxAlpha
Copy link
Author

@baturalp1337
Copy link

Im get crash after inject. Pls help!

@NaxAlpha
Copy link
Author

I think this only works for 32-bit processes.

@EazyDuzIt736
Copy link

Works with 64-bit processes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment