0

I am trying to coding to mouse left click in windows form. i want to do the left click of mouse anywhere on the screen when i say "left click". I have tried some codes but it gives errors here is the code:

public Form1()
    {
        InitializeComponent();


        this.KeyPreview = true;
        this.KeyDown += new    System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);


        var Form1 = new Form();
        Form1.Location = new Point(50, 50);

        Form1.AutoSize = true;
        Form1.Click += new EventHandler(Form1_Click);
        this.Controls.Add(Form1);
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int  cButtons, int dwExtraInfo);

    public const int MOUSEEVENTF_LEFTDOWN = 0x02;
    public const int MOUSEEVENTF_LEFTUP = 0x04;


    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        SimulateLeftClick();
    }


    private void SimulateLeftClick()
    {
        int xpos = Cursor.Position.X;
        int ypos = Cursor.Position.Y;
        mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
    }
case "left click":
                int xpos = Cursor.Position.X;
                int ypos = Cursor.Position.Y;
                mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
                mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
                break;

   private void Form1_Click(object sender, EventArgs e)
    {

        MessageBox.Show("Left Click simulated");
    }

when i run this program an error gives "Top-level control cannot be added to a control." at the this.Controls.Add(Form1) in above program. so please anyone give me a solution

2
  • 1
    You cannot add a Form (which is a top-level control) into a Form (or any other control). That's what your error is about.
    – Otiel
    Mar 7, 2015 at 17:05
  • @otiel Actually I want to do the left click after I opening the powepoint presentation. here I do controlling the powerpoint presentation according to my voice command. at that time my c# program have to minimize. I can see only powerpoint presentation on the screen. so how i do the left click on the powerpoint presentation. Mar 8, 2015 at 4:21

1 Answer 1

0

The top-level control is defined as the parent control that is not parented by another Windows Forms control. Typically, this is the outermost Form that the control is contained in.

In your case, it seems Form1 is the top level control. Remove the line:

 this.Controls.Add(Form1);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.