【发布时间】:2015-06-22 16:35:58
【问题描述】:
基本上,我想创建一个 C# 应用程序(我正在使用在 Visual Studio 中打开的标准 WPF 项目),它可以检测用户何时向上或向下滚动鼠标滚轮,并触发鼠标点击当前鼠标屏幕位置。
我想要的程序的伪代码是
While the program is running
If the program detects a mouse scroll wheel up or scroll wheel down from the user
Perform a Single Left Click at the current mouse screen position
End If
End While
我不知道如何检测鼠标滚轮。我在 WPF 应用程序中使用 C#,我已经成功地能够移动鼠标光标并使用以下代码执行左键单击,但我无法弄清楚如何侦听鼠标滚轮输入并执行将当它接收到输入时发送鼠标左键。即使应用程序没有焦点,它也需要工作,因为鼠标点击被发送到另一个应用程序。任何人都可以为我指出正确的方向,我需要去哪里进行这项工作。
谢谢。当前代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Clicky_Clicky
{
public partial class MainWindow : Window
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;
public const int WM_MOUSEWHEEL = 0x020A;
public void MouseClick(int x, int y)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
public MainWindow()
{
int x = 1400;//Set Mouse Pos X
int y = 340;//Set Mouse Pos Y
InitializeComponent();
SetCursorPos(x, y); //Move Mouse to position on screen designated by X and Y
MouseClick(x, y); //Perform a mouse click (mouse event down, mouse event up)
}
}
}
编辑:通过更多的研究,看起来我想要的东西是鼠标的全局钩子,但我仍然无法找到一种简单的方法来获得我想要的东西。
【问题讨论】:
-
如果您滚动鼠标滚轮,MouseWheel 事件将触发
-
这有效,但仅适用于鼠标在矩形边界内时的鼠标滚动。我的需求要求即使在使用另一个应用程序时也能接收到鼠标滚动事件
标签: c# wpf interop mouseevent mousewheel