views:

44

answers:

2

Hello all,

I have a Windows Form with a Rich Textbox control on the form. What I want to do is make it so that each line only accepts 32 characters of text. After 32 characters, I want the text to flow to the next line (I do NOT want to insert any carriage returns). The WordWrap property almost does this, except that it moves all the text entered, up to the last space in the text and moves it all. I just want to neatly wrap the text right after 32 characters. How can I do this? I'm using C#.

+1  A: 

If you are using only (one) fixed width font for text within rich text box then you can use MeasureString to count the width needed for 32 characters and then adjust rich text box width accordingly. Thats should do wrapping within 32 characters.

VinayC
I am using Courier New font, which is a fixed width font. Using your suggestion kinda works, however, if I set the WordWrap property to false, then my textbox scrolls horizontally, which I don't want. If I set WordWrap to true, then it wraps at 32 characters, however it wraps the entire last word down, which I don't want.
icemanind
A: 

Ok, I have found a way to do this (after a lot of googling and Windows API referencing) and I am posting a solution here in case anyone else ever needs to figure this out. There is no clean .NET solution to this, but fortunately, the Windows API allows you to override the default procedure that gets called when handling word wrapping. First you need to import the following DLL:

[DllImport("user32.dll")]

    extern static IntPtr SendMessage(IntPtr hwnd, uint message, IntPtr wParam, IntPtr lParam);

Then you need to define this constant:

 const uint EM_SETWORDBREAKPROC = 0x00D0;

Then create a delegate and event:

    delegate int EditWordBreakProc(IntPtr text, int pos_in_text, int bCharSet, int action);

    event EditWordBreakProc myCallBackEvent;

Then create our new function to handle word wrap (which in this case I don't want it to do anything):

     private int myCallBack(IntPtr text, int pos_in_text, int bCharSet, int action)

    {

        return 0;

    }

Finally, in the Shown event of your form:

        myCallBackEvent = new EditWordBreakProc(myCallBack);

        IntPtr ptr_func = Marshal.GetFunctionPointerForDelegate(myCallBackEvent);

        SendMessage(txtDataEntry.Handle, EM_SETWORDBREAKPROC, IntPtr.Zero, ptr_func);
icemanind