![](/img/trans.png)
[英]How to display a ContextMenuStrip on a ToolStripMenuItem?
[英]Display a logo in a contextmenustrip
我正在.net 2.0中開發Winforms應用程序。
我想知道如何在附加到通知圖標的contextmenustrip中顯示徽標。
它不是在文本旁邊顯示的圖標。 這種類型橫跨整個行,通常用於顯示公司徽標。 很抱歉,我無法發布圖片。
編輯:
ContextMenuStrip1.Items.Add(new ToolStripMenuItem(String, Image) )
但是,這僅給我一個圖標,其中一行旁邊有一些文本,並且當光標懸停在該圖標上時,它將突出顯示。
我要實現的是在單行上顯示圖像而沒有任何文本,並且當光標懸停或可單擊時無法突出顯示該圖像。
解決方案非常簡單。 您必須使用自定義ToolStripRenderer
並重寫OnRenderImageMargin
方法 。 您還需要准備適當大小的徽標圖像。
這是代碼:
public class Form1 : Form {
public Form1(){
InitializeComponent();
// This contextMenuStrip is used for your Notify Icon
// Just show it as you do
contextMenuStrip1.Renderer = new CustomRenderer();
}
}
public class CustomRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
e.Graphics.DrawImage(yourImage, e.AffectedBounds);
}
}
注意:您的圖像應該已經旋轉了90度。 否則,您必須在繪制之前使用代碼旋轉它。
這是上面代碼的屏幕快照,使用了Stack Overflow徽標:
編輯后,看起來您想要其他東西。 您可能需要顯示徽標,該徽標沿項目的整個區域延伸。 我想那是最后一項。 您必須添加Text = string.Empty
的項目。 這是代碼:
public class Form1 : Form {
public Form1(){
InitializeComponent();
// This contextMenuStrip is used for your Notify Icon
// Just show it as you do
contextMenuStrip1.Renderer = new CustomRenderer(){RootToolStrip = contextMenuStrip1};
//Add your last item first
int lastItemIndex = contextMenuStrip1.Items.Count - 1;
contextMenuStrip1.Items[lastItemIndex].AutoSize = false;
contextMenuStrip1.Items[lastItemIndex].Text = "";
contextMenuStrip1.Items[lastItemIndex].Height = 40;
}
}
public class CustomRenderer : ToolStripProfessionalRenderer
{
public ToolStrip RootToolStrip;
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
int i = e.ToolStrip.Items.Count - 1;
if (e.ToolStrip.Items.IndexOf(e.Item) == i&&e.ToolStrip == RootToolStrip)
{
e.Graphics.DrawImage(yourImage, new Rectangle(0,0,e.Item.Width, e.Item.Height));
} else base.OnRenderMenuItemBackground(e);
}
}
屏幕截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.