1

我目前正在开发一个 Windows 窗体控件库,作为其中的一部分,我正在编写一个自定义按钮控件。它与标准的 Button 控件非常相似,但在呈现方式上确实存在一些差异。话虽这么说,下面的代码并不是我想要实现的目标的完整表示,但它确实说明了我想要表达的观点。

以下是代码示例:

public class Button : System.Windows.Forms.ButtonBase, IButtonControl
{
    public Button()
    {
        base.SetStyle(ControlStyles.UserPaint, true);
        base.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        base.SetStyle(ControlStyles.ResizeRedraw, true);
        base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        using (Bitmap bitmap = new Bitmap(this.ClientRectangle.Width, 
                                          this.ClientRectangle.Height, 
                                          PixelFormat.Format32bppArgb))
        {
            using(Graphics graphics = Graphics.FromImage(bitmap))
            {
                ButtonRenderer.DrawButton(graphics, 
                                          this.ClientRectangle, 
                                          this.Text, 
                                          this.Font, 
                                          TextFormatFlags.HorizontalCenter 
                                            | TextFormatFlags.VerticalCenter, 
                                          this.Focused, 
                                          this.GetButtonState());
            }
            e.Graphics.DrawImageUnscaled(bitmap, this.ClientRectangle);
        }
    }   
}

这工作正常,并适当地呈现按钮,但是,按钮上总是有一个焦点矩形,即使表单上的其他对象应该接收焦点(从而从自定义按钮中移除焦点),它仍然被绘制为焦点矩形。

是否有一个原因?为什么控件没有失去焦点?

4

1 回答 1

1

试试这个

public Button()
    {
        base.SetStyle(ControlStyles.UserPaint, true);
        base.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        base.SetStyle(ControlStyles.ResizeRedraw, true);
        base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        base.SetStyle(ControlStyles.Selectable, false);

    }   

它删除了控件的焦点矩形。

于 2013-04-24T09:26:03.507 回答