Hi, @华 张. Welcome to Microsoft Q&A.
I used the following code to successfully obtain the value of the text. You could refer to it.
if (textBox != null && textBox.TryGetCurrentPattern(TextPattern.Pattern, out object pattern))
{
TextPattern textPattern = (TextPattern)pattern;
if (textPattern.DocumentRange != null)
{
string text = textPattern.DocumentRange.GetText(-1);
Debug.WriteLine($"Selected Text: {text}");
return text;
}
else
{
Debug.WriteLine("No text selected.");
return string.Empty;
}
}
Complete code(Here I use the Click
event of Button
instead of the MouseHook_MouseUp
event of MouseHook
)
MainWindow.xaml
<Grid x:Name="MyGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox x:Name="MyText" Text="HAHA" Background="GreenYellow" Height="50"></TextBox>
<TextBlock x:Name="selectedTBK" Grid.Row="1" Background="DimGray" Height="50"></TextBlock>
<Button Grid.Row="1" Height="50" Width="200" Content="Click Me!" Margin="0,120,0,0" Click="Button_Click"></Button>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public IntPtr GetForegroundWindow()
{
return new WindowInteropHelper(this).Handle;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var text = GetControlText();
selectedTBK.Text = text;
Debug.WriteLine($"Selected text: {text}");
}
private string GetControlText()
{
try
{
IntPtr hwnd = GetForegroundWindow();
AutomationElement rootElement = AutomationElement.FromHandle(hwnd);
AutomationElement textBox = rootElement.FindFirst(TreeScope.Descendants,new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
if (textBox != null && textBox.TryGetCurrentPattern(TextPattern.Pattern, out object pattern))
{
TextPattern textPattern = (TextPattern)pattern;
if (textPattern.DocumentRange != null)
{
string text = textPattern.DocumentRange.GetText(-1);
Debug.WriteLine($"Selected Text: {text}");
return text;
}
else
{
Debug.WriteLine("No text selected.");
return string.Empty;
}
}
else
{
Debug.WriteLine("Text control not found or does not support TextPattern.");
return string.Empty;
}
}
catch (AccessViolationException ex)
{
Debug.WriteLine(ex.Message);
}
catch (ElementNotAvailableException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return string.Empty;
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.