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;
}
}
加上一个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();
}
}
}
}