C#用windows Api Hooks 控制鼠标键盘在一个窗体内
主要是第一个窗体类.其他的2个类是我封装的WINDOWS API
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace HookDemo
{
public partial class Form1 : Form
{
private System.Windows.Forms.Timer monitorTimer = null;
private Kits.Hook.WinHook mouseHook = null;
private IntPtr HWND = IntPtr.Zero;
public Form1()
{
InitializeComponent();
this.monitorTimer = new Timer();
this.monitorTimer.Tick += new EventHandler(this.TimeProc);
this.monitorTimer.Interval = 1000;
mouseHook = new Kits.Hook.WinHook(Kits.Win32API.HookType.WH_MOUSE_LL);
}
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
this.monitorTimer.Enabled = true;
}
private void TimeProc(object sender, EventArgs e)
{
HWND = Kits.Win32API.WinAPI.FindWindow("Notepad", null);
if (HWND != IntPtr.Zero)
{
//Kits.Win32API.CSharpRect rect = new Kits.Win32API.CSharpRect();
//Kits.Win32API.WinAPI.GetWindowRect(HWND, ref rect);
//this.Text = string.Format("{0},{1},{2},{3}",rect.top,rect.left,rect.width,rect.height);
if (HWND == Kits.Win32API.WinAPI.GetForegroundWindow())
{
mouseHook.SetWindowsHookEx(new Kits.Win32API.HookProc(this.MouseHookProc));
}
else
{
if (mouseHook.HHook != 0)
{
mouseHook.UnhookWindowsHookEx();
}
}
}
}
private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (wParam == new IntPtr((int)Kits.Win32API.WindowsMessages.WM_MOUSEMOVE))
{
bool isOut = false;
Kits.Win32API.MouseHookStruct MyMouseHookStruct = (Kits.Win32API.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Kits.Win32API.MouseHookStruct));
Kits.Win32API.CSharpRect rect = new Kits.Win32API.CSharpRect();
Kits.Win32API.WinAPI.GetWindowRect(HWND, ref rect);
if (MyMouseHookStruct.pt.x >= rect.right)
isOut = true;
if (MyMouseHookStruct.pt.x
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!