Here are two more solutions to send keys or set text of a specific control in another process which you may find useful in some scenarios:
- Using UI Automation
- Sending WM_SETTEXT message
Using UI Automation
Using UI Automation, you can get the specific automation element of the main window of the process and query its child to find your desired element. Then send data using either of ValuePattern, or SendKeysm or SendMessage.
To learn more about UI Automation, take a look at:
Here is an example to send text to notepad:
var notepad = System.Diagnostics.Process.GetProcessesByName("notepad").FirstOrDefault();
if (notepad != null)
{
var root = AutomationElement.FromHandle(notepad.MainWindowHandle);
var element = root.FindAll(TreeScope.Subtree, Condition.TrueCondition)
.Cast<AutomationElement>()
.Where(x => x.Current.ClassName == "Edit" &&
x.Current.AutomationId == "15").FirstOrDefault();
if (element != null)
{
if (element.TryGetCurrentPattern(ValuePattern.Pattern, out object pattern))
{
((ValuePattern)pattern).SetValue("This is a test.");
}
else
{
element.SetFocus();
SendKeys.SendWait("^{HOME}"); // Move to start of control
SendKeys.SendWait("^+{END}"); // Select everything
SendKeys.SendWait("{DEL}"); // Delete selection
SendKeys.SendWait("This is a test.");
// OR
// SendMessage(element.Current.NativeWindowHandle, WM_SETTEXT, 0, "This is a test.");
}
}
}
Sending WM_SETTEXT message
Using FindWindowEx, you can find the specific control of the main window of the other process, and then set the text using WM_SETTEXT, for exapmle:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, string lParam);
const int WM_SETTEXT = 0x000C;
private void button1_Click(object sender, EventArgs e)
{
//Find notepad by its name, or use the instance which you opened yourself
var notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
if(notepad!=null)
{
var edit = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, "Edit", null);
SendMessage(edit, WM_SETTEXT, IntPtr.Zero, "This is a test.");
}
}