J’ai un contrôle ProgressBar
comme les deux suivants:
Le premier est peint correctement. Comme vous pouvez le constater, le second n’a qu’un seul 0, il est censé en avoir deux, mais l’autre ne peut pas être vu, car ForeColor
de ProgressBar est identique à TextColor
. Est-il possible de peindre le texte en noir lorsque la ProgressBar
ci ProgressBar
dessous est peinte en chaux et de peindre le texte en chaux lorsque l’arrière-plan est noir?
Vous pouvez d’abord dessiner l’arrière-plan et le texte, puis le rectangle de chaux de premier plan à l’aide de la méthode PATINVERT
avec le paramètre PATINVERT
afin de combiner le dessin de premier plan avec le dessin d’arrière-plan:
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms;
public class MyProgressBar : Control { public MyProgressBar() { DoubleBuffered = true; Minimum = 0; Maximum = 100; Value = 50; } public int Minimum { get; set; } public int Maximum { get; set; } public int Value { get; set; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Draw(e.Graphics); } private void Draw(Graphics g) { var r = this.ClientRectangle; using (var b = new SolidBrush(this.BackColor)) g.FillRectangle(b, r); TextRenderer.DrawText(g, this.Value.ToSsortingng(), this.Font, r, this.ForeColor); var hdc = g.GetHdc(); var c = this.ForeColor; var hbrush = CreateSolidBrush(((cR | (cG << 8)) | (cB << 16))); var phbrush = SelectObject(hdc, hbrush); PatBlt(hdc, r.Left, rY, (Value * r.Width / Maximum), r.Height, PATINVERT); SelectObject(hdc, phbrush); DeleteObject(hbrush); g.ReleaseHdc(hdc); } public const int PATINVERT = 0x005A0049; [DllImport("gdi32.dll")] public static extern bool PatBlt(IntPtr hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int dwRop); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(int crColor); }
Remarque: les commandes servent uniquement à illustrer la logique de peinture. Pour une application réelle, vous devez append une validation sur les propriétés Minimum
, Maximum
et Value
.