在 C# 中使用 Windows 窗体中鼠标左键单击的语音识别
本文关键字:单击 语音识别 鼠标 窗体 Windows | 更新日期: 2024-11-04 18:18:14
我正在尝试编码为在Windows表单中单击鼠标左键。 当我说"左键单击"时,我想在屏幕上的任何地方单击鼠标左键。我尝试了一些代码,但它给出了错误这是代码:
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");
}
当我运行此程序时,错误显示"无法将顶级控件添加到控件中"。Controls.Add(Form1) 在上面的程序中。所以请任何人给我一个解决方案
顶级
控件定义为不受另一个 Windows 窗体控件父级设置的父控件。通常,这是控件包含在的最外层窗体中。
在您的情况下,似乎Form1
是顶级控件。删除该行:
this.Controls.Add(Form1);