简体   繁体   中英

Performing a mouse click without moving cursor

I couldn't find any solution except moving the cursor by Cursor class, clicking with mouse_event then moving the cursor to its old position. I am playing with SendInput function right now but still no chance for a good solution. Any advice?

You should use Win32 API. Use pInvoked SendMessage from user32.dll

pInvoked Function

Then read about mouse events: Mouse Input on msdn

And then read about: System events and Mouse Mess.......

Also there is lots of info: Info

Here's an example following the approach Hooch suggested.

I created a form which contains 2 buttons. When you click upon the first button, the position of the second button is resolved (screen coördinates). Then a handle for this button is retrieved. Finally the SendMessage(...) (PInvoke) function is used to send a click event without moving the mouse.

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, 
        IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", EntryPoint = "WindowFromPoint", 
        CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr WindowFromPoint(Point point);

    private const int BM_CLICK = 0x00F5;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Specify the point you want to click
        var screenPoint = this.PointToScreen(new Point(button2.Left, 
            button2.Top));
        // Get a handle
        var handle = WindowFromPoint(screenPoint);
        // Send the click message
        if (handle != IntPtr.Zero)
        {
            SendMessage( handle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Hi", "There");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM