.net c# winform 如果想模拟键盘输入内容,非常简单,3个步骤搞定
1. 获取当前所在的进程.
/// <summary>
/// 获取当前正在运行的应用程序
/// </summary>
/// <param name="name">应用程序名称</param>
/// <returns></returns>
public Process ProcessGet(string name)
{
var processes = Process.GetProcessesByName(name);
if (processes == null || processes.Length <= 0) return null;
foreach (var thisproc in processes)
{
var strBuilder = new StringBuilder(256);
Win32.GetWindowText(thisproc.MainWindowHandle, strBuilder, 256);
var txt = strBuilder.ToString();
if (string.IsNullOrEmpty(txt)) return thisproc;
if ("BOSSLOGIN:" + name == txt) return thisproc;
if (txt.IndexOf("BOSSLOGIN:") == 0) continue;
return thisproc;
}
return null;
}
2.将程序置于最前方,如果该程序光标已经在指定的地方,在直接忽略该步骤,如果不在,这需要模拟点击,将光标置于要输入内容的位置.
public Point ProcessShow(Process pross)
{
Win32.RECT rect;
Win32.GetWindowRect(pross.MainWindowHandle, out rect);
Point _point = new Point(rect.Left, rect.Top);
Win32.ShowWindow(pross.MainWindowHandle, Win32.WindowAction.Show);
Win32.SetForegroundWindow(pross.MainWindowHandle);
return _point;
}
public void ProcessClick(int x, int y, Point point)
{
x += point.X;
y += point.Y;
Win32.SetCursorPos(x, y);
Win32.mouse_event((int)(Win32.MouseEventFlags.LeftDown | Win32.MouseEventFlags.Absolute), x, y, 0, 0);
Thread.Sleep(50);
Win32.mouse_event((int)(Win32.MouseEventFlags.LeftUp | Win32.MouseEventFlags.Absolute), x, y, 0, 0);
Thread.Sleep(150);
}
调用:
private void zbtnclick_Click(object sender, EventArgs e)
{
SiteProcess item = new SiteProcess();
string name = zproname.Text;
var process = item.ProcessGet(name);
if (process == null) { MessageBox.Show("程序未启动"); return; }
Point point = item.ProcessShow(process);
item.ProcessClick(item.FormatInt(zx.Text, 0), item.FormatInt(zy.Text, 0), point);
}
3.这个时候,只要模拟输入内容即可.
public void InputMsg(IntPtr handle, string strtext)
{
foreach(var s in strtext)
{
SendKeys.SendWait(s.ToString());
Thread.Sleep(50);
}
Thread.Sleep(100);
}
调用:
private void zbtninput_Click(object sender, EventArgs e)
{
SiteProcess item = new SiteProcess();
string name = zproname.Text;
var process = item.ProcessGet(name);
if (process == null) { MessageBox.Show("程序未启动"); return; }
Point point = item.ProcessShow(process);
item.ProcessClick(item.FormatInt(zx.Text, 0), item.FormatInt(zy.Text, 0), point);
Thread.Sleep(2000);
item.InputMsg(process.MainWindowHandle, ztxtcon.Text);
}