Question

  1. Is there a difference between a real mouse click (by hand) and execution of the click from code (by mouse_event in c#)?
  2. Similarly, is there a difference between the real moving the mouse cursor and setting Cursor.Position?

If there is a difference:

  1. How to recognize source of that event?
  2. There is a way to simulate a mouse click / cursor move as if it came from a mouse or keyboard driver?

Edit1: Code sample added for @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);
    }
}
Était-ce utile?

La solution

There is no difference if you create proper Event arguments. The only way to find out that event is from "machine" is to analyze moments.

Autres conseils

@Garath, MSLLHOOKSTRUCT contain a LLMHF_INJECTED flag witch is set when the event come from a call to mouse_event function.

You can retrieve this information by using SetWindowsHookEx as I explained here.

The difference between a real click on a control and programmatical call to your mouse event handler should be the sender prarameter.

For real mouse clicks you receive the control that was clicked as sender. when you call an event handler programmatically you should provide a sensible sender

I'm also trying to do this in C# but within an injected c# dll, hosted clr. A friend of mine suggested reading this article http://pastebin.com/rj4YcW4C

I'v tried mouse_event, PostMessage,SendMessage,SendInput and Cursor.Position. All ignored but i beleave that article has the answers we both seek.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top