我需要在我的应用程序内的屏幕上显示鼠标位置 NOT 。
我使用了全局鼠标和键盘钩here
它在winforms下工作正常,但在wpf下无法工作。
我正在使用代码的版本1并使用以下
UserActivityHook activity=new UserActivityHook();
activity.OnMouseActivity += activity_OnMouseActivity;
但不是工作,而是给我以下错误:
其他信息:找不到指定的模块
以下代码
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
WPF还有其他选择,还是我错过了什么?
答案 0 :(得分:10)
dotctor的答案给出了鼠标位置,但不是我正在寻找的事件......
所以我自己想通了。以下是我的发现,供将来参考。
我们需要改变:
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
以下内容:
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
IntPtr.Zero,
0);
或者您可以从here下载已编辑的cs文件,然后我们就可以使用该事件
activity.OnMouseActivity += activity_OnMouseActivity;
我们可以使用e.X
和e.Y
获取鼠标位置。
答案 1 :(得分:1)
从向导获取帮助! (做到这一点很简单)
添加对System.Windows.Forms
的引用并使用Control.MousePosition
成为炼金术士! (合并你的物品)
合并Visual.PointToScreen和Mouse.GetPosition以及Application.Current.MainWindow
使用能量脉轮(win32)
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}