1. 添加引用。 需要添加UIAutomationClient.dll,UIAutomationClientSideProvider.dll,UIAutomationTypes.dll
2. 添加相应的命名空间System.Windows.Automation。
使用 ui spy工具查看 processId 和automationId
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Automation;
using System.Runtime.InteropServices;
using System.Windows;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
[DllImport("user32.dll", EntryPoint = "SendMessage")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, string lParam);
const int WM_SETTEXT = 0x000C;//发送文本
private void button1_Click(object sender, EventArgs e)
{
AutomationElement element = FindElementById(3572, "1172");
MessageBox.Show(element.Current.ClassName);
SendMessage((IntPtr)element.Current.NativeWindowHandle, WM_SETTEXT, 0, "淘宝群发工具");
}
//public static void ClickLeftMouse(int processId, string automationId)
//{
// AutomationElement element = FindElementById(processId, automationId);
// if (element == null)
// {
// throw new NullReferenceException(string.Format("Element with AutomationId '{0}' and Name '{1}' can not be find.",
// element.Current.AutomationId, element.Current.Name));
// }
// Rect rect = element.Current.BoundingRectangle;
// int IncrementX = (int)(rect.Left + rect.Width / 2);
// int IncrementY = (int)(rect.Top + rect.Height / 2);
// //Make the cursor position to the element.
// SetCursorPos(IncrementX, IncrementY);
// //Make the left mouse down and up.
// mouse_event(MOUSEEVENTF_LEFTDOWN, IncrementX, IncrementY, 0, UIntPtr.Zero);
// mouse_event(MOUSEEVENTF_LEFTUP, IncrementX, IncrementY, 0, UIntPtr.Zero);
//}
public AutomationElement FindWindowByProcessId(int processId)
{
AutomationElement targetWindow = null;
int count = 0;
try
{
Process p = Process.GetProcessById(processId);
targetWindow = AutomationElement.FromHandle(p.MainWindowHandle);
return targetWindow;
}
catch (Exception ex)
{
count++;
StringBuilder sb = new StringBuilder();
string message = sb.AppendLine(string.Format("Target window is not existing.try #{0}", count)).ToString();
if (count > 5)
{
throw new InvalidProgramException(message, ex);
}
else
{
return FindWindowByProcessId(processId);
}
}
}
public AutomationElement FindElementById(int processId, string automationId)
{
AutomationElement aeForm = FindWindowByProcessId(processId);
AutomationElement tarFindElement = aeForm.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.AutomationIdProperty, automationId));
return tarFindElement;
}
}
}