Customers using C1TrueDbgrid often find themselves in need of changing the border color of the control. For instance, change the control border when the control has focus. However, there is no property or VisualStyle in C1TrueDbgrid to do this. In this blog let's discuss an approach to change C1TrueDbgrid's Border color. The approach involves use of two class
This class inherits from the Control class and contains the method DrawBorder() that accepts a Win32 API message and two integers ( width and height) as arguments. Also, there's a property BorderColor.
class Draw_Border : Control
{
[DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr hDC);
[DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hwnd);
private Color borderColor = Color.Black;
private static int WM_NCPAINT = 0x0085;
public void DrawBorder(ref Message message, int width, int height)
{
if (message.Msg == WM_NCPAINT)
{
Pen penBorder = new Pen(borderColor, 5);
IntPtr hdc = GetWindowDC(message.HWnd);
using (Graphics g = Graphics.FromHdc(hdc))
{
Rectangle rDraw = new Rectangle(0, 0, width, height);
g.DrawRectangle(penBorder, rDraw);
}
ReleaseDC(message.HWnd, hdc);
}
else
{
base.WndProc(ref message);
}
}
public Color BorderColor
{
get { return borderColor; }
set { borderColor = value; }
}
}
Lets add another class that inherits C1TrueDbgrid. This class contains the property BorderColor that gets exposed at design/run time. Also, we need to override WndProc and pass the control's height and width to DrawBorder method.
class MyGrid : C1.Win.C1TrueDBGrid.C1TrueDBGrid
{
private Draw\_Border borderDrawer = new Draw\_Border();
protected override void WndProc(ref Message m)
{
borderDrawer.DrawBorder(ref m, this.Width, this.Height);
base.WndProc(ref m);
}
public Color BorderColor
{
get { return borderDrawer.BorderColor; }
set
{
borderDrawer.BorderColor = value;
int width = this.Width;
this.Width = ((int)((Double)(this.Width) - 0.01));
this.Width = width;
}
}
}
To draw C1TrueDbGrid's border, there are two approaches :
For an existing application that uses C1TrueDbGrid, make the following changes in Form.Designer.cs file
private MyGrid myGrid1;
private MyGrid myGrid2;
this.myGrid1 = new BorderColor_CS.MyGrid();
this.myGrid2 = new BorderColor_CS.MyGrid();
Now, as our requirement was to toggle the C1TrueDbGrid border, we will set the border color in GotFocus and LostFocus events as :
void myGrid_GotFocus(object sender, EventArgs e)
{
var grid = sender as MyGrid;
grid.BorderColor = Color.Green;
}
void myGrid_LostFocus(object sender, EventArgs e)
{
var grid = sender as MyGrid;
grid.BorderColor = SystemColors.ControlLight;
}
And this is how C1TrueDbGrid that has focus looks like. Download CS Sample