有趣的问题(貌似取词翻译),试验了一下,符合你的要求 private void textBox1_MouseClick(object sender, MouseEventArgs e) { if (textBox1.TextLength < 1) return; int index = textBox1.SelectionStart;//获取光标位置 int start = index; int end = index; int length = textBox1.TextLength; if (start >= length || start < 1)//超过文本框范围不处理 return; if (end >= length || end < 1) return; char c = textBox1.Text[start]; while (c != ' ' && start >=1)//向左搜空格,以空格来区分单词 { start--; c = textBox1.Text[start]; } c = textBox1.Text[end]; while (c != ' ' && end < textBox1.TextLength-1)//向右搜空格 { end++; c = textBox1.Text[end]; } //取出字符串,该字符串左右都是空格 string s = textBox1.Text.Substring(start, end - start); Console.WriteLine(s); }
int index = this.textBox1.GetCharIndexFromPosition(this.textBox1.PointToClient((Cursor.Position))); 获取鼠标字符串中的位置,再根据需要取。
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 WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.textBox1.Text = "sdfdsfsdfsdfsdgfsdgsddddddddddddddddddd"; } private void textBox1_MouseEnter(object sender, EventArgs e) {
int a = this.textBox1.GetCharIndexFromPosition(this .textBox1 .PointToClient (Cursor.Position ));
{
this.label1.Text = this.textBox1.GetCharFromPosition(e.Location).ToString();
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
if (textBox1.TextLength < 1)
return;
int index = textBox1.SelectionStart;//获取光标位置
int start = index;
int end = index;
int length = textBox1.TextLength;
if (start >= length || start < 1)//超过文本框范围不处理
return;
if (end >= length || end < 1)
return; char c = textBox1.Text[start];
while (c != ' ' && start >=1)//向左搜空格,以空格来区分单词
{
start--;
c = textBox1.Text[start]; }
c = textBox1.Text[end];
while (c != ' ' && end < textBox1.TextLength-1)//向右搜空格
{
end++;
c = textBox1.Text[end];
}
//取出字符串,该字符串左右都是空格
string s = textBox1.Text.Substring(start, end - start);
Console.WriteLine(s);
}
获取鼠标字符串中的位置,再根据需要取。
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.Text = "sdfdsfsdfsdfsdgfsdgsddddddddddddddddddd";
} private void textBox1_MouseEnter(object sender, EventArgs e)
{
int a = this.textBox1.GetCharIndexFromPosition(this .textBox1 .PointToClient (Cursor.Position ));
//你要对它进行的操作
}
}
}