Measure String inside RichTextBox Control

后端 未结 6 1013
刺人心
刺人心 2020-12-19 02:44

Can somebody please explain how I would go about measuring the string inside a richtextbox control so that the I can automatically resize the richtextbox control according t

6条回答
  •  眼角桃花
    2020-12-19 02:59

    Add on to bathineni's great answer:

    Background: I needed to measure RTF output height for rendering onto paper and because I have custom dynamic page headers/footers I needed to control paging).

    (RichTextBox.GetLineFromCharIndex let me down because of complex RTF; including lines & multi column Tables with wordwrap).

    Anyhow all was working fine, until someone else used my app with the dreaded windows "Make text and other items larger or smaller" (DPI settings.) - in short now measuring bigger sized fonts it screwed up the page length calculations. (the printer still rendered the text and columns correctly - only the page lengths were now all wrong.)

    Only factoring DPI difference failed as in short bigger text didn't fit properly into source RTF tx and cellx values.

    Anyhow, in case others are doing similar crazy things bit of trial and error came up with the following (eventually very few) mods to the bathineni CalculateRichTextHeight method:

    RichTextBox richTextBox = new RichTextBox();     // same as original
    int dpix = richTextBox.CreateGraphics().DpiX;    // get dpi
    richTextBox.WordWrap = true;                     // I needed this, you many not
      // ... set size etc - same as original answer
    richTextBox.Scale(new System.Drawing.SizeF(dpix / 96, dpix / 96));  // scale RTB
      // ...
      // 96? my original calculations based on windows default 96dpi settings.
    

    Seems the otherwise obscure Control.Scale(sizef) is actually useful for something after all.

    Note: if converting results to actual printed lines, (in my case all my \pard's were "\sl-240\slmult0" which comes out to 16 (pix?) per line) also remember to re-factor the divisor. i.e. in my case:

    lines = height / (int)(16 * (dpix / 96))
    

提交回复
热议问题