Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a rectangular selection in a RichTextBox with Alt-Left-Mouse sweep?

There are quite a few applications that allow you to select a box or rectangle of text by sweeping with mouse while the Alt key is pressed. Visual Studio 2010 does this in the code editor, for instance. Emacs does it. Winword does it. We've all seen it. It seems like there must be a standard pattern to follow to encode this behavior but I cannot seem to find it.

I suspect I am not Googling with the correct keywords as all I am getting are false hits on rectangle, Alt-Left, sweep, selection, etc.

I'm sure I can code it up but it would mean disabling the normal selection code used in, say, RichTextBox. And that sounds ugly, error prone and probably more work than it is worth.

Anybody have a suggestion (be nice! :-) ) of how to do this or an example of how it is done?

UPDATE: I just found this article on Code Project that might apply: Column based selection

like image 649
Harold Bamford Avatar asked Oct 15 '22 05:10

Harold Bamford


1 Answers

RichTextBox is often mistaken for an editor. It is technically possible, you'll need a lot of code. First order of business is to select a fixed pitch font, like Courier.

Chief problem is that you cannot use the selection feature, it always spans lines. You'll have to fake it, possible by using the SelectionBackColor property. Implement the MouseDown and MouseMove events, check the Control.Modifiers property to see if the ALT key is down. Use GetCharIndexFromPosition to see what is being selected. In the move event, loop through the columns and rows that were de/selected, using the SelectionStart, SelectionLength and SelectionBackColor property to colorize characters.

This will flicker like a cheap motel. P/Invoke SendMessage() to send the WM_SETREDRAW message before and after to avoid this.

Doing something with the selection is challenging. You'll need to sub-class RTB so you can override WndProc() and detect the WM_COPY, WM_CUT, WM_PASTE messages. Other random problems is auto-scrolling when the mouse gets close to the top or bottom of the control and unselecting when another selection is being made.

Or you could use a real editor, like ScintillaNET. All and all, this answer is unlikely to get as many upvotes as the question.

like image 194
Hans Passant Avatar answered Nov 15 '22 05:11

Hans Passant