Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align separator in ContextMenuStrip

Tags:

c#

winforms

Here is my code for ContextMenuStrip:

        ContextMenuStrip _menuStrip = new ContextMenuStrip();
        Image image = new Bitmap("icon_main.ico");
        _menuStrip.Items.Add("First item", image);

        ToolStripSeparator stripSeparator1 = new ToolStripSeparator();
        stripSeparator1.Alignment = ToolStripItemAlignment.Right;//right alignment
        _menuStrip.Items.Add(stripSeparator1);

        _menuStrip.Items.Add("Second item", image);

        ToolStripSeparator stripSeparator = new ToolStripSeparator();
        stripSeparator.Alignment = ToolStripItemAlignment.Left;//left alignment
        _menuStrip.Items.Add(stripSeparator);

        _menuStrip.Items.Add("Exit", image, OnClickExit);            
        _mainIcon.ContextMenuStrip = _menuStrip;

Strange thing is that separators are not aligned - I have a little space between edge of ContextMenuStrip and separator, even if I try to align the separator (I've tried both - left and right alignment):

enter image description here

It's not a big graphical failure, but I'm asking myself how this can be aligned perfectly:

enter image description here

Any ideas what should I do?

like image 659
FrenkyB Avatar asked Oct 20 '22 19:10

FrenkyB


1 Answers

You should use Paint event (msdn):

...
ToolStripSeparator stripSeparator = new ToolStripSeparator();                   
stripSeparator.Paint += stripSeparator_Paint;
_menuStrip.Items.Add(stripSeparator);
...

Paint event handler:

void stripSeparator_Paint(object sender, PaintEventArgs e)
{
    ToolStripSeparator stripSeparator = sender as ToolStripSeparator;
    ContextMenuStrip menuStrip = stripSeparator.Owner as ContextMenuStrip;
    e.Graphics.FillRectangle(new SolidBrush(Color.Transparent), new Rectangle(0, 0, stripSeparator.Width, stripSeparator.Height));
    using (Pen pen = new Pen(Color.LightGray, 1))
    {
        e.Graphics.DrawLine(pen, new Point(23, stripSeparator.Height / 2), new Point(menuStrip.Width, stripSeparator.Height / 2));
    }
}
like image 174
kmatyaszek Avatar answered Oct 31 '22 22:10

kmatyaszek