2011-07-08 42 views
15

MenuItemのテキストの隣にアイコンを配置する方法はありますか?MenuItemにアイコンを配置する方法

私は、ユーザーが適切なユーザーコントロールでクリックしたときにポップアップメニューを表示するには、次のコードを使用し

ContextMenu menu = new ContextMenu(); 
MenuItem item = new MenuItem("test", OnClick); 
menu.MenuItems.Add(item); 
menu.Show(this, this.PointToClient(MousePosition)); 

私は、ポップアップで「テスト」の文字列の左側にあるアイコンを置くしたいと思いますユーザがそれをより容易に認識できるようにする。 OwnerDrawプロパティをtrueに設定する以外の方法があります(この例ではメニュー項目を完全に描画する必要があります:http://www.codeproject.com/KB/menus/cs_menus.aspx)。

何か助けていただければ幸いです。

+1

代わりに 'ContextMenuStrip'を' ToolStripMenuItem'で使用できますか?この場合、 'ToolStripMenuItem.Image'を設定することができます。 http://msdn.microsoft.com/en-us/library/system.windows.forms.contextmenustrip.aspx – Bolu

答えて

18

ContextMenuStripを使用して、ToolStripMenuItemsを追加してみてください。

MenuItemを使用する必要がある場合は、OwnerDrawプロパティをtrueに設定してDrawItemイベントを実行する必要があります。

+0

ContextMenuStripは確かにその仕事をします。私はそれが存在することを知らなかった。どうもありがとう! –

1

ContextMenuStripコントロールを使用すると、デザイナーでアイテムをクリックして[イメージを設定...]を選択するか、ToolStripMenuItemのImageプロパティをプログラムで変更することができます。

+0

この回答はwinformで有効ですか? – Bolu

+0

@Bolu - このリンクを見てください - http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.icon.aspx – Bibhu

+0

System.Windows.Forms.MenuItemにはそのようなものがありません最低でも.Net 2.0にないプロパティ –

9

これは6年前に.NET 2.0リリースで修正されました。 ToolStripクラスを取得しました。コードは非常に似ています

 var menu = new ContextMenuStrip(); 
     var item = new ToolStripMenuItem("test"); 
     item.Image = Properties.Resources.Example; 
     item.Click += OnClick; 
     menu.Items.Add(item); 
     menu.Show(this, this.PointToClient(MousePosition)); 
4

あなたがMenuItemに関連付けられている場合は、私は解決策はこの1つのようであることが判明しました:

var dropDownButton = new ToolBarButton(); 
dropDownButton.ImageIndex = 0; 
dropDownButton.Style = ToolBarButtonStyle.DropDownButton; 

var mniZero = new MenuItem("Zero", (o, e) => DoZero()); 
mniZero.OwnerDraw = true; 
mniZero.DrawItem += delegate(object sender, DrawItemEventArgs e) { 
    double factor = (double) e.Bounds.Height/zeroIconBmp.Height; 
    var rect = new Rectangle(e.Bounds.X, e.Bounds.Y, 
         (int) (zeroIconBmp.Width * factor), 
         (int) (zeroIconBmp.Height * factor)); 
    e.Graphics.DrawImage(zeroIconBmp, rect); 
}; 

var mniOne = new MenuItem("One", (o, e) => DoOne()); 
mniOne.OwnerDraw = true; 
mniOne.DrawItem += delegate(object sender, DrawItemEventArgs e) { 
    double factor = (double) e.Bounds.Height/oneIconBmp.Height; 
    var rect = new Rectangle(e.Bounds.X, e.Bounds.Y, 
        (int) (oneIconBmp.Width * factor), 
        (int) (oneIconBmp.Height * factor)); 
    e.Graphics.DrawImage(oneIconBmp, rect); 
}; 

dropDownButton.DropDownMenu = new ContextMenu(new MenuItem[]{ 
    mniZero, mniOne, 
}); 

この情報がお役に立てば幸いです。

関連する問題