这是我的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;
奇怪的是分隔符没有对齐 - 我在ContextMenuStrip的边缘和分隔符之间有一点空间,即使我尝试对齐分隔符(我已经尝试了两种 - 左右对齐):
这不是一个很大的图形失败,但我问自己这是如何完美对齐的:
任何想法我应该怎么做?
答案 0 :(得分:3)
您应该使用Paint
事件(msdn):
...
ToolStripSeparator stripSeparator = new ToolStripSeparator();
stripSeparator.Paint += stripSeparator_Paint;
_menuStrip.Items.Add(stripSeparator);
...
绘制事件处理程序:
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));
}
}