C#中使用鼠标Hook示例程序(原码)

作者:痕迹

示例代码如下:

using System;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
class Hook : Form
{
    [DllImport("kernel32 ")]
    public static extern int GetCurrentThreadId();

    [DllImport("user32 ", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern int SetWindowsHookEx(HookType idHook, HOOKPROC lpfn, int hmod, int dwThreadId);

    public enum HookType
    {
        WH_MOUSE = 7
    }

    public Hook()
    {
        this.AutoScaleBaseSize = new Size(5, 13);
        this.ClientSize = new Size(400, 200);
        this.Text = "鼠标勾子";
        this.Load += new EventHandler(this.Form1_Load);
    }
    public delegate int HOOKPROC(int nCode, int wParam, int lParam);

    public void SetHook(HOOKPROC callbackProc)
    {
        SetWindowsHookEx(HookType.WH_MOUSE, callbackProc, 0, GetCurrentThreadId());
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
        SetHook(new HOOKPROC(this.MyMouseProc));
    }

    public int MyMouseProc(int nCode, int wParam, int lParam)
    {
        if (nCode == 0 && wParam == 514)
        {
            MessageBox.Show("鼠标左键事件. LParam= " + lParam);
        }
        return 0; //return 1 to trap the mouse event  
    }

    public static void Main()
    {
        Application.Run(new Hook()); ;
    }
}
Powered by DvNews.net
来源:uncj.net
阅读:204 次
日期:2003-7-1
Contributors: FHL