当前位置: 代码迷 >> .NET Framework >> 自定义控件焦点有关问题
  详细解决方案

自定义控件焦点有关问题

热度:1111   发布时间:2016-05-02 01:07:02.0
自定义控件焦点问题
写了个用户自定义控件,希望控件在获得焦点和失去焦点时候显示的外观不一样,比如获得焦点时显示一个黑色的外框,请问如何实现?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
  public partial class xButton : UserControl
  {
  private bool bFocused = true;

  public xButton()
  {
  InitializeComponent();
  }

  public void DrawControl(Graphics g)
  {
  if (bFocused)
  {
  Pen p = new Pen(Color.Black, 1);
  g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
  p = null;
  }

  Pen p1 = new Pen(Color.AliceBlue, 1);
  Pen p2 = new Pen(Color.Gray, 1);
  Pen p3 = new Pen(Color.DarkGray, 1);

  g.DrawRectangle(p2, 1, 1, this.Width - 3, this.Height - 3);
  g.DrawLine(p1, 2, 2, this.Width - 3, 2);
  g.DrawLine(p1, 2, 2, 2, this.Height - 3);
  g.DrawLine(p3, this.Width - 3, 2, this.Width - 3, this.Height - 3);
  g.DrawLine(p3, 2, this.Height - 3, this.Width - 3, this.Height - 3);
  p1 = null;
  p2 = null;
  p3 = null;
  }

  private void UserControl1_Paint(object sender, PaintEventArgs e)
  {
  DrawControl(e.Graphics);
  }

  private void UserControl1_Click(object sender, EventArgs e)
  {
  this.Focus();
  bFocused = true;
  }
  }
}


------解决方案--------------------
重写下面3个方法:

在 OnPaint 里判断 bFocused 然后画(用 e.Graphics.DrawRectangle 就好了,不用4边画4条线。。。)
在 OnEnter 里设 bFocused = true 然后调用 Me.Refresh() 触发 OnPaint
在 OnLeave 里设 bFocused = false 同样调用 Me.Refresh() 触发 OnPaint
  相关解决方案