Muhammet Ali Asan
Muhammet Ali Asan

Reputation: 1514

Is it possible to get which character of text is clicked on C# form?

I am trying to get which of the * is clicked in text of label as in picture. Pic

NOTE : Number of * is not known at first.User inputs it.So the position of mouse click is not useful.

Upvotes: 0

Views: 391

Answers (2)

Muhammet Ali Asan
Muhammet Ali Asan

Reputation: 1514

Answer is :

X of first *'s location is known, equals = 10 .The asterisks are spaced equally,distance between two * is ~15 pixel .

When user clicks on one of asterisks , index of asterisks can be calculated as the code below

private void label4_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            double t = (e.X - 10) / 15.0;
            int indexOfClickedAsterisk=(int)Math.Round(t) + 1;
        }

Upvotes: 3

Peter Duniho
Peter Duniho

Reputation: 70671

It depends. If you are willing to display the text in a TextBox instead of Label (which is what it looks like you're using now), then you can use the GetCharIndexFromPosition method. Just make sure you specify the Point in client coordinates (comes for free if you are handling mouse clicks in the Label control itself).

Note that you can set the TextBox as ReadOnly, assuming you don't want the user actually modifying the text. They will still be able to select the text though.

If you need an actual Label control (e.g. you don't even want selectable text and the grayed-out appearance of a disabled TextBox isn't appropriate), then you'll have to write your own (or find one online that someone else wrote already), as the built-in one doesn't have that functionality. It would not be too difficult. You can use the TextRenderer methods to determine where each character is laid out when drawn and then use that information to correlate character positions with mouse clicks.

Upvotes: 2

Related Questions