1. 程式人生 > >C#實現的鼠標鉤子

C#實現的鼠標鉤子

margin more fail codes ava private ops 類型 show

C#實現的鼠標鉤子,可以獲取鼠標在屏幕中的坐標,記得要以管理員權限運行才行


代碼如下:


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Reflection;

using System.Runtime.InteropServices;

using System.Text;

using System.Windows.Forms;

namespace app01

{

public partial class Form1 : Form

{

public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

//定義鉤子句柄

public static int hHook = 0;

//定義鉤子類型

public const int WH_MOUSE_LL = 14;

public HookProc MyProcedure;

//安裝鉤子

[DllImport(“user32.dll”, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]

public static extern int SetWindowsHookEx(int idHook, HookProc 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);

[StructLayout(LayoutKind.Sequential)]

public class POINT

{

public int x;

public int y;

}

[StructLayout(LayoutKind.Sequential)]

public class MouseHookStruct

{

public POINT pt;

public int hwnd;

public int wHitTestCode;

public int dwExtraInfo;

}

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

if (hHook == 0)

{

MyProcedure = new HookProc(this.MouseHookProc);

//這裏掛節鉤子

hHook = SetWindowsHookEx(WH_MOUSE_LL, MyProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);

if (hHook == 0)

{

MessageBox.Show(“SetWindowsHookEx Failed”);

return;

}

button1.Text = “卸載鉤子”;

}

else

{

bool ret = UnhookWindowsHookEx(hHook);

if (ret == false)

{

MessageBox.Show(“UnhookWindowsHookEx Failed”);

return;

}

hHook = 0;

button1.Text = “安裝鉤子”;

}

}

public int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)

{

MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

if (nCode < 0)

{

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

}

else

{

String strCaption = “x = ” + MyMouseHookStruct.pt.x.ToString(“d”) + ” y = ” + MyMouseHookStruct.pt.y.ToString(“d”);

this.Text = strCaption;

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

}

}

}

}

演示:

技術分享圖片

以上就是本文所述的全部內容了,希望大家能夠喜歡。

除聲明外,跑步客文章均為原創,轉載請以鏈接形式標明本文地址
C#實現的鼠標鉤子

本文地址: http://www.paobuke.com/develop/c-develop/pbk23118.html






相關內容

技術分享圖片C# NetRemoting實現雙向通信技術分享圖片C# 裝箱和拆箱的知識回顧技術分享圖片C# TextBox多行文本框的字數限制問題技術分享圖片C#怎麽給PDF添加背景圖片
技術分享圖片C#連接數據庫的方法技術分享圖片C#和JavaScript實現交互的方法技術分享圖片C#實現老板鍵功能的代碼技術分享圖片C#生成code128條形碼的方法

C#實現的鼠標鉤子