简体   繁体   中英

How to: Get text index from label by mouse position? C#

I have a label that contains text like this:

00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3

So, as this is a label (i don't want to use a TextBox) i need to know the way for get the index of the text in the label in the position of the cursor.

Let's say that in the last text, the mouse was clicked upside the AA.

00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3 00 AA FA 08 0F FF 84 7A A7 22 27 94 73 9A 7F D3

Then, i need get the index of "AA", is there a way for do it?, (No matter if i've to use the Win32 API)

I really can't find anything...

I'm working with Windows Forms.

Is it winforms or WPF?

Have you tried using the onMouseMove event (http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousemove%28v=vs.71%29.aspx) and getting the location from the mousemoveeventargs? That should give a location. The you can calculate the font size and work out if you can divide the location by the number of charachters to find the position.

One thing to becareful of is, to make sure the font you use has characters with equal widths, many of them don't.

I wouldn't recommend the approach Im suggesting architecutally because its very hacky and is not likely to be reuseable for other things. It will also take a while to get rid of all of the errors.

I would recommend using WPF is possible, and using a listview with a template that makes into a grid. See this example here: http://www.mindscapehq.com/blog/index.php/2007/12/04/five-steps-to-wpf-data-visualisation/ That example shows how a listbox can have its appearance changed to place elements in x,y co-ordinates. The listview defaultly supports checking if items are selected or not. If you are stuck with winforms maybe, my orginal approach is ok, or maybe dynamically generating lots of labels is better.

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