У меня есть UserControl (Groupbox) со следующим OnPaint метода:Как сделать OnPaint запускать различные функции ControlPaint.DrawBorderStyle, когда пользователь выбирает элемент управления
protected override void OnPaint(PaintEventArgs e) {
Size tSize = TextRenderer.MeasureText(this.Text, this.Font);
Rectangle borderRect = e.ClipRectangle;
borderRect.Y += tSize.Height/2;
borderRect.Height -= tSize.Height/2;
ControlPaint.DrawBorder(e.Graphics, borderRect, this.borderColor, ButtonBorderStyle.Solid);
Rectangle textRect = e.ClipRectangle;
textRect.X += 6;
textRect.Width = tSize.Width;
textRect.Height = tSize.Height;
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), textRect);
e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), textRect);
}
Когда пользователь выбирает этот элемент управления, я хочу изменить границу, чтобы быть темнее, поэтому я попытался следующую логику:
protected override void OnPaint(PaintEventArgs e) {
Size tSize = TextRenderer.MeasureText(this.Text, this.Font);
Rectangle borderRect = e.ClipRectangle;
borderRect.Y += tSize.Height/2;
borderRect.Height -= tSize.Height/2;
if (ContainsFocus) {
ControlPaint.DrawBorder(e.Graphics, borderRect,
this.borderColor, 4, ButtonBorderStyle.Solid,
this.borderColor, 4, ButtonBorderStyle.Solid,
this.borderColor, 4, ButtonBorderStyle.Solid,
this.borderColor, 4, ButtonBorderStyle.Solid);
} else {
ControlPaint.DrawBorder(e.Graphics, borderRect, this.borderColor, ButtonBorderStyle.Solid);
}
Rectangle textRect = e.ClipRectangle;
textRect.X += 6;
textRect.Width = tSize.Width;
textRect.Height = tSize.Height;
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), textRect);
e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), textRect);
}
Мой контроль, кажется, постоянно входя еще даже когда я выбираю мой пользовательский элемент управления. Любая помощь в этом направлении будет оценена по достоинству.
Вам необходимо переопределить OnEnter() и OnLeave() и вызвать this.Invalidate(). Это получает контроль, чтобы перекрасить себя, когда он получает и теряет фокус. Очень просто. –
Привет @HansPassant, я не уверен, как это сделать. Не могли бы вы помочь мне. Я не могу заставить e.Graphics работать внутри onEnter или onLeave ... –
Я сказал: «Назовите this.Invalidate()», это не похоже на «заставить работать e.Graphics»? Пример кода [находится здесь] (http://stackoverflow.com/a/3562449/17034). –