CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 17

Threaded View

  1. #1
    Join Date
    Nov 2009
    Posts
    18

    [RESOLVED] Code that generates a mouse click event doesn't work

    This program is supposed to move to a button and click on it. When the button is clicked, it changes text.

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    
            private const int MOUSEEVENTF_LEFTDOWN = 0x02;
            private const int MOUSEEVENTF_LEFTUP = 0x04;
            private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
            private const int MOUSEEVENTF_RIGHTUP = 0x10;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
              //My button is about 150 units away from the top left corner
                Cursor.Position = new Point(this.Location.X + 150, this.Location.Y + 150);
    
                DoMouseClick();
            }
            public void DoMouseClick()
            {
                //Call the imported function with the cursor's current position
                int X = Cursor.Position.X;
                int Y = Cursor.Position.Y;
                mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y, 0, 0);           
                mouse_event(MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                button1.Text = "Clicked";
            }
    
        }
    }
    It moves till the button but it does not click on it. I don't know if something's wrong with the code or if I'm being blocked by some feature of Windows 7. Thank you for your help.
    Last edited by gregorian; December 6th, 2009 at 05:01 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured