【问题标题】:mouse_event vs real mouse eventmouse_event 与真正的鼠标事件
【发布时间】:2013-04-16 08:37:52
【问题描述】:
  1. 真正的鼠标点击(手动)和执行从代码中点击(在 c# 中通过 mouse_event)有区别吗?
  2. 同理,真正移动鼠标光标和设置Cursor.Position有区别吗?

如果有区别:

  1. 如何识别该事件的来源?
  2. 有一种方法可以模拟鼠标点击/光标移动,就好像它来自鼠标或键盘驱动程序

Edit1:为@Marco Forberg 添加了代码示例。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);

    Button button;

    private void Form1_Load(object sender, EventArgs e)
    {

        button = new Button();
        button.Text = "Click";
        button.Location = new Point(50, 50);
        button.Size = new System.Drawing.Size(100, 20);
        button.Click += button_Click;
        Controls.Add(button);

        Button simulate = new Button();
        simulate.Text = "Simulate";
        simulate.Location = new Point(50, 100);
        simulate.Size = new System.Drawing.Size(100, 20);
        simulate.Click += simulate_Click;
        Controls.Add(simulate);

    }

    void button_Click(object sender, EventArgs e)
    {
        Console.WriteLine(sender);
    }

    void simulate_Click(object sender, EventArgs e)
    {
        Point location = button.PointToScreen(Point.Empty);
        Cursor.Position = new Point(location.X + (button.Width / 2), location.Y + (button.Height / 2));

        mouse_event(0x02 | 0x04, 0, 0, 0, 0);
    }
}

【问题讨论】:

  • 真正的点击可能会被拦截,并可能引发多个事件,运行一个事件只会触发一个事件。
  • 是的,例如。鼠标左键单击应该由 2 个事件创建:DOWN 0x02 和 UP 0x04。

标签: c# mouseevent keyevent mouseclick-event cursor-position


【解决方案1】:

如果您创建正确的事件参数,则没有区别。找出事件来自“机器”的唯一方法是分析时刻。

【讨论】:

  • 那么如果我改变Cursor.Position并及时随机运行mouse_event或者会模拟人手的行为,就无法识别origin event?
【解决方案2】:

@加拉斯, MSLLHOOKSTRUCT 包含一个 LLMHF_INJECTED 标志,当事件来自对 mouse_event 函数的调用时设置。

您可以使用SetWindowsHookEx 检索此信息,正如我在here 中解释的那样。

【讨论】:

    【解决方案3】:

    真正单击控件和以编程方式调用鼠标事件处理程序之间的区别应该是sender 参数。

    对于真正的鼠标点击,您会收到作为发送者点击的控件。当您以编程方式调用事件处理程序时,您应该提供一个 sensible 发送者

    【讨论】:

    • 我知道你的意思,但问题是关于事件的起源,而不是事件执行的对象。
    • “原点”是什么意思。 sender 参数持有/应该持有事件来自的元素
    • 对我来说,控制完成的事件并不重要。无论我是手动(手动)单击鼠标,还是使用 mouse_event(以编程方式),sedner 在这两种情况下都是相同的。
    • 你能告诉我一个代码 sn-p 你怎么称呼这个事件吗?
    • 啊,看来我误会了你。以为你调用了处理程序而不是模拟点击
    【解决方案4】:

    我也尝试在 C# 中执行此操作,但在注入的 c# dll 中,托管 clr。 我的一个朋友建议阅读这篇文章http://pastebin.com/rj4YcW4C

    我尝试过 mouse_event、PostMessage、SendMessage、SendInput 和 Cursor.Position。 都被忽略了,但我相信那篇文章有我们都在寻找的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多