Any way to custom draw a title bar?

B

Benny Raymond

How would you go about custom drawing the title bar of a form? I'd like
to change it so that I can add different colors to my title and also
change how the close button works (since I override it and cause the
form to minimize).

Thanks in advance,
Benny
 
N

Nicholas Paldino [.NET/C# MVP]

Benny,

You will have to override the WndProc method on your form. In there,
you will want to handle the WM_NCPAINT message, which is sent when the frame
(including the title bar) needs to be painted.

If you call the base method of WndProc, it will draw the frame, and then
you can draw over the frame, or, you can paint the whole thing yourself.

Hope this helps.
 
B

Benny Raymond

I'm now overriding wndproc and handling the wm_ncpaint by letting base
do it first and then drawing over the top... This works the first time
the program draws the close button but after that it doesn't work...
Note: I'm just drawing a big white box right now to get the
functionality in - why is the close button drawing outside of
wm_ncpaint?... Here's the code:

protected override void WndProc(ref Message m)
{
switch ( m.Msg )
{
case (int) MSG.WM_NCPAINT:
base.WndProc( ref m );
Main_OnNcPaint( ref m );
return;
}
}

private void Main_OnNcPaint ( ref Message m )
{
Debug.WriteLine("drawing");
// If I use GetDCEx, the program crashes on the Graphics
// .FromHdc Line - GetDCEx returns 0?
//IntPtr hdc = User32.GetDCEx( m.HWnd, m.WParam,
((uint)DCX_FLAGS.DCX_WINDOW)|((uint)DCX_FLAGS.DCX_INTERSECTRGN) );

IntPtr hdc = User32.GetWindowDC(m.HWnd);
Graphics g = Graphics.FromHdc(hdc);

int CaptionHeight = Bounds.Height - ClientRectangle.Height; //Titlebar
Size CloseButtonSize = SystemInformation.CaptionButtonSize;
int X = Bounds.Width - CloseButtonSize.Width;
int Y = 6;

// ControlPaint causes the program to not use XP styles anymore :(
//ControlPaint.DrawButton(g, X, Y, 15, 15, ButtonState.Normal);

// Fill a rectangle instead
g.FillRectangle(SystemBrushes.Window, X, Y, CloseButtonSize.Width,
CloseButtonSize.Height);
//g.Dispose();
User32.ReleaseDC(m.HWnd, hdc);

m.Result = IntPtr.Zero;

}
 

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