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

如何在Edit.MouseDown事件中设置SelStart或模拟Edit.Click?

Edit控件右键点击SelStart设置问题解决办法

可以在Edit.MouseDown事件中模拟Click操作,不过得先让控件正确识别右键点击位置对应的文本索引,具体做法如下:

  • 首先在MouseDown事件里判断是否是右键点击(比如Delphi里判断Button = mbRight,C#里判断e.Button == MouseButtons.Right)
  • 调用控件的消息接口获取鼠标位置对应的字符索引:比如通过EM_CHARFROMPOS消息,这个消息能把鼠标坐标转换成控件内的字符位置
  • 先手动设置SelStart为获取到的字符索引,再触发Click事件

以Delphi为例,代码示例:

procedure TForm1.Edit1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  CharIndex: Integer;
begin
  if Button = mbRight then
  begin
    // 获取右键点击位置对应的字符索引
    CharIndex := Edit1.Perform(EM_CHARFROMPOS, 0, MakeLParam(X, Y));
    // 设置选中文本的起始位置
    Edit1.SelStart := CharIndex;
    // 模拟Click事件触发
    Edit1.Click;
  end;
end;

如果是C#,逻辑类似:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
private const int EM_CHARFROMPOS = 0xD7;

private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        int lParam = (e.Y << 16) | (e.X & 0xFFFF);
        int charIndex = SendMessage(textBox1.Handle, EM_CHARFROMPOS, 0, lParam);
        textBox1.SelectionStart = charIndex;
        // 模拟Click事件
        textBox1.PerformClick();
    }
}

之所以之前直接在MouseDown里设置SelStart无效,是因为默认右键点击Edit控件不会自动关联鼠标位置到文本索引,而左键Click事件会自动处理这个定位逻辑。先手动获取索引设置SelStart,再模拟Click,就能让SelStart位置和左键点击后右键的效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:26:05