how to paint on top of a forms main menu?

P

Peter Row

Hi,

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

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
try
{
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);
}
}
base.OnPaint(e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

....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.

Regards,
Peter
 
N

Nicholas Paldino [.NET/C# MVP]

Peter,

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.
 
M

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:
http://www.dotnetrix.co.uk/menus.html --> Custom MenuBar color

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

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