[C#][Windows API] 接收全域滑鼠事件(Windows Hook for Mouse)
不用DLL解碼 加入 MouseHook.cs、NativeContansts.cs、NativeMethods.cs、NativeStructs.cs
[WinForm, C#] 全域監控 滑鼠(Mouse)及鍵盤(Keyboard) 事件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsHookSample; //接收全域滑鼠事件
namespace WindowsMouseHook
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//全域滑鼠偵測啟動
MouseHook.Enabled = true;
//偵測滑鼠點擊
MouseHook.GlobalMouseDown += new EventHandler(MouseHook_GlobalMouseDown);
}
void MouseHook_GlobalMouseDown(object sender, MouseHook.MouseEventArgs e)
{
//視訊視窗黃色顯示
this.BackColor = System.Drawing.Color.LightYellow;
}
}
}
[WinForm, C#] 全域監控 滑鼠(Mouse)及鍵盤(Keyboard) 事件
第二版
加入參考 Gma.UserActivityMonitor.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Gma.UserActivityMonitor; //加入dll
namespace UserActivityMonitor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//啟動全域滑鼠點擊偵測
HookManager.MouseDown += HookManager_MouseDown;
}
private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
this.BackColor = System.Drawing.Color.PaleGreen;
}
}
}
F5執行會出現 未處理Win32Exception 的錯
修正方法: 修改專案屬性 目標Framework選擇 3.5版本
移除參考 Microsoft CSharp 即可正常執行
第一版
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using gma.System.Windows; //加入UserActivityHook.cs 後引用
namespace GlobalHook
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
UserActivityHook actHook;
private void Form1_Load(object sender, EventArgs e)
{
actHook = new UserActivityHook(); // crate an instance with global hooks
// hang on events
actHook.OnMouseActivity += new MouseEventHandler(MouseMoved);
actHook.Start(); //actHook.Stop();
}
public void MouseMoved(object sender, MouseEventArgs e)
{
//滑鼠點擊視窗變色
if (e.Clicks > 0) this.BackColor = System.Drawing.Color.PaleGreen;
}
}
}
F5執行會出現 未處理Win32Exception 的錯修正方法: 項目-屬性-調試-啟用Visual Studio宿主進程 把勾去掉





沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。