So I have a WinForms application running on .NET 7.0 and I need to get a selection from a focused control (and this should work in any application that supports text selection) and replace it with specific text. The problem is that I can replace all the text in the field, but I can't replace just the part of the text that I need.
private void GetSelectedText()
{
try
{
var element = AutomationElement.FocusedElement;
if (element != null)
{
object pattern;
object valuePattern;
// Here I can get the selected text from almost any application.
if (element.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
{
var tp = (TextPattern)pattern;
var sb = new StringBuilder();
foreach (var r in tp.GetSelection())
{
sb.AppendLine(r.GetText(-1));
}
// Debug info:
MessageBox.Show(sb.ToString());
}
// And this code sets value of the focused control to "aaaaaaa".
if (element.TryGetCurrentPattern(ValuePattern.Pattern, out valuePattern))
{
((ValuePattern)valuePattern).SetValue("aaaaaaa");
}
}
}
catch (Exception ex)
{
// Debug info:
Console.WriteLine(ex.Message, ex.StackTrace);
}
}
I've also tried WinAPI calls for copying and pasting the value but I couldn't figure out how to replace the text without using the clipboard or writing a huge amount of code.
I would be grateful if you could help me with this.
CodePudding user response:
Text pattern doesn't provide any method to modify the text, and the value pattern also allows just setting the whole value. What you can do is modifying the selection through direct keyboard input. This is what I tried and works as expected:
var element = AutomationElement.FocusedElement;
if (element != null)
{
if (element.TryGetCurrentPattern(TextPattern.Pattern, out object pattern))
{
var tp = (TextPattern)pattern;
var selection = tp.GetSelection().FirstOrDefault();
if(selection != null)
{
SendKeys.SendWait("XXXXXX");
}
}
}
Fore more information, take a look at TextPattern overview
The TextPattern classes do not provide a means to insert or modify text. However, depending on the control, this may be accomplished by the UI Automation ValuePattern or through direct keyboard input. See the TextPattern Insert Text Sample for an example.