Coding机器人 2018-10-17 10:07 采纳率: 50%
浏览 1124
已采纳

C#RichTextBox鼠标右键点击后光标移动至点击的位置

C#RichTextBox鼠标右键点击后光标移动至点击的位置

代码如下:
首先我模拟鼠标点击,光标目前应该是在我点击的位置,但是txtTextArea.SelectionStart的值还是光标上一次停留的位置的值.
我现在就是想点鼠标右键,光标就移动到我点的位置,然后我要获取这个位置在RichTextBox中的值.
请大神指点,谢谢!

 private void txtTextArea_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,e.X,e.Y,0,0);
        int i = txtTextArea.SelectionStart;
    }
}
  • 写回答

1条回答

  • threenewbee 2018-10-17 16:43
    关注

    加上一个Application.DoEvents();就好了

     using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace Q702922
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            [System.Runtime.InteropServices.DllImport("user32")]
            private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
    
            const int MOUSEEVENTF_MOVE = 0x0001;
            const int MOUSEEVENTF_LEFTDOWN = 0x0002;
            const int MOUSEEVENTF_LEFTUP = 0x0004;
            const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
            const int MOUSEEVENTF_RIGHTUP = 0x0010;
            const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
            const int MOUSEEVENTF_MIDDLEUP = 0x0040;
            const int MOUSEEVENTF_ABSOLUTE = 0x8000;
    
            private void txtTextArea_MouseDown(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Right)
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, e.X, e.Y, 0, 0);
                    Application.DoEvents();
                    int i = txtTextArea.SelectionStart;
                    label1.Text = i.ToString();
                }
            }
        }
    }
    
    

    图片说明

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?