I am setting my Winforms Button control properties to appear as a hyperlink would on a web page. I've formatted everything fine, except the border in the FlatAppearance object. I have code to act as pseudo-CSS (FormBackColor is a string constant.):
b.FlatStyle = FlatStyle.Flat
b.BackColor = ColorTranslator.FromHtml(FormBackColor)
b.ForeColor = Color.Blue
b.Font = New Font(b.Font.FontFamily, b.Font.Size, FontStyle.Underline)
b.Cursor = Cursors.Hand
Dim fa As FlatButtonAppearance = b.FlatAppearance
fa.BorderSize = 0
fa.MouseOverBackColor = b.BackColor
fa.MouseDownBackColor = b.BackColor
AddHandler b.MouseEnter, AddressOf ButtonMouseOver
AddHandler b.MouseLeave, AddressOf ButtonMouseOut
Here are the mouse out/over functions as a reference to what is going on:
Public Shared Sub ButtonMouseOver(ByVal sender As Object, ByVal e As EventArgs)
Dim b As Button = DirectCast(sender, Button)
Dim fa As FlatButtonAppearance = b.FlatAppearance
fa.BorderSize = 1
End Sub
Public Shared Sub ButtonMouseOut(ByVal sender As Object, ByVal e As EventArgs)
Dim b As Button = DirectCast(sender, Button)
Dim fa As FlatButtonAppearance = b.FlatAppearance
fa.BorderSize = 0
End Sub
The code removes the border from the flat Button control except on MouseOver, where I add a 1 pixel border. On MouseLeave, I remove the border. This is to show some visual feedback. This works fine when the button does not have the focus. However, if I click on the button, giving the button focus, mousing out and over again now shows a greater than 1 pixel border around the button. I'm imagining it's combining my button's explicit 1 pixel border with the traditional "Winform Button has the focus, so add a border" border around the Button.
How can I disable/remove the "Winform Button has the focus, so add a border" border? Or, should I just do a check in ButtonMouseOver to check if the control has the focus, being a condition of adding the border, and just be done with it? I'd prefer to remove the automatic border from focus for whatever reason 🙂
Best Answer
You can override the button's OnPaint event and re-paint over the drawn border with the form's background color: