Results 1 to 3 of 3

Thread: [RESOLVED] How to align TextBox properly

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2016
    Posts
    597

    Resolved [RESOLVED] How to align TextBox properly

    I am doing an usercontrol. It uses Graphics.DrawString to draw Cell's text. On the edit mode, there's a TextBox (Single Line, BorderStyle = None) appearing. How to position the textbox to align the Text?

    I am trying to put offset X/Y, but with different Font or FontStyle or Font Size, the TextBox can't handle all situations.

    If I uses TextRender.DrawText to draw the Cell's text, the TextBox can align for most of case, much improved from Graphics.DrawString.

    After few days' try, I found TextBox uses DrawTextExW, TextRender.DrawText may do so.

    So the root cause is GDI+ vs GDI.

    Wondering why Excel can always align.
    Attached Images Attached Images  

  2. #2

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2016
    Posts
    597

    Re: How to align TextBox properly

    For Graphics.DrawString, the left padding and top padding of drawing String is unmeasurable for me, I need to help to get the accurate padding so that I can position TextBox.

    Code:
    public void SetTextBoxBounds(Rectangle CellRectangle)
    {
         txtEditor.Left = 1;
         txtEditor.Width = CellRectangle.Width - 2; 
         int gdiHeight = TextRenderer.MeasureText("ABC", txtEditor.Font).Height;                
         txtEditor.Height = gdiHeight;               
         txtEditor.Top = (int)Math.Round(Math.Floor((double)(CellRectangle.Height - gdiHeight) / 2.0));  
    }
    Attached Images Attached Images  

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2016
    Posts
    597

    Re: How to align TextBox properly

    OK.
    Almost resolved by using StringFormat.SetMeasurableCharacterRanges and graphics.MeasureCharacterRanges to calculate the padding then compensate. Test OK for most of case (Fonts).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width