I'm working on a project which is in the C# language. 开发者_如何学GoMy question is: How can I detect the string which is under the Mouse Cursor and is between the "(" and ")"?
For example: I want to highlight "yahoo" in a textbox with this content when the mouse is over it: google(1) yahoo(2) apple(3) microsoft(4) ...
Edit
The following code will select the word directly under the Mouse
Xaml
<TextBox MouseMove="TextBox_MouseMove"
Text="Google(1) yahoo(2) apple(3) microsoft(4)"/>
Code behind
private void TextBox_MouseMove(object sender, MouseEventArgs e)
{
TextBox textBox = sender as TextBox;
Point mousePoint = Mouse.GetPosition(textBox);
int charPosition = textBox.GetCharacterIndexFromPoint(mousePoint, true);
if (charPosition > 0)
{
textBox.Focus();
int index = 0;
int i = 0;
string[] strings = textBox.Text.Split(' ');
while (index + strings[i].Length < charPosition && i < strings.Length)
{
index += strings[i++].Length + 1;
}
textBox.Select(index, strings[i].Length);
}
}
Very interesting problem, I don't know the answer right away, there are similar questions around, not a solution out of the box but if you work it out and let it inspire you, a solution could be possible:
Get Displayed Text from TextBlock
You can split up the text into multiple TextBlock
runs... just like you would in a web site (using spans
)... then you can tap into the MouseOver events in the styleing.
Example:
<TextBox>
<TextBox.Text>
<TextBlock Text="google" />
<TextBlock Text="(1) " />
<TextBlock Text="yahoo" />
<TextBlock Text="(2) " />
<TextBlock Text="apple" />
<TextBlock Text="(3) " />
<TextBlock Text="microsoft" />
<TextBlock Text="(4) " />
</TextBox.Text>
</TextBox>
Then add styling for the IsMouseOver of the textblocks that you want. (You can do this all in code as well).
精彩评论