gpt4 book ai didi

c# - 所选文本未显示在 WPF 窗口中的 Windows 窗体 RichTextBox 控件中

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:53 27 4
gpt4 key购买 nike

出于某种原因,我必须使用 Windows.Forms。 RichTextBox在我的 WPF 窗口中进行控制:

<Window x:Class="TestSelectionRTBDansWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:local="clr-namespace:TestSelectionRTBDansWPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button x:Name="btnSelect" Content="Select 10 first characters" Padding="10" Margin="0 0 0 10" Width="160" Click="BtnSelect_Click"/>
<WindowsFormsHost Grid.Row="1">
<wf:RichTextBox x:Name="rtb" Dock="Fill" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non mauris id ipsum auctor vehicula sed ut felis. Donec porttitor nisi eget ex porttitor, sed posuere sapien pretium."/>
</WindowsFormsHost>
</Grid>
</Window>

有时,我不想从另一个线程中选择我的 RichTextBox 中的文本:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void BtnSelect_Click(object sender, RoutedEventArgs e)
{
Thread th = new Thread(() =>
{
Thread.Sleep(2000);
SelectText(0, 10);
});
th.Start();
}

delegate void ParametrizedMethodInvoker5(int arg1, int arg2);
public void SelectText(int start, int length)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new ParametrizedMethodInvoker5(SelectText), start, length);
return;
}
rtb.SelectionStart = start;
rtb.SelectionLength = length;
MessageBox.Show("Selection done!\nSelected text: " + rtb.SelectedText);
}
}

消息框正确显示选定的文本,但在显示的 RichTextBox 控件中没有突出显示任何内容。编辑:使用鼠标或键盘时,选择效果非常好。

在写这篇文章时,我意识到添加对 System.Drawing 的引用并设置 rtb.SelectionBackColor 属性就可以了,尽管它看起来更像是一个补丁不是一个真正的解决方案,因为我将不得不处理 SelectionChanged 以重置先前选定文本的背景颜色。

有人对此有任何线索吗?

最佳答案

选择有效,但 RichTextBox 没有焦点。您只需通过以下方式将焦点设置到 RichTextBoxrtb.Focus(); 在通过 Tab 键手动选择或聚焦控件之后。

关于c# - 所选文本未显示在 WPF 窗口中的 Windows 窗体 RichTextBox 控件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078930/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com