C#如何做一个HOOK钩子,截获系统消息。

skyvin_xu 2009-12-06 11:49:46
本人初学C#。要做一个HOOK钩子实现在任务管理器隐藏自己的应用程序。
听说HOOK技术很成熟了。但始终没找到用C#如何做。
请高手指教。最好附完成源代码
...全文
636 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
dushaofuo 2012-03-26
  • 打赏
  • 举报
回复
转载。。
zl194 2009-12-07
  • 打赏
  • 举报
回复
关注
cjnkd 2009-12-07
  • 打赏
  • 举报
回复
ding 学习
hgxg0401sgb 2009-12-07
  • 打赏
  • 举报
回复
顶一个
tkscascor 2009-12-07
  • 打赏
  • 举报
回复
学习!
tkscascor 2009-12-07
  • 打赏
  • 举报
回复
学习!
cymandhxl 2009-12-07
  • 打赏
  • 举报
回复
good good study,day day up
Bingoguy 2009-12-07
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;

namespace KeyboardDLL
{
public class KeyboardHook
{
public delegate int KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

static int hKeyboardHook = 0;
KeyboardProc KeyboardHookProcedure;

/// <summary>
/// 钩子函数,需要引用空间(using System.Reflection;)
/// 线程钩子监听键盘消息设为2,全局钩子监听键盘消息设为13
/// 线程钩子监听鼠标消息设为7,全局钩子监听鼠标消息设为14
/// </summary>

public const int WH_KEYBOARD = 13;
public const int WH_MOUSE_LL = 14;

public struct KeyboardMSG
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
public int VK_CONTROL;
public int VK_MENU;
public int VK_DELETE;
}

/// <summary>
/// kernel32.dll是Windows 95,Windows 98和Windows Me中使用的32位动态链接库文件。
/// kernel32.dll是负责内存管理、输入输出以及中断等工作。启动Windows系统之后,
/// kernel32.dll就会被装载到不会被其他应用程序影响的受保护的内存空间中。在某些时候,
/// 会出现invalid page fault(IPF)错误信息,这是由于其他应用程序视图访问kernel32.dll
/// 所在的受保护内存空间引起的。不过有时,特定的某些程序也能引起这种错误。
/// </summary>
/// <returns></returns>
[DllImport("kernel32")]
public static extern int GetCurrentThreadId();

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, KeyboardProc lpfn, IntPtr hInstance, int threadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);

private int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
KeyboardMSG m = (KeyboardMSG)Marshal.PtrToStructure(lParam, typeof(KeyboardMSG));
if ((int)m.vkCode == 91 || (int)m.vkCode == 92 ||(int)m.vkCode == 10)
{
return 1;
}
if (((int)m.vkCode == 46) && ((int)m.vkCode == 17) && ((int)m.vkCode == 18))
{
return 2;
}
if ((int)m.vkCode == 20)
{
return 1;
}
if (1 == 1)
{
return 1;
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

// 安装钩子
public void KeyboardStart()
{
if (hKeyboardHook == 0)
{
// 创建HookProc实例
KeyboardHookProcedure = new KeyboardProc(KeyboardHookProc);

// 设置线程钩子
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProcedure,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
// 如果设置钩子失败
if (hKeyboardHook == 0)
{
KeyboardStop();
throw new Exception("SetWindowsHookEx failed.");
}
}
}

// 卸载钩子
public void KeyboardStop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
if (!(retKeyboard))
{
throw new Exception("UnhookWindowsHookEx failed.");
}
}
}
}

Bingoguy 2009-12-07
  • 打赏
  • 举报
回复
给你个代码看看!

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;

namespace MouseDLL
{
public class MouseHook
{
public delegate int MouseProc(int nCode, IntPtr wParam, IntPtr lParam);

static int hMouseHook = 0;
MouseProc MouseHookProcedure;

public const int WH_KEYBOARD = 13;
public const int WH_MOUSE_LL = 14;

public struct MouseMSG
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}

[DllImport("kernel32")]
public static extern int GetCurrentThreadId();

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, MouseProc lpfn, IntPtr hInstance, int threadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);

private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
MouseMSG m = (MouseMSG)Marshal.PtrToStructure(lParam, typeof(MouseMSG));

if (1 == 1)
{
return 1;
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}

// 安装钩子
public void MouseStart()
{
if (hMouseHook == 0)
{
// 创建HookProc实例
MouseHookProcedure = new MouseProc(MouseHookProc);

// 设置线程钩子
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
// 如果设置钩子失败
if (hMouseHook == 0)
{
HookStop();
throw new Exception("SetWindowsHookEx failed.");
}
}
}

// 卸载钩子
public void HookStop()
{
bool retKeyboard = true;
if (hMouseHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hMouseHook);
hMouseHook = 0;
}
if (!(retKeyboard))
{
throw new Exception("UnhookWindowsHookEx failed.");
}
}
//慎用!开机修改注册表,自动运行
//private void Form1_Load(object sender, EventArgs e)
//{
// RegistryKey hklm = Registry.LocalMachine;
// RegistryKey software = hklm.OpenSubKey("Software", true);
// RegistryKey microsoft = software.OpenSubKey("Microsoft", true);
// RegistryKey windows = microsoft.OpenSubKey("Windows", true);
// RegistryKey currentversion = windows.OpenSubKey("CurrentVersion", true);
// RegistryKey run = currentversion.OpenSubKey("Run", true);
// string[] ValName = run.GetValueNames();
// run.SetValue(ValName[0], System.Environment.CommandLine);
//}
}
}
frank_necsthz 2009-12-07
  • 打赏
  • 举报
