【问题标题】:Focused property is always true in Windows Forms controlWindows 窗体控件中的焦点属性始终为真
【发布时间】:2013-04-24 09:19:59
【问题描述】:

我目前正在开发一个 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);
        }
    }   
}

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

这是有原因的吗?为什么控件没有失去焦点?

【问题讨论】:

  • 我更新了我的答案.. 试试看。
  • 当它处于不应该被聚焦的状态时,如果你调整包含窗口的大小会发生什么?焦点矩形是否消失?如果是这样,当焦点状态发生变化时,您会遇到不重绘的问题。
  • 提供的代码没有重现,它可以很好地绘制焦点矩形,并在按钮没有焦点时省略它。也许它真的确实有焦点,Control.Focused 属性永远不会说谎。

标签: c# .net winforms focus gdi+


【解决方案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);

    }   

它会移除控件的焦点矩形。

【讨论】:

  • 这不起作用,因为 SetStyle 被定义为 SetStyle(ControlStyles, Boolean)。由于“CanFocus”是布尔值,因此需要这样定义 SetStyle:SetStyle(Boolean, Boolean)。另外,我希望按钮可以聚焦,但我希望它在失去焦点时正确更新。
  • 这更好,感谢更新,但是,我希望我的按钮像任何其他可聚焦控件一样获得/失去焦点,但我希望它正确失去焦点......也许我需要强制重绘 OnGotFocus 和 OnLostFocus 方法。话虽如此,努力+1! :-)
猜你喜欢
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2015-10-08
相关资源
最近更新 更多