如何在WinForms中创建一个ownerdraw Trackbar

Ada*_*rce 5 custom-controls ownerdrawn winforms

我正在尝试使用滑块拇指的自定义图形制作轨迹栏.我已经开始使用以下代码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它永远不会叫OnPaint.有人遇到过这个吗?我之前使用过这种技术来创建一个ownerdraw按钮但由于某种原因它不适用于TrackBar.

PS.是的,我已经看到问题#625728,但解决方案是从头开始完全重新实现控件.我只是想稍微修改现有的控件.

Aar*_*oyd 7

如果你想在轨迹栏的顶部绘画,你可以手动捕捉WM_PAINT消息,这意味着你不必自己重写所有的绘画代码,并且可以简单地绘制它,如下所示:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*rce 5

我通过在构造函数中设置UserPaint样式来解决它,如下所示:

public MyTrackBar()
{
    InitializeComponent();
    SetStyle(ControlStyles.UserPaint, true);
}
Run Code Online (Sandbox Code Playgroud)

OnPaint现在被调用.