我有一个使用ContextMenuStrip的C#winForm项目.我根据使用交互动态地将ToolStripMenuItems添加到ContextMenuStrip.当我添加一个新的ToolStripMenuItem时,我设置了它的Text属性和Image属性.我不知道如何设置Image属性而不从它所在的位置获取图像.如何将想象添加到我的项目中?这是我的代码正在做的一个例子
ContextMenuStrip cxtMnuStrp = new ContextMenuStrip;
private void Button_Click(object sender, EventArgs e)
{
// some filtering and logic
// to determine weather to
// create and add a ToolStripMenuItem
// blah, blah, blah...
ToolStripMenuItem item = new ToolStripMenuItem("uniqueName");
item.Image = Image.FromFile(@"C:\MyFolder\MyIcon.ico");
if (cxtMnuStrp.Items.ContainsKey(item) == false)
cxtMnuStrp.Items.Add(item);
}
使用"item.Image = Image.FromFile(@"C:\ MyFolder\MyIcon.ico")"当我分发我的每台机器时,必须有"C:\ MyFoler"目录并且还有"MyIcon.ico"在他们的计算机上的"C:\ MyFoler"目录中.
另外,每次我想在ToolStripMenuItem上添加一个图标时,我都点击硬盘驱动器似乎不对
您可以将图标保存在资源文件中,也可以将图像另存为嵌入式资源.
使用资源文件.
将图像添加为嵌入式资源
您的代码将如下所示.
private void BuildContextMenuStrip_Click(object sender, EventArgs e)
{
ContextMenuStrip cxtMnuStrp = new ContextMenuStrip();
ToolStripMenuItem item = new ToolStripMenuItem("uniqueName") { Image = WindowsFormsApplication2.Properties.Resources.Search.ToBitmap() };
if (cxtMnuStrp.Items.Contains(item) == false)
cxtMnuStrp.Items.Add(item);
this.ContextMenuStrip = cxtMnuStrp;
}
Run Code Online (Sandbox Code Playgroud)
注意:
除了提供的有关如何在上面的链接中添加资源的信息之外,您还可以按如下方式添加它们

| 归档时间: |
|
| 查看次数: |
9974 次 |
| 最近记录: |