private class SetPID
{
public delegate void SETPID(uint iPID);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern SETPID GetProcAddress(IntPtr hModule, string procName);
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint GetCurrentProcessId();
private delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern HookProc GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr LoadLibrary(string sComName);
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr pInstance, int threadId);
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
private const string NKCore = "NKCore.dll";
private const int WH_GETMESSAGE = 3;
public static bool ProtectProcess(uint processID, out IntPtr iHookProcedure)
{
//创建VC++核心动态库
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, NKCore);
if (!File.Exists(path))
{
AppRuntime.CreateFileFromResource(false, "Rocky.Resources.NKCore.dll", path);
}
IntPtr pInstance = LoadLibrary(NKCore);
SetPID.SETPID pGPA = SetPID.GetProcAddress(pInstance, "SetPID");
if (pGPA == null)
{
iHookProcedure = IntPtr.Zero;
return false;
}
pGPA(processID);
HookProc HookProcedure = GetProcAddress(pInstance, "MsgProc");
iHookProcedure = SetWindowsHookEx(WH_GETMESSAGE, HookProcedure, pInstance, 0);
return iHookProcedure != IntPtr.Zero;
}
public static bool UnprotectProcess(ref IntPtr iHookProcedure)
{
return UnhookWindowsHookEx(iHookProcedure);
}