how to paint on top of a forms main menu?


Peter Row


I am trying to draw on top of the main menu area of a form (this is just a
at the moment). I'm handling the forms paint event and using the following

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs
using (Graphics g = Graphics.FromHwnd(mainMenu1.Handle))
RectangleF testBox = new RectangleF(g.ClipBounds.Width - 50,
g.ClipBounds.Y, 50, g.ClipBounds.Height);
using (StringFormat sf = new StringFormat())
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.FillRectangle(Brushes.Yellow, testBox);
g.DrawString("TEST", this.Font, Brushes.Black, testBox, sf);
catch (Exception ex)

....however I get an OutOfMemoryException error on the line above that starts
using (Graphics g = Graphics.FromHwnd(...

Anybody have any ideas about how I might achieve this?
All ideas welcome, although I don't want to have to use the Win API if I can
help it.


Nicholas Paldino [.NET/C# MVP]


You can't do what you are doing, trying to get the Graphics instance
from the handle of the menu. The menu handle is not a window handle, but
something else completely.

What you have to do is get the handle of the window the menu is attached
to, and then paint that. This is not the recommended way, however.

Do you have to paint over the menu, or can you just get by painting the
menu items? If it is the latter, then just set the OwnerDraw property to
true and handle the DrawItem event.

Hope this helps.

Mick Doherty

Why don't you want to use API? AFAIK it's the only way to do it, and you'll
find an example using API on my site: --> Custom MenuBar color

The example uses a SolidBrush but you can easily replace that with a

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