Search code examples
c#tooltip

Customized ToolTip Not Working Correctly


In my Windows Form Application in C#, I have many TextBox controls, all of which have the same ToolTip control/message attached to them. Without any customization, the ToolTip was working perfectly.

enter image description here

Now, I added BackColor to the ToolTip balloons using the code snippet selected as the best answer in Change winform ToolTip backcolor. This does work great to add a BackColor to the ToolTip balloon, but it somehow removed all Environment.NewLine's in the string message. It seems to be showing the balloon of the same size, though.

enter image description here

Can someone tell me why this is happening, and how to fix this?

private ToolTip _tt = new ToolTip();
private string _ttipText;
private void ToolTipCustomization(){
    string nl = Environment.NewLine;
    /* This text is not shown properly when BackColor is added */
    _ttipText = "The value must be: " + nl +
                      "1, Numeric " + nl +
                      "2, Between 0 and 1000" + nl +
                      "3, A multiple of 10";
    _tt.OwnerDraw = true;
    _tt.BackColor = Color.LightBlue;
    _tt.Draw += new DrawToolTipEventHandler(TT_Draw);
}

private void TT_Draw(object sender, DrawToolTipEventArgs e){
    e.DrawBackground();
    e.DrawBorder();
    e.DrawText();
}

//Adding TextBox controls programmatically
private Textbox[] tbx = new TextBox[20];
private void CreateTextBox(){
    for(int i=0; i<20; i++){
        tbx[i] = new TextBox();
        /* More TextBox properties for design (Omit) */
        _tt.SetToolTip(tbx[i], _ttipText);  //Set ToolTip text to tbx here
        this.Controls.Add(tbx[i]);
    }
}

I tried subscribing PopupEventHandler in which I enlarged the balloon size but it did not solve my problem.


Solution

  • Finally, I was able to find a solution to my own question thanks to the advice from Hans Passant.

    It was as simple as adding a TextFormatFlags parameter to e.DrawText like the following:

    private void TT_Draw(object sender, DrawToolTipEventArgs e){
        e.DrawBackground();
        e.DrawBorder();
        e.DrawText(TextFormatFlags.VerticalCenter); /* here */
    }
    

    enter image description here

    Now It is showing the text properly. Thank you!