using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; 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); // Function to be hooked [DllImport("kernel32.dll")] static extern void Sleep(uint dwMilliseconds); // Must create delegate type // Marshal.GetFunctionPointerForDelegate requires non generic delegate tpe delegate void SleepFx(uint ms); static FxHook hook; // Hook function must be of same signature as of original function static void Sleep2(uint ms) { MessageBox.Show("Sleeping for: " + ms.ToString()); // Uninstall hook before calling real function otherwise stack overflow hook.Uninstall(); Sleep(ms); hook.Install(); } static void Main(string[] args) { var k32 = LoadLibrary("kernel32"); var slp = GetProcAddress(k32, "Sleep"); using(hook = new FxHook(slp, (SleepFx)Sleep2)) { hook.Install(); Sleep(1000); } // This will call original sleep Sleep(1000); } }