将按钮放在字符串前面

Place the button in front of the string

如何把button放在标记所在行的前面? button 应该放在字符串之前。如果用户移动标记,则 button 将移动到另一个字符串。如图所示。

目前,button 显示在 click 所在行的对面。

        private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
    {
        buttonaddmenu.Visible = true;

        int index = richTextBox1.SelectionStart;
        int line = richTextBox1.GetLineFromCharIndex(index);
        buttonaddmenu.Visible = true;
        int x = richTextBox1.Location.X - 10;
        int y = 25;

        for (int i = 0; i < richTextBox1.Lines.Length; i++)
        {
            buttonaddmenu.Location = new Point(3, Cursor.Position.Y - 170);
        }
    }

您可以根据按钮大小(我的按钮大小为 21、23)通过增加或减少 x 和 y 来更改新位置(例如:locationOnForm.X-20)试试这个:

      private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
        var pos = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
        Point locationOnForm = richTextBox1.FindForm().PointToClient(richTextBox1.Parent.PointToScreen(richTextBox1.Location));
        Point newLocation = new Point(locationOnForm.X-20,
                          pos.Y + locationOnForm.Y);
        button2.Location = newLocation;
        }

更新

        Point locationOnForm = panel1.FindForm().PointToClient(panel1.Parent.PointToScreen(richTextBox1.Location));