samedi 31 juillet 2021

Transparent, custom checkbox with owner drawn text

I had the problem to create an owner drawn checkox as I didnt like the check styles. Subclassing the Winform checkbox is no big deal and overpainting the checkbox itself easy. But I didnt like the position of the text and there are no properties for positioning it.

So basically, clear the control's graphics and paint all new. Just, not working as you loose then the transparency. But without overpainting, original text painting was always overlapped owner draw text.

The solution was to set control's text to string.empty, call the base OnPaint method and override the OnTextChange event. That's it. Now I can draw the text exactly how I want and control is still transparent:

    class mycheckBox
    {
        private string _Text;

        protected override void OnTextChanged(EventArgs e)
        {
         // Prevent calling paint method on text change
        }

       protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
       {
        _Text = this.Text;
        this.Text = string.empty;
        base.OnPaint(e);
        Text = _Text; 

        // do your drawing here
        }
    }



Aucun commentaire:

Enregistrer un commentaire