简体   繁体   中英

speech recognition for mouse left click in windows form using in c#

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

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);

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