读书人

C#怎么做一个HOOK钩子截获系统消息

发布时间: 2012-03-30 17:32:09 作者: rapoo

C#如何做一个HOOK钩子,截获系统消息。
本人初学C#。要做一个HOOK钩子实现在任务管理器隐藏自己的应用程序。
听说HOOK技术很成熟了。但始终没找到用C#如何做。
请高手指教。最好附完成源代码

[解决办法]
调用钩子函数。参照如下详细代码:
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);
}

}

}
}


[解决办法]
给你个代码看看![code=C#][/code]
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);
//}
}
}

读书人网 >C#

热点推荐