是否可以在 wpf 中更改光标闪烁率和光标移动速度?

Is is possible to change cursor blink rate and cursor movement speed in wpf?

我在相同的系统和相同的键盘属性上测试了 Word 2010 和 Word 2019。 我没有更改 Windows 键盘的属性。

光标移动和光标闪烁在 Word 2010 中很快,但在 Word 2019 中非常慢。

我想修改wpf项目中Cursor的闪烁频率和移动速度

怎么做?感谢您的帮助。

<Grid>
         <TextBox x:Name="tb"  Height="230" Padding="4"  TextWrapping="Wrap" AcceptsReturn="True"  Width="320" Focusable="True" Loaded="tb_Loaded"  />
    
     </Grid>
  private void tb_Loaded(object sender, RoutedEventArgs e)
     {
       Keyboard.Focus(tb);
     }

编辑: 我看了here,但不知道它是否正确以及如何去做。

WPF 基本上遵循 Windows 控制面板的闪烁率设置。我系统上的 Word 2019 也是如此。如果您想更改文本框上的比率,您唯一的选择是禁用 built-in 插入符号(文本光标),然后自己绘制。

以下是无耻地偷来的,灵感来自this article,解决了一些问题:

    当 TextBox 高度不是行高的完整倍数时,
  • SelectionChanged 会过早触发,从而导致错误的光标定位。改为 LayoutUpdated.
  • Caret.Height 尊重文本高度,而不是硬编码。

现在开始魔术。在您的 MainWindow.xaml:

上试试这个
<Grid x:Name="YouNeedAGridToContainTheTextBoxAndCanvas">

  <TextBox x:Name="CustomTextBox"
    FontSize="20" 
    AcceptsReturn="True" TextWrapping="Wrap"
    CaretBrush="Transparent" />
    <!--CaretBrush must be Transparent, as we will draw manually below-->

  <Canvas ClipToBounds="True">
    <Border x:Name="Caret" 
      Width="4" 
      Visibility="Collapsed"
      Background="Transparent"> <!--Start drawing Transparent-->
      <Border.Triggers>
        <EventTrigger RoutedEvent="Border.Loaded">
          <BeginStoryboard>
            <Storyboard RepeatBehavior="Forever">
              <ColorAnimationUsingKeyFrames 
                Storyboard.TargetProperty="Background.Color"
                FillBehavior="HoldEnd">
                <ColorAnimationUsingKeyFrames.KeyFrames>
                  <!--Ease to Red in 1sec-->
                  <EasingColorKeyFrame KeyTime="0:0:1.0" Value="Red"/>
                  <!--Ease back into Transparent in another 1sec-->
                  <EasingColorKeyFrame KeyTime="0:0:2.0" Value="Transparent" />
                </ColorAnimationUsingKeyFrames.KeyFrames>
              </ColorAnimationUsingKeyFrames>
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Border.Triggers>
    </Border>
  </Canvas>

</Grid>

然后您需要使用 MainWindow.xaml.cs 后面的代码手动更新绘图位置:

public MainWindow() //Constructor
{
    InitializeComponent();

    CustomTextBox.LayoutUpdated += (_, _) => {
        var rect = CustomTextBox.GetRectFromCharacterIndex(CustomTextBox.CaretIndex);
        if (rect.IsEmpty) return;
        Canvas.SetLeft(Caret, rect.Left);
        Canvas.SetTop(Caret, rect.Top);
        Caret.Height = rect.Height;
    };
    CustomTextBox.LostFocus += (_, _) => Caret.Visibility = Visibility.Collapsed;
    CustomTextBox.GotFocus += (_, _) => Caret.Visibility = Visibility.Visible;
    CustomTextBox.Focus();
}

随意调整彩色动画,根据需要添加帧并使用 KeyTime 播放 faster/slower 脉冲。如果您想要用力眨眼而不是脉冲,请使用 <DiscreteColorKeyFrame> 而不是 <EasingColorKeyFrame>