سؤال

Ok, I'm trying to do something a little specific here. I want to get the location of the selected text in a textbox.

To elaborate- I can use location to select text. If I have a textBox1 I could do:

textBox1.SelectionStart = 1;
textBox1.SelectionLength = 4;

That would start at the second letter and select 4 letters.

What I want to do is the opposite: when the user selects text, I want to find out what the start is and what the length is (or what the start is and what the end is. Either will work).

I thought about just searching the string for the selectedtext (textBox1.SelectedText). The problem comes if it is a common word or a string that is used multiple times. For instance.

This is a cat. This is a cat. This is a cat.

If they select the second sentence, using SelectedText to search the string for that specific sentence does me no good. It could be either of the 3.

So, my question is: When the user clicks a button, how do I determine the exact elements that are selected by the user, so that I can later manipulate those specific elements? Important to note the later part- I likely will not only want to manipulate the text when the button is pressed. I will also want to manipulate it later, at a time when the text may no longer be highlighted. This means I'll want to store SOMETHING to tell me what specific parts of the sentence I'm dealing with. If that solution isn't viable, is there a solution you can think of where, in the above "this is a cat" example, the user could select the second sentence, hit a button, and then later I know which sentence was selected when he hit that button?

هل كانت مفيدة؟

المحلول

According to the documentation, SelectionStart and SelectionLength can be both set and read. Just use those.

نصائح أخرى

You dont even need to know the position of selected text to manipulate them, to edit the text that you have selected in the text you can simple set the SelectedText property to the new edited value.

// if textBox1.text = "Hello World World"; with first "World" selected
textBox1.SelectedText = textBox1.SelectedText.Replace("World", "Raj");
// then it becomes "Hello Raj World" 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top