How to create an ownerdraw dashboard in WinForms

I am trying to create a tracklist with custom graphics for a large slider. I started 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 he never calls OnPaint. Anyone else come across this? I used this technique before to create an ownerdraw button, but for some reason it doesn't work with TrackBar.

PS. Yes, I saw Question # 625728 , but the solution was to completely redo the control from scratch. I just want to slightly modify an existing control.

+4
source share
3 answers

I solved this by setting the UserPaint style in the constructor as follows:

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

Now called OnPaint.

+5
source

If you want to draw the top of the trackbar, you can manually capture the WM_PAINT message, which means that you do not need to rewrite the entire drawing code yourself and you can simply draw it, for example:

 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 } } } 
+5
source

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

-2
source

All Articles