【问题标题】:How to make an ownerdraw Trackbar in WinForms如何在 WinForms 中制作 ownerdraw Trackbar
【发布时间】:2009-10-11 21:54:43
【问题描述】:

我正在尝试为滑块拇指制作一个带有自定义图形的轨迹栏。我从以下代码开始:

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

但它从不调用 OnPaint。还有人遇到这个吗?我以前使用过这种技术来创建一个所有者绘制按钮,但由于某种原因它不适用于 TrackBar。

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

【问题讨论】:

标签: winforms custom-controls ownerdrawn


【解决方案1】:

如果你想在轨迹栏的顶部进行绘制,你可以手动捕获 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
        }
    }
}

【讨论】:

  • 谢谢!你刚刚为我节省了很多时间!你太棒了!
【解决方案2】:

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

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

现在调用 OnPaint。

【讨论】:

    【解决方案3】:

    在这个答案中,PaintOver 从未被调用,因为它从未被赋值,它的值为 null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多