简体   繁体   中英

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.

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;
        }

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM