Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an ownerdraw Trackbar in WinForms

I'm trying to make a trackbar with a custom graphic for the slider thumb. I have started out with the following code:

namespace testapp
{
    partial class MyTrackBar : System.Windows.Forms.TrackBar
    {
        public MyTrackBar()
        {
            InitializeComponent();
        }

        protected override void  OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
        //   base.OnPaint(e);
            e.Graphics.FillRectangle(System.Drawing.Brushes.DarkSalmon, ClientRectangle);
        }
    }
}

But it never calls OnPaint. Anyone else come across this? I have used this technique before to create an ownerdraw button but for some reason it doesn't work with TrackBar.

PS. Yes, I have seen question #625728 but the solution there was to completely re-implement the control from scratch. I just want to modify the existing control a little.

like image 683
Adam Pierce Avatar asked Oct 11 '09 21:10

Adam Pierce


1 Answers

If you want to paint over the top of the trackbar you can capture the WM_PAINT message manually, this means you dont have to re-write all the painting code yourself and can simply paint it, like this:

using System.Drawing;
using System.Windows.Forms;

namespace TrackBarTest
{
    public class CustomPaintTrackBar : TrackBar
    {
        public event PaintEventHandler PaintOver;

        public CustomPaintTrackBar()
            : base()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            // WM_PAINT
            if (m.Msg == 0x0F) 
            {
                using(Graphics lgGraphics = Graphics.FromHwndInternal(m.HWnd))
                    OnPaintOver(new PaintEventArgs(lgGraphics, this.ClientRectangle));
            }
        }

        protected virtual void OnPaintOver(PaintEventArgs e)
        {
            if (PaintOver != null) 
                PaintOver(this, e);

            // Paint over code here
        }
    }
}
like image 149
Aaron Murgatroyd Avatar answered Jan 03 '23 05:01

Aaron Murgatroyd