• .NET的键盘Hook管理类,用于禁用键盘输入和切换


    一、MyHook帮助类

     此类需要编写指定屏蔽的按键,灵活性差。

    1. using System;
    2. using System.Runtime.InteropServices;
    3. using System.Diagnostics;
    4. using System.Windows.Forms;
    5. using Microsoft.Win32;
    6. namespace MyHookClass
    7. {
    8. /// <summary>
    9. /// 类一
    10. /// </summary>
    11. public class MyHook
    12. {
    13. //消息函数的委托
    14. public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
    15. static int hHook = 0;
    16. public const int WH_KEYBOARD_LL = 13;//底层键盘钩子
    17. static HookProc KeyBoardHookProcedure;
    18. //按键信息结构
    19. [StructLayout(LayoutKind.Sequential)]
    20. public class KeyBoardHookStruct
    21. {
    22. public int vkCode;
    23. public int scanCode;
    24. public int flags;
    25. public int time;
    26. public int dwExtraInfo;
    27. }
    28. //安装钩子
    29. [DllImport("user32.dll")]
    30. public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
    31. //卸载钩子
    32. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    33. public static extern bool UnhookWindowsHookEx(int idHook);
    34. //下一个钩挂的函数
    35. [DllImport("user32.dll")]
    36. public static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
    37. //返回当前线程 ID
    38. [DllImport("kernel32.dll")]
    39. public static extern int GetCurrentThreadId();
    40. //得到模块的句柄
    41. [DllImport("kernel32.dll")]
    42. public static extern IntPtr GetModuleHandle(string name);
    43. //安装钩子
    44. public static void InsertHook()
    45. {
    46. if (hHook == 0)
    47. {
    48. KeyBoardHookProcedure = new HookProc(KeyBoardHookProc);
    49. hHook = SetWindowsHookEx(WH_KEYBOARD_LL,
    50. KeyBoardHookProcedure,
    51. GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
    52. if (hHook == 0)
    53. {
    54. UnHook();
    55. throw new Exception("设置Hook失败!");
    56. }
    57. else
    58. {
    59. RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
    60. if (key == null)//如果该项不存在的话,则创建该项
    61. key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
    62. key.SetValue("DisableTaskMgr", 1, RegistryValueKind.DWord);
    63. //key.SetValue("DisableLockWorkstation", 1, RegistryValueKind.DWord);
    64. key.Close();
    65. }
    66. }
    67. }
    68. //卸载钩子
    69. public static void UnHook()
    70. {
    71. bool retKeyboard = true;
    72. if (hHook != 0)
    73. {
    74. retKeyboard = UnhookWindowsHookEx(hHook);
    75. hHook = 0;
    76. }
    77. //if (!retKeyboard) throw new Exception("卸载Hook失败!");
    78. RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
    79. if (key != null)
    80. {
    81. key.DeleteValue("DisableTaskMgr", false);
    82. //key.DeleteValue("DisableLockWorkstation", false);
    83. key.Close();
    84. }
    85. }
    86. //按键消息的处理函数
    87. public static int KeyBoardHookProc(int nCode, int wParam, IntPtr lParam)
    88. {
    89. if (nCode >= 0)
    90. {
    91. KeyBoardHookStruct kbh = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct));
    92. //添加自己的判断语句,如果符合要求的按键,就 return 1;
    93. //没有判断直接 return 1;那么就屏蔽所有按键除了ctrl+alt+del
    94. //屏蔽Ctrl+Esc
    95. if (kbh.vkCode == (int)Keys.Delete && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt) //截获Ctrl+Alt+Delete
    96. {
    97. PubLibrary.WriteErrLog("1.拦截信息:Ctrl+Alt+Delete");
    98. return 1;
    99. }
    100. if (kbh.vkCode == (int)Keys.Escape)
    101. {
    102. PubLibrary.WriteErrLog("2.拦截信息:Escape");
    103. return 1;
    104. }
    105. if (kbh.vkCode == 91) // 截获左win(开始菜单键)
    106. {
    107. PubLibrary.WriteErrLog("3.拦截信息:截获左win");
    108. return 1;
    109. }
    110. if (kbh.vkCode == 92)// 截获右win
    111. {
    112. PubLibrary.WriteErrLog("4.拦截信息:截获右win");
    113. return 1;
    114. }
    115. //if (kbh.vkCode == (int)Keys.L)
    116. //{
    117. // PubLibrary.WriteErrLog("5.拦截信息:L");
    118. // return 1;
    119. //}
    120. if (kbh.vkCode == (int)Keys.Alt)
    121. {
    122. PubLibrary.WriteErrLog("6.拦截信息:Alt");
    123. return 1;
    124. }
    125. if ((int)Control.ModifierKeys == (int)Keys.Alt) //截获alt
    126. {
    127. PubLibrary.WriteErrLog("7.拦截信息:Alt");
    128. return 1;
    129. }
    130. if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control) //截获Ctrl+Esc
    131. {
    132. PubLibrary.WriteErrLog("8.拦截信息:Ctrl+Esc");
    133. return 1;
    134. }
    135. if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Alt) //截获Alt+Esc
    136. {
    137. PubLibrary.WriteErrLog("9.拦截信息:Alt+Esc");
    138. return 1;
    139. }
    140. if (kbh.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+f4
    141. {
    142. PubLibrary.WriteErrLog("10.拦截信息:F4+Alt");
    143. return 1;
    144. }
    145. if (kbh.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+tab
    146. {
    147. PubLibrary.WriteErrLog("10.拦截信息:alt+tab");
    148. return 1;
    149. }
    150. if (kbh.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Shift) //截获Ctrl+Shift+Esc
    151. {
    152. PubLibrary.WriteErrLog("11.拦截信息:Ctrl+Shift+Esc");
    153. return 1;
    154. }
    155. if (kbh.vkCode == (int)Keys.Space && (int)Control.ModifierKeys == (int)Keys.Alt) //截获alt+空格
    156. {
    157. PubLibrary.WriteErrLog("12.拦截信息:alt+空格");
    158. return 1;
    159. }
    160. if (kbh.vkCode == 241) //截获F1
    161. {
    162. PubLibrary.WriteErrLog("13.拦截信息:F1");
    163. return 1;
    164. }
    165. if ((int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt + (int)Keys.Delete) //截获Ctrl+Alt+Delete
    166. {
    167. PubLibrary.WriteErrLog("14.拦截信息:Ctrl+Alt+Delete");
    168. return 1;
    169. }
    170. if ((int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Shift) //截获Ctrl+Shift
    171. {
    172. PubLibrary.WriteErrLog("15.拦截信息:Ctrl+Shift");
    173. return 1;
    174. }
    175. if (kbh.vkCode == (int)Keys.Space && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt) //截获Ctrl+Alt+空格
    176. {
    177. PubLibrary.WriteErrLog("16.拦截信息:Ctrl+Alt+空格");
    178. return 1;
    179. }
    180. }
    181. return CallNextHookEx(hHook, nCode, wParam, lParam);
    182. }
    183. }
    184. }

    二、KeyboardHookLib帮助类

    1. using System;
    2. using System.Runtime.InteropServices;
    3. using System.Diagnostics;
    4. using Microsoft.Win32;
    5. namespace VendorSoftwareReleaseLW.Class
    6. {
    7. /// <summary>
    8. /// 键盘Hook管理类
    9. /// </summary>
    10. public class KeyboardHookLib
    11. {
    12. private const int WH_KEYBOARD_LL = 13; //键盘
    13. //键盘处理事件委托 ,当捕获键盘输入时调用定义该委托的方法.
    14. private delegate int HookHandle(int nCode, int wParam, IntPtr lParam);
    15. //客户端键盘处理事件
    16. public delegate void ProcessKeyHandle(HookStruct param, out bool handle);
    17. //接收SetWindowsHookEx返回值
    18. private static int _hHookValue = 0;
    19. //勾子程序处理事件
    20. private HookHandle _KeyBoardHookProcedure;
    21. //Hook结构
    22. [StructLayout(LayoutKind.Sequential)]
    23. public class HookStruct
    24. {
    25. public int vkCode;
    26. public int scanCode;
    27. public int flags;
    28. public int time;
    29. public int dwExtraInfo;
    30. }
    31. //设置钩子
    32. [DllImport("user32.dll")]
    33. private static extern int SetWindowsHookEx(int idHook, HookHandle lpfn, IntPtr hInstance, int threadId);
    34. //取消钩子
    35. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    36. private static extern bool UnhookWindowsHookEx(int idHook);
    37. //调用下一个钩子
    38. [DllImport("user32.dll")]
    39. private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
    40. //获取当前线程ID
    41. [DllImport("kernel32.dll")]
    42. private static extern int GetCurrentThreadId();
    43. //Gets the main module for the associated process.
    44. [DllImport("kernel32.dll")]
    45. private static extern IntPtr GetModuleHandle(string name);
    46. private IntPtr _hookWindowPtr = IntPtr.Zero;
    47. //构造器
    48. public KeyboardHookLib() { }
    49. //外部调用的键盘处理事件
    50. private static ProcessKeyHandle _clientMethod = null;
    51. /// <summary>
    52. /// 安装勾子
    53. /// </summary>
    54. /// <param name="hookProcess">外部调用的键盘处理事件</param>
    55. public void InstallHook(ProcessKeyHandle clientMethod)
    56. {
    57. _clientMethod = clientMethod;
    58. // 安装键盘钩子
    59. if (_hHookValue == 0)
    60. {
    61. _KeyBoardHookProcedure = new HookHandle(OnHookProc);
    62. _hookWindowPtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
    63. //************************************
    64. //键盘线程钩子
    65. //SetWindowsHookEx( 2,KeyboardHookProcedure, IntPtr.Zero, GetCurrentThreadId()); //GetCurrentThreadId()为要监视的线程ID,你完全可以自己写个方法获取QQ的线程哦
    66. //键盘全局钩子,需要引用空间(using System.Reflection;)
    67. //SetWindowsHookEx( 13,KeyboardHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
    68. //
    69. //关于SetWindowsHookEx (int idHook, HookProc lpfn, IntPtr hInstance, int threadId)函数将钩子加入到钩子链表中,说明一下四个参数:
    70. //idHook 钩子类型,即确定钩子监听何种消息,上面的代码中设为2,即监听键盘消息并且是线程钩子,如果是全局钩子监听键盘消息应设为13
    71. //线程钩子监听鼠标消息设为7,全局钩子监听鼠标消息设为14
    72. //
    73. //lpfn 钩子子程的地址指针。如果dwThreadId参数为0 或是一个由别的进程创建的线程的标识,lpfn必须指向DLL中的钩子子程。 除此以外,lpfn可
    74. //以指向当前进程的一段钩子子程代码。钩子函数的入口地址,当钩子钩到任何消息后便调用这个函数。
    75. //
    76. //hInstance应用程序实例的句柄。标识包含lpfn所指的子程的DLL。如果threadId 标识当前进程创建的一个线程,而且子程代码位于当前
    77. //进程,hInstance必须为NULL。可以很简单的设定其为本应用程序的实例句柄。
    78. //
    79. //threadedId 与安装的钩子子程相关联的线程的标识符。如果为0,钩子子程与所有的线程关联,即为全局钩子。
    80. //************************************
    81. _hHookValue = SetWindowsHookEx(
    82. WH_KEYBOARD_LL,
    83. _KeyBoardHookProcedure,
    84. _hookWindowPtr,
    85. 0);
    86. //如果设置钩子失败.
    87. if (_hHookValue == 0)
    88. {
    89. UninstallHook();
    90. }
    91. else
    92. {
    93. RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
    94. if (key == null)//如果该项不存在的话,则创建该项
    95. key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
    96. key.SetValue("DisableTaskMgr", 1, RegistryValueKind.DWord);
    97. //key.SetValue("DisableLockWorkstation", 1, RegistryValueKind.DWord);
    98. key.Close();
    99. }
    100. }
    101. }
    102. //取消钩子事件
    103. public void UninstallHook()
    104. {
    105. if (_hHookValue != 0)
    106. {
    107. bool ret = UnhookWindowsHookEx(_hHookValue);
    108. if (ret) _hHookValue = 0;
    109. }
    110. RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
    111. if (key != null)
    112. {
    113. key.DeleteValue("DisableTaskMgr", false);
    114. //key.DeleteValue("DisableLockWorkstation", false);
    115. key.Close();
    116. }
    117. }
    118. //钩子事件内部调用,调用_clientMethod方法转发到客户端应用。
    119. private static int OnHookProc(int nCode, int wParam, IntPtr lParam)
    120. {
    121. if (nCode >= 0)
    122. {
    123. //转换结构
    124. HookStruct hookStruct = (HookStruct)Marshal.PtrToStructure(lParam, typeof(HookStruct));
    125. if (_clientMethod != null)
    126. {
    127. bool handle = false;
    128. //调用客户提供的事件处理程序。
    129. _clientMethod(hookStruct, out handle);
    130. if (handle) return 1; //1:表示拦截键盘,return 退出
    131. }
    132. }
    133. return CallNextHookEx(_hHookValue, nCode, wParam, lParam);
    134. }
    135. }
    136. }

    三、在WinForm中的使用

    1. using Newtonsoft.Json;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Data;
    5. using System.Diagnostics;
    6. using System.Runtime.InteropServices;
    7. using System.Threading;
    8. using System.Windows.Forms;
    9. using MyHookClass;
    10. using KeyboardHookLibClass;
    11. namespace TestForm
    12. {
    13. public partial class LoginForm : Form
    14. {
    15. DateTime _dtNow;
    16. [DllImport("user32.dll")]
    17. private static extern IntPtr GetForegroundWindow();
    18. [DllImport("user32.dll")]
    19. private static extern bool SetForegroundWindow(IntPtr hWnd);
    20. [DllImport("user32.dll")]
    21. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    22. [DllImport("user32.dll")]
    23. public static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
    24. [DllImport("user32.dll")]
    25. public static extern bool IsWindowVisible(IntPtr hWnd);
    26. //勾子管理类
    27. private KeyboardHookLib _keyboardHook = null;
    28. public delegate void ForegroundWin();
    29. private void LoginForm_Load(object sender, EventArgs e)
    30. {
    31. SetHook();
    32. Thread threadForeground = new Thread(ShowWindowAsync);
    33. //threadForeground.IsBackground = true;
    34. threadForeground.Start();
    35. }
    36. private void txt_KeyDown(object sender, KeyEventArgs e)
    37. {
    38. _dtNow = DateTime.Now;
    39. }
    40. private void txt_KeyUp(object sender, KeyEventArgs e)
    41. {
    42. if (e.KeyCode != Keys.Enter)
    43. {
    44. DateTime dtTemp = DateTime.Now;
    45. TimeSpan ts = dtTemp.Subtract(_dtNow);
    46. if (ts.Milliseconds > 65)
    47. {
    48. //setTool("错误:禁止手工输入!", "N");
    49. txt.Text = "";//清空
    50. }
    51. }
    52. }
    53. private void txtID_KeyPress(object sender, KeyPressEventArgs e)
    54. {
    55. if (e.KeyChar == 13)
    56. {
    57. //做些操作
    58. ClearHook();
    59. }
    60. }
    61. public static void SetWindowPos(IntPtr hWnd)
    62. {
    63. //0x0010为不激活窗口,这个比较关键
    64. SetWindowPos(hWnd, -1, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);// 0x001 | 0x002 | 0x0010| 0x040
    65. }
    66. private void ShowWindowAsync()
    67. {
    68. while (true)
    69. {
    70. //高版本的这里可以直接使用Action,更简化一些
    71. //ForegroundWin d = new ForegroundWin(action);
    72. //this.Invoke(d);
    73. Action a = new Action(() => { action(); });
    74. Thread.Sleep(100);//这个时间间隔,用户基本感觉不出有切换窗体
    75. }
    76. }
    77. void action()
    78. {
    79. IntPtr hWnd = this.Handle;
    80. if (hWnd != IntPtr.Zero || GetForegroundWindow() != hWnd)
    81. {
    82. //选中当前的句柄窗口
    83. SetWindowPos(hWnd);
    84. //SendKeys.SendWait(" ");
    85. }
    86. }
    87. private void ClearHook()
    88. {
    89. //取消勾子
    90. if (_keyboardHook != null) _keyboardHook.UninstallHook();
    91. //MyHook.UnHook();
    92. //ProcessMgr.ResumeWinlogon();
    93. }
    94. private void SetHook()
    95. {
    96. //安装勾子
    97. _keyboardHook = new KeyboardHookLib();
    98. _keyboardHook.InstallHook(this.OnKeyPress);
    99. //MyHook.InsertHook();
    100. //ProcessMgr.SuspendWinlogon();
    101. }
    102. /// <summary>
    103. /// 客户端键盘捕捉事件.
    104. /// </summary>
    105. /// <param name="hookStruct">由Hook程序发送的按键信息</param>
    106. /// <param name="handle">是否拦截</param>
    107. public void OnKeyPress(KeyboardHookLib.HookStruct hookStruct, out bool handle)
    108. {
    109. handle = false; //预设不拦截任何键
    110. if (hookStruct.vkCode == 91) // 截获左win(开始菜单键)
    111. {
    112. handle = true;
    113. }
    114. if (hookStruct.vkCode == 92)// 截获右win
    115. {
    116. handle = true;
    117. }
    118. if ((int)Control.ModifierKeys == (int)Keys.Alt) //截获alt
    119. {
    120. handle = true;
    121. }
    122. //截获Ctrl+Esc
    123. if (hookStruct.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control)
    124. {
    125. handle = true;
    126. }
    127. //截获alt+f4
    128. if (hookStruct.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt)
    129. {
    130. handle = true;
    131. }
    132. //截获alt+tab
    133. if (hookStruct.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt)
    134. {
    135. handle = true;
    136. }
    137. //截获alt+tab
    138. if (hookStruct.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Alt)
    139. {
    140. handle = true;
    141. }
    142. //截获F1
    143. if (hookStruct.vkCode == (int)Keys.F1)
    144. {
    145. handle = true;
    146. }
    147. //截获Ctrl+Alt+Delete
    148. if ((int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt + (int)Keys.Delete)
    149. {
    150. handle = true;
    151. }
    152. //如果键A~Z
    153. if (hookStruct.vkCode >= (int)Keys.A && hookStruct.vkCode <= (int)Keys.Z)
    154. {
    155. //挡掉B键
    156. if (hookStruct.vkCode == (int)Keys.B)
    157. hookStruct.vkCode = (int)Keys.None; //设键为0
    158. handle = true;
    159. }
    160. Keys key = (Keys)hookStruct.vkCode;
    161. PubLibrary.WriteErrLog("你按下:" + (key == Keys.None ? "" : key.ToString()));
    162. }
    163. }
    164. }

    四、其他类

    1. using System;
    2. using System.Runtime.InteropServices;
    3. namespace ShareToolClass
    4. {
    5. public class ShareTool : IDisposable
    6. {
    7. [DllImport("advapi32.dll", SetLastError = true)]
    8. static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
    9. int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
    10. // closes open handes returned by LogonUser
    11. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    12. extern static bool CloseHandle(IntPtr handle);
    13. [DllImport("Advapi32.DLL")]
    14. static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
    15. [DllImport("Advapi32.DLL")]
    16. static extern bool RevertToSelf();
    17. const int LOGON32_PROVIDER_DEFAULT = 0;
    18. const int LOGON32_LOGON_NEWCREDENTIALS = 9;
    19. const int LOGON32_LOGON_INTERACTIVE = 2;
    20. private bool disposed;
    21. public ShareTool(string username, string password, string ip)
    22. {
    23. // initialize tokens
    24. IntPtr pExistingTokenHandle = new IntPtr(0);
    25. IntPtr pDuplicateTokenHandle = new IntPtr(0);
    26. try
    27. {
    28. // get handle to token
    29. bool bImpersonated = LogonUser(username, ip, password,
    30. LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
    31. if (bImpersonated)
    32. {
    33. if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
    34. {
    35. int nErrorCode = Marshal.GetLastWin32Error();
    36. throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
    37. }
    38. }
    39. else
    40. {
    41. int nErrorCode = Marshal.GetLastWin32Error();
    42. throw new Exception("LogonUser error;Code=" + nErrorCode);
    43. }
    44. }
    45. finally
    46. {
    47. // close handle(s)
    48. if (pExistingTokenHandle != IntPtr.Zero)
    49. CloseHandle(pExistingTokenHandle);
    50. if (pDuplicateTokenHandle != IntPtr.Zero)
    51. CloseHandle(pDuplicateTokenHandle);
    52. }
    53. }
    54. protected virtual void Dispose(bool disposing)
    55. {
    56. if (!disposed)
    57. {
    58. RevertToSelf();
    59. disposed = true;
    60. }
    61. }
    62. public void Dispose()
    63. {
    64. Dispose(true);
    65. }
    66. }
    67. }
    1. using System;
    2. using System.Diagnostics;
    3. using System.Runtime.InteropServices;
    4. namespace ProcessMgrClass
    5. {
    6. class ProcessMgr
    7. {
    8. /// <summary>
    9. /// The process-specific access rights.
    10. /// </summary>
    11. [Flags]
    12. public enum ProcessAccess : uint
    13. {
    14. /// <summary>
    15. /// Required to terminate a process using TerminateProcess.
    16. /// </summary>
    17. Terminate = 0x1,
    18. /// <summary>
    19. /// Required to create a thread.
    20. /// </summary>
    21. CreateThread = 0x2,
    22. /// <summary>
    23. /// Undocumented.
    24. /// </summary>
    25. SetSessionId = 0x4,
    26. /// <summary>
    27. /// Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
    28. /// </summary>
    29. VmOperation = 0x8,
    30. /// <summary>
    31. /// Required to read memory in a process using ReadProcessMemory.
    32. /// </summary>
    33. VmRead = 0x10,
    34. /// <summary>
    35. /// Required to write to memory in a process using WriteProcessMemory.
    36. /// </summary>
    37. VmWrite = 0x20,
    38. /// <summary>
    39. /// Required to duplicate a handle using DuplicateHandle.
    40. /// </summary>
    41. DupHandle = 0x40,
    42. /// <summary>
    43. /// Required to create a process.
    44. /// </summary>
    45. CreateProcess = 0x80,
    46. /// <summary>
    47. /// Required to set memory limits using SetProcessWorkingSetSize.
    48. /// </summary>
    49. SetQuota = 0x100,
    50. /// <summary>
    51. /// Required to set certain information about a process, such as its priority class (see SetPriorityClass).
    52. /// </summary>
    53. SetInformation = 0x200,
    54. /// <summary>
    55. /// Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob).
    56. /// </summary>
    57. QueryInformation = 0x400,
    58. /// <summary>
    59. /// Undocumented.
    60. /// </summary>
    61. SetPort = 0x800,
    62. /// <summary>
    63. /// Required to suspend or resume a process.
    64. /// </summary>
    65. SuspendResume = 0x800,
    66. /// <summary>
    67. /// Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION.
    68. /// </summary>
    69. QueryLimitedInformation = 0x1000,
    70. /// <summary>
    71. /// Required to wait for the process to terminate using the wait functions.
    72. /// </summary>
    73. Synchronize = 0x100000
    74. }
    75. [DllImport("ntdll.dll")]
    76. private static extern uint NtResumeProcess([In] IntPtr processHandle);
    77. [DllImport("ntdll.dll")]
    78. private static extern uint NtSuspendProcess([In] IntPtr processHandle);
    79. [DllImport("kernel32.dll", SetLastError = true)]
    80. private static extern IntPtr OpenProcess(
    81. ProcessAccess desiredAccess,
    82. bool inheritHandle,
    83. int processId);
    84. [DllImport("kernel32.dll", SetLastError = true)]
    85. [return: MarshalAs(UnmanagedType.Bool)]
    86. private static extern bool CloseHandle([In] IntPtr handle);
    87. public static void SuspendProcess(int processId)
    88. {
    89. IntPtr hProc = IntPtr.Zero;
    90. try
    91. {
    92. // Gets the handle to the Process
    93. hProc = OpenProcess(ProcessAccess.SuspendResume, false, processId);
    94. if (hProc != IntPtr.Zero)
    95. NtSuspendProcess(hProc);
    96. }
    97. finally
    98. {
    99. // Don't forget to close handle you created.
    100. if (hProc != IntPtr.Zero)
    101. CloseHandle(hProc);
    102. }
    103. }
    104. public static void ResumeProcess(int processId)
    105. {
    106. IntPtr hProc = IntPtr.Zero;
    107. try
    108. {
    109. // Gets the handle to the Process
    110. hProc = OpenProcess(ProcessAccess.SuspendResume, false, processId);
    111. if (hProc != IntPtr.Zero)
    112. NtResumeProcess(hProc);
    113. }
    114. finally
    115. {
    116. // Don't forget to close handle you created.
    117. if (hProc != IntPtr.Zero)
    118. CloseHandle(hProc);
    119. }
    120. }
    121. public static void SuspendWinlogon()
    122. {
    123. Process[] processes = Process.GetProcesses();
    124. foreach (Process process in processes)
    125. {
    126. if (process.ProcessName == "winlogon")
    127. {
    128. SuspendProcess(process.Id);
    129. }
    130. }
    131. }
    132. public static void ResumeWinlogon()
    133. {
    134. Process[] processes = Process.GetProcesses();
    135. foreach (Process process in processes)
    136. {
    137. Console.WriteLine(process.ProcessName);
    138. if (process.ProcessName == "winlogon")
    139. {
    140. ResumeProcess(process.Id);
    141. }
    142. }
    143. }
    144. }
    145. }

  • 相关阅读:
    Android聚合SDK母包反编译出包教程
    2022.11.25Dungeon Master POJ - 2251
    Python用GAN生成对抗性神经网络判别模型拟合多维数组、分类识别手写数字图像可视化...
    【MySQL】的存储引擎 事务 锁机制 日志
    【servelt原理_14_Session对象】
    社区系统项目复盘-5
    INI 格式配置文件基础知识
    Linux 进程间通信
    js监听页面滚动
    笛卡尔积现象
  • 原文地址:https://blog.csdn.net/weixin_50478033/article/details/133272524