需要调用user32.dll
csharp
[DllImport("user32.dll")]
public static extern bool ScreenToClient(IntPtr hWnd, ref Point lpPoint);
public static int WM_GETTEXT = 0x0D;//应用程序发送此消息来复制对应窗口的文本到缓冲区
public static int WM_GETTEXTLENGTH = 0x0E;//得到与一个窗口有关的文本的长度(不包含空字符)
public static int BM_CLICK = 0xF5; //鼠标点击的消息,对于各种消息的数值,大家还是得去API手册
const int WM_LBUTTONDOWN = 0x0201;
const int WM_LBUTTONUP = 0x0202;
bool isRuning = false;
IntPtr lastHwnd = IntPtr.Zero;
System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(true);
private bool SendClid(Point p)
{
try
{
//Point p = new Point(1200, 150);
IntPtr curHwnd = WindowFromPoint(p);//获取当前坐标位置的控件句柄(不能获取Disabled未激活的控件)
ScreenToClient(curHwnd, ref p);//将屏幕坐标转换为窗口客户区坐标
curHwnd = ChildWindowFromPoint(curHwnd, p);//从当前坐标查找子控件(可获取Disabled未激活的控件).如果没有则返回自己
SendMessage(curHwnd, WM_LBUTTONDOWN, 0, 0);//按下鼠标左键
SendMessage(curHwnd, WM_LBUTTONUP, 0, 0);//抬起鼠标左键
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 获取 指定点 控件文本
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private string GetCtlText(Point p)
{
string ret;
try
{
IntPtr curHwnd = WindowFromPoint(p);//获取当前坐标位置的控件句柄(不能获取Disabled未激活的控件)
ScreenToClient(curHwnd, ref p);//将屏幕坐标转换为窗口客户区坐标
curHwnd = ChildWindowFromPoint(curHwnd, p);//从当前坐标查找子控件(可获取Disabled未激活的控件).如果没有则返回自己
int len = SendMessage(curHwnd, WM_GETTEXTLENGTH, 0, 0);
StringBuilder sb = new StringBuilder(len + 1);
SendMessage(curHwnd, WM_GETTEXT, sb.Capacity, sb);
ret = sb.ToString();
return ret;
}
catch (Exception ex)
{
return ex.Message;
}
}
调用:
csharp
Invoke((Action)delegate
{
string s_text = GetCtlText(new Point(200, 240)); // 读取 SN
MessageBox.Show(s_text);
SendClid(new Point(400, 100)); // 该位置是一个按钮
});