You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TextBox的GotFocus事件中触发含KeyEventArgs的事件?

解决方案

有两种方式可以实现你的需求,根据实际场景选择:

方式一:直接调用方法(推荐,仅执行目标方法逻辑)

如果只是想执行TextBox27_PreviewKeyUp里的处理逻辑,不需要真正触发PreviewKeyUp事件(比如不需要其他注册了该事件的处理器执行),直接构造合适的KeyEventArgs参数调用方法即可:

private void TextBox27_GotFocus(object sender, RoutedEventArgs e)
{
    Stil53.Begin();
    TextBox27.Select(TextBox27.Text.Length, 0);
    Takvim_Kapat();
    
    // 构造KeyEventArgs,示例用Key.None,可根据需求修改为特定按键(如Key.Enter)
    KeyEventArgs keyArgs = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(TextBox27), 0, Key.None)
    {
        RoutedEvent = Keyboard.PreviewKeyUpEvent
    };
    
    // 直接调用目标方法
    TextBox27_PreviewKeyUp(sender, keyArgs);
}

方式二:触发PreviewKeyUp事件(执行所有注册的事件处理器)

如果需要让所有注册了TextBox27.PreviewKeyUp的事件处理器都执行,可以用RaiseEvent方法触发事件:

private void TextBox27_GotFocus(object sender, RoutedEventArgs e)
{
    Stil53.Begin();
    TextBox27.Select(TextBox27.Text.Length, 0);
    Takvim_Kapat();
    
    // 构造KeyEventArgs
    KeyEventArgs keyArgs = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(TextBox27), 0, Key.None)
    {
        RoutedEvent = Keyboard.PreviewKeyUpEvent
    };
    
    // 触发PreviewKeyUp事件,所有注册的处理器都会执行
    TextBox27.RaiseEvent(keyArgs);
}

补充说明

  • 若要模拟特定按键行为,把Key.None替换为对应的Key枚举值即可,比如Key.Enter、Key.Tab等。
  • PresentationSource.FromVisual(TextBox27)用于获取控件的可视化源,保证事件路由能正常工作。

内容的提问来源于stack exchange,提问作者Muharrem Adalmış

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 16:03:32