进程守护

时光怂恿深爱的人放手 提交于 2020-03-23 11:13:53
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);
        }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!