Changing border color?

D

David Veeneman

Is there a simple way to change a UserControl border color?

I'm creating a UserControl that will have a border, using the
UserControl.BorderStyle property. The standard border is black; I'd like to
change the color to something a little more appealing. I've tried overriding
OnPaint, like this:

public partial class MyControl : UserControl
{
public MyControl()
{
this.SetStyle(ControlStyles.UserPaint, true);
InitializeComponent();
}

protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

if (this.BorderStyle == BorderStyle.FixedSingle)
{
int borderWidth = 1;
Color borderColor = SystemColors.ControlDark;
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,
borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid);
}
}

}

That doesn't work, because it leaves the black border. Plus, UserPaint
setting apparently drops all control painting in my lap, when all I want to
do is change the border color.

Is there a P/Invoke or a Windows message I can use to change the border
color? Thanks.
 
D

David Veeneman

I found my answer. The problem is that the border is not part of the client
area, which is what the OnPaint event args provide in e.Graphics. So, you
have to PInvoke GetDCEx() to get the window's device context. Then call
Graphics.FromHdc() to get a graphics object for the entire window, including
the non-client area on which the border is drawn. From there, it's drawing
as usual.

Here is some very simple code that draws a red border around a user control:

// PInvoke declaration
[DllImport("User32.dll", EntryPoint = "GetDCEx")]
internal static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hRgn, int flags);

// Event Override
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

IntPtr hWnd = this.Handle;
IntPtr hRgn = IntPtr.Zero;
IntPtr hdc = this.GetDCEx(hWnd, hRgn, 1027);

using (Graphics grfx = Graphics.FromHdc(hdc))
{
Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height -
1);
Pen pen = new Pen(Color.Red, 1);
grfx.DrawRectangle(pen, rect);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top