How to make an ownerdraw Trackbar in WinForms

半城伤御伤魂 提交于 2019-11-30 14:44:29

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
        }
    }
}

I've solved it by setting the UserPaint style in the constructor like so:

public MyTrackBar()
{
    InitializeComponent();
    SetStyle(ControlStyles.UserPaint, true);
}

OnPaint now gets called.

In this answer PaintOver is never called, because it is never assigned, its value is null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!