回复
调用钩子函数。参照如下详细代码:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;

namespace OpenLogHook
{
/// <summary>
/// Class1
/// </summary>
public class Class1
{
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
//Declare hook handle as int.
static int hHook = 0;

//Declare mouse hook constant.
//For other hook types, you can obtain these values from Winuser.h in Microsoft SDK.
public const int WH_MOUSE = 7;
//public string temp;
public IntPtr glhLogWnd;

public delegate uint aw();
//Declare MouseHookProcedure as HookProc type.
HookProc MouseHookProcedure;

//Declare wrapper managed POINT class.
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}

//Declare wrapper managed MouseHookStruct class.
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public IntPtr hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}

//Declare wrapper managed MouseHookStruct class.
[StructLayout(LayoutKind.Sequential)]
public class COPYDATASTRUCT
{
public int dwData;
public int cbData;
public string lpData;
}

public struct Mystruct//mousehook struct
{
public string szCaption;
public string szHwnd;
public string szOperation;
public string szPtx;
public string szPty;
}
//public delegate int COPYDATASTRUCT();

public const int WM_MOUSEMOVE= 0x0200;
public const int WM_LBUTTONDOWN= 0x0201;
public const int WM_LBUTTONUP= 0x0202;
public const int WM_RBUTTONDOWN= 0x0204;
public const int WM_RBUTTONUP= 0x0205;

public const int WM_COPYDATA= 0x004A;
public const int WM_USER= 0x0400;
public const int WM_SENDDATA= WM_USER + 101;


//Import for SetWindowsHookEx function.
//Use this function to install thread-specific hook.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
IntPtr hInstance, int threadId);

//Import for UnhookWindowsHookEx.
//Call this function to uninstall the hook.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

//Import for CallNextHookEx.
//Use this function to pass the hook information to next hook procedure in chain.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode,
IntPtr wParam, IntPtr lParam);

[DllImport("kernel32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

[DllImport("user32.dll")]//,CharSet=CharSet.Auto,
//CallingConvention=CallingConvention.StdCall)]
private static extern IntPtr WindowFromPoint(POINT point);

[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll")]//,CharSet=CharSet.Auto,
//CallingConvention=CallingConvention.StdCall)]
private static extern IntPtr GetActiveWindow();

[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
private static extern int SendMessage(IntPtr hWnd, uint message, int wparam, ref Mystruct lparam);

public Class1()
{

//StartHook();

}

public void StartHook(IntPtr hWnd)
{
if(hHook == 0)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
string moduleName =
System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

glhLogWnd = hWnd;

hHook = SetWindowsHookEx(WH_MOUSE,
MouseHookProcedure,
Marshal.GetHINSTANCE(
System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]),
0);

//If SetWindowsHookEx fails.
if(hHook == 0 )
{

return;
}

}
else
{

}
}

protected int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
//Marshall the data from callback.

if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

IntPtr glhTargetWnd = WindowFromPoint(MyMouseHookStruct.pt);

StringBuilder sb2 = new StringBuilder();
sb2.Capacity = 256;

int i = GetWindowText(MyMouseHookStruct.hwnd, sb2, 256);

Mystruct myst = new Mystruct();
myst.szCaption = sb2.ToString();
myst.szHwnd = MyMouseHookStruct.hwnd.ToString();
myst.szPtx = MyMouseHookStruct.pt.x.ToString();
myst.szPty = MyMouseHookStruct.pt.y.ToString();

switch (wParam.ToInt32())
{
case WM_MOUSEMOVE:
myst.szOperation = "M_MOVE";
SendMessage(glhLogWnd, WM_SENDDATA, 0,ref myst);
break;

case WM_LBUTTONDOWN:
myst.szOperation = "LB_PUSH";
SendMessage(glhLogWnd, WM_SENDDATA, 0,ref myst);
break;

case WM_LBUTTONUP:
myst.szOperation = "LB_RELEASE";
SendMessage(glhLogWnd, WM_SENDDATA, 0,ref myst);
break;

case WM_RBUTTONDOWN:
myst.szOperation = "RB_PUSH";
SendMessage(glhLogWnd, WM_SENDDATA, 0,ref myst);
break;

case WM_RBUTTONUP:
myst.szOperation = "RB_RELEASE";
SendMessage(glhLogWnd, WM_SENDDATA, 0,ref myst);
break;

default:
break;

}

return CallNextHookEx(hHook, nCode, wParam, lParam);
}

}

}
}

freeboy827 2009-12-07
  • 打赏
  • 举报
回复
http://www.cnblogs.com/youzai/archive/2008/05/19/1202732.html
影子_爱人 2009-12-06
  • 打赏
  • 举报
回复
顶起

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