How to make an ownerdraw Trackbar in WinForms

后端 未结 3 1936
囚心锁ツ
囚心锁ツ 2021-01-03 02:56

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          


        
相关标签:
3条回答
  • 2021-01-03 03:32

    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
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 03:32

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

    0 讨论(0)
  • 2021-01-03 03:44

    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.

    0 讨论(0)
提交回复
热议问题