首页 > 新闻系统 > 编程天地 > 文章正文

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

2008-04-17 09:58:53 来源:blog 作者:贾 涛 点击:
这个问题来自论坛提问,C#的大致代码如下

这个问题来自论坛提问,C#的大致代码如下

using  System;
using
 System.Windows.Forms;
using
 System.Runtime.InteropServices;
namespace
 WindowsApplication1
{
    
public   partial   class
 Form1 : Form
    
{
        
public
 Form1()
        
{
            InitializeComponent();
        }

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


        
void  hook_onMouseChange( object  sender, EventArgs e)
        
{
            
this .Text  =
 Cursor.Position.ToString();
        }

    }

    
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(
null null
);
            }

            
return   0 ;
        }

    }

}
9 7 3 1 2 4 8 :

精彩推荐
焦点大图推荐
本类热门文章

论坛美图

广告联系 | 版权说明 | 意见建议 | 加入收藏 | 军网站群 [ 军软件园 - 军软件商城 - 军软件园论坛 ]

电信与信息服务业务经营许可证:京ICP证050203