c#中通过设置钩子监视鼠标移动

摘自http://blog.csdn.net/jinjazz/archive/2008/04/16/2298699.aspx

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace HotelManage
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }
         
        
void hook_onMouseChange(object sender, EventArgs e)
        {
            
this.Text = Cursor.Position.ToString();
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            Win32Hook hook 
= new Win32Hook();
            hook.onMouseChange 
+= new EventHandler(hook_onMouseChange);
            hook.SetHook();
        }
    }

    
public class Win32Hook
    {
        [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_GETMESSAGE 
= 3
        }

        
public delegate int HOOKPROC(int nCode, int wParam, int lParam);

        
public event System.EventHandler onMouseChange;

        
public void SetHook()
        {
            SetWindowsHookEx(HookType.WH_GETMESSAGE,
                
new HOOKPROC(this.MyKeyboardProc),
                
0,
                GetCurrentThreadId());
        }

        
public int MyKeyboardProc(int nCode, int wParam, int lParam)
        {
            
if (onMouseChange != null)
            {
                onMouseChange(
nullnull);
            }
            
return 0;
        }
    }
}
posted on 2008-06-06 14:42  迷你软件  阅读(410)  评论(0)    收藏  举报

本网站绝大部分资源来源于Internet,本站所有作品版权归原创作者所有!!如有以下内容:章节错误、非法内容、作者署名出错、版权疑问、作品内容有违相关法律等请及时与我联系. 我将在第一时间做出响应!本站所有文章观点不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。