c#WinForm:删除或自定义按钮的“焦点矩形”

时间:2009-11-09 11:50:04

标签: c# winforms

有没有办法禁用或更好地为常规按钮控件绘制自己的焦点矩形! (虚线似乎是Windowss 95ish)

我注意到控件属性(FOR BUTTONS)没有ownerdrawfixed设置(我不知道这是否是用于解决方案的路径,虽然我已经看到它用于自定义其他控件)。

6 个答案:

答案 0 :(得分:13)

获得这个权利比听起来更棘手。毫无疑问,自定义按钮绘制不可覆盖的原因之一。这按预期工作:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

class MyButton : Button {
    private VisualStyleRenderer renderer;
    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);
        if (this.Focused && Application.RenderWithVisualStyles && this.FlatStyle == FlatStyle.Standard) {
            if (renderer == null) {
                VisualStyleElement elem = VisualStyleElement.Button.PushButton.Normal;
                renderer = new VisualStyleRenderer(elem.ClassName, elem.Part, (int)PushButtonState.Normal);
            }
            Rectangle rc = renderer.GetBackgroundContentRectangle(e.Graphics, new Rectangle(0, 0, this.Width, this.Height));
            rc.Height--;
            rc.Width--;
            using (Pen p = new Pen(Brushes.DarkGray)) {
                e.Graphics.DrawRectangle(p, rc);
            }
        }
    }
}

答案 1 :(得分:11)

一种快速简便的方法是一起禁用焦点矩形是对控件进行子类化并包含以下代码:

public class CustomButton : Button  
{  
    protected override bool ShowFocusCues  
    {  
        get 
        {  
            return false;  
        }  
    }  
} 

答案 2 :(得分:2)

只是简单的方法。

设置

button.FlatStyle = Flat;
button.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255);
button.FlatAppearance.BorderSize = 0;
button.TabStop = false;
  

FlatAppearance.BorderColor

设置代码原因无法在设计模式下设置透明颜色。

答案 3 :(得分:0)

对Button类进行子类化并覆盖OnPaint。如果您的覆盖不调用base.OnPaint,则不会为该按钮绘制任何内容,您将完全控制(包括焦点矩形)。

答案 4 :(得分:0)

答案 5 :(得分:0)

我在使用 BackgroundImage 在按钮上设置图像时遇到了同样的问题。当用户按下“Tab”时,我的图像按钮会出现一个黑色矩形。

对我有用的解决方案是:

  1. 为我使用的每个按钮调用 NotifyDefault(false)
  2. 将我使用的每个按钮的 TabStop 属性设置为 false。

在 .NET Framework 4.6.2 上测试。

之前:

before

之后:

after