我在一个进程上创建了一个钩子,用于注册其窗口移动的事件。
我使用了事件常量EVENT_OBJECT_LOCATIONCHANGE,详情请参见MSDN。
这是一个可以重现它的示例:
它确实起作用,但也会在简单的鼠标悬停应用程序时触发。有人能解释一下为什么吗?对象已更改位置、形状或大小。系统会为以下用户界面元素发送此事件:插入符号和窗口对象。服务器应用程序会为其可访问对象发送此事件。
这是一个可以重现它的示例:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class NativeMethods
{
[DllImport("user32.dll")]
public static extern System.IntPtr SetWinEventHook(uint eventMin, uint eventMax, System.IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
public delegate void WinEventDelegate(System.IntPtr hWinEventHook, uint eventType, System.IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
}
public partial class Form1 : Form
{
private const uint WINEVENT_OUTOFCONTEXT = 0x0000;
private const uint EVENT_OBJECT_LOCATIONCHANGE = 0x800B;
public Form1()
{
InitializeComponent();
int processId = Process.GetCurrentProcess().Id;
NativeMethods.SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, System.IntPtr.Zero, WinEventProc, (uint)processId, (uint)0, WINEVENT_OUTOFCONTEXT);
}
private void WinEventProc(System.IntPtr hWinEventHook, uint eventType, System.IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
if (hwnd == IntPtr.Zero)
{
Debug.WriteLine("Mouse moved");
}
else
{
Debug.WriteLine("Location changed");
}
}
}
}