2016-12-10 4 views
0

У меня есть 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); 
} 

Мой контроль, кажется, постоянно входя еще даже когда я выбираю мой пользовательский элемент управления. Любая помощь в этом направлении будет оценена по достоинству.

+0

Вам необходимо переопределить OnEnter() и OnLeave() и вызвать this.Invalidate(). Это получает контроль, чтобы перекрасить себя, когда он получает и теряет фокус. Очень просто. –

+0

Привет @HansPassant, я не уверен, как это сделать. Не могли бы вы помочь мне. Я не могу заставить e.Graphics работать внутри onEnter или onLeave ... –

+0

Я сказал: «Назовите this.Invalidate()», это не похоже на «заставить работать e.Graphics»? Пример кода [находится здесь] (http://stackoverflow.com/a/3562449/17034). –

ответ

0

Для того, чтобы решить эту проблему, я использовал событие OnMouseClick с комбинацией объявить конструктор, который установлен начальный BorderColor на другое значение. например

private Color borderColor; 
    private int entered; 

    public TUserControlGroupBox() { 
     this.borderColor = SystemColors.ControlDark; 
    } 

    public Color BorderColor { 
     get { return this.borderColor; } 
     set { this.borderColor = value; } 
    } 

    public BorderState Border { 
     set { 
      switch (value) { 
       case BorderState.Unselected: 
        this.BorderColor = Color.LightGray; 
        break; 
       case BorderState.Selected: 
        this.BorderColor = Color.Black; 
        break; 
       case BorderState.SelectedFirst: 
        this.BorderColor = SystemColors.ControlDark; 
        break; 
      } 

      this.Invalidate(); 
     } 
    } 

    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 ((this.BorderColor == Color.Black || this.borderColor == SystemColors.ControlDark) && this.entered == 1) { 
      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); 
    } 

    protected override void OnMouseClick(MouseEventArgs e) { 
     this.entered = 1; 
     this.Invalidate(); 
     base.OnMouseClick(e); 
    } 

Надеюсь, что этот ответ поможет тем, кто ищет подобное решение в будущем.