[SOLVED] C# Event mouse left and move

Issue

This Content is from Stack Overflow. Question asked by Đức Cường

Can someone help me complete my code , i don’t know how to click and move the image
I found on google the code

 [DllImport("user32.dll")]
    static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

    [Flags]   
    public enum MouseEventFlags
    {
        LEFTDOWN = 0x000000002,
        LEFTUP = 0x000000004,
        MIDDLEDOWN = 0x000000020,
        MIDDLEUP = 0x000000040,
        MOVE = 0x000000001,
        ABSOLUTE = 0x000008000,
        RIGHTDOWN = 0x000000008,
        RIGHTUP = 0x000000010,
    }
    public void mousedown(Point p)
    {
        Cursor.Position = p;
        mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0); 
    }

Code find image and move it

        private void btntestcode_Click(object sender, EventArgs e)
    {
        var screen = CaptureHelper.CaptureScreen();

        var subBitmap = ImageScanOpenCV.GetImage("testmousemove.PNG");

        var resBitmap = ImageScanOpenCV.FindOutPoint((Bitmap)screen, subBitmap);
        if (resBitmap != null)
        {
            mousedown((Point)resBitmap);
            
        }
    }



Solution

If you want to click on your picture and drag it and you want to move it everywhere, you can use this code.

  1. Add a picture box in your form and set your desired image in it:
    • I loaded an online image
pictureBox1.Load("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");
  1. Define two variables to save X and Y globally
private int oldX;
private int OldY;
  1. Add a MouseDown event to the PictureBox that you added in step 1:
if(e.Button == MouseButtons.Left)
{
    OldX = e.X;
    OldY = e.Y;
}
  1. In the end, add a MouseDown event to the PictureBox:
if (e.Button == MouseButtons.Left)
{
    pictureBox1.Left += e.X - oldX;
    pictureBox1.Top += e.Y - OldY;
}

enter image description here

Here you can see the whole code at once:

public partial class Form1 : Form
{
    private int oldX;
    private int OldY;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        pictureBox1.Load("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            oldX = e.X;
            OldY = e.Y;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            pictureBox1.Left += e.X - oldX;
            pictureBox1.Top += e.Y - OldY;
        }
    }
}


This Question was asked in StackOverflow by Đức Cường and Answered by Saeid Amini It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?