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

C#中如何监听文本选中及Ctrl+Shift+右箭头事件并执行代码

C#实现文本选中或Ctrl+Shift+右箭头触发自定义操作

一、监听文本选中事件

对于TextBox、RichTextBox这类支持文本选择的控件,可通过SelectionChanged事件监听文本选中状态,当选中长度大于0时执行自定义代码。

代码示例

// 窗体加载时绑定控件的SelectionChanged事件
private void Form1_Load(object sender, EventArgs e)
{
    textBox1.SelectionChanged += TextBox_SelectionChanged;
    // RichTextBox同理:richTextBox1.SelectionChanged += RichTextBox_SelectionChanged;
}

private void TextBox_SelectionChanged(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    // 判断是否有文本被选中
    if (textBox != null && textBox.SelectionLength > 0)
    {
        // 执行自定义业务代码
        CustomOperation();
    }
}

二、监听Ctrl+Shift+右箭头快捷键

沿用你提供的Hook_KeyUp事件逻辑,判断Ctrl、Shift键同时按下且触发右箭头键时,执行自定义代码。

代码示例

private void Hook_KeyUp(object sender, KeyEventArgs e)
{
    // 监听Ctrl+Shift+右箭头组合键
    if (e.Control && e.Shift && e.KeyCode == Keys.Right)
    {
        // 执行自定义业务代码
        CustomOperation();
        // 可选:阻止系统默认文本选择行为
        e.Handled = true;
    }

    // 保留原有Ctrl+C、Ctrl+V监听逻辑(如需保留)
    if (e.KeyCode == Keys.C && e.Control)
    {
        // 原Ctrl+C执行逻辑
    }
    if (e.KeyCode == Keys.V && e.Control)
    {
        // 原Ctrl+V执行逻辑
    }
}

// 统一的自定义操作方法
private void CustomOperation()
{
    // 这里编写你的业务逻辑,例如模拟粘贴操作
    // Clipboard.SetText("自定义内容");
    // textBox1.Paste();
}

注意事项

  • 上述代码适用于单个控件或窗体级别的按键监听,若需全局快捷键监听,需使用全局钩子实现。
  • 若要屏蔽系统默认的文本选择行为,可设置e.Handled = true或e.SuppressKeyPress = true。

内容的提问来源于stack exchange,提问作者today sprint

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:00:59