我正在为C#Windows表单创建一个自定义控件,一个媒体播放器工具。
我的控件具有标准按钮的自定义图像(例如,播放,暂停,停止,下一个,上一个,随机)。我的问题是我无法正确加载这些图像。因为我在控件的构造函数中执行此操作,所以当我从工具箱拖动控件并将其拖放到表单上时,它在设计时失败。
使用实际文件的完整路径
加载图像时,它工作正常Image bmpPlay = Image.FromFile(@"C:\Users\CybeX\Documents\Visual Studio 2012\Projects\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\images\play.bmp");
但我不想这样做,因为显然,路径会根据应用程序的安装位置而有所不同。我尝试使用相对路径
Image bmpPause = Image.FromFile(@"Images\pause.bmp");
但是这会引发异常,说它无法找到指定的文件。
我尝试将这些图像复制到应用程序的调试文件夹中,但同样出错。
如何在运行期间以可靠的方式创建这些图像,无论应用程序安装在何处?
为了完整性,这里是我控制的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class mediaplayerbox : System.Windows.Forms.Button
{
const int buttonwidth = 150;
const int buttonheight = 150;
public mediaplayerbox()
{
InitializeComponent();
Button btnPlay = new Button();
Button btnPause = new Button();
Button btnStop = new Button();
Button btnNext = new Button();
Button btnPrevious = new Button();
Button btnPlayRandom = new Button();
btnPlay.SetBounds(0, 0, buttonwidth, buttonheight);
btnPause.SetBounds(btnPlay.Left + buttonwidth, 0, buttonwidth, buttonheight);
btnStop.SetBounds(btnPause.Left + buttonwidth, 0, buttonwidth, buttonheight);
btnNext.SetBounds(btnStop.Left + buttonwidth, 0, buttonwidth, buttonheight);
btnPrevious.SetBounds(btnNext.Left + buttonwidth, 0, buttonwidth, buttonheight);
btnPlayRandom.SetBounds(btnPrevious.Left + buttonwidth, 0, buttonwidth, buttonheight);
Image bmpPlay = Image.FromFile(@"C:\Users\CybeX\Documents\Visual Studio 2012\Projects\WindowsFormsApplication3\WindowsFormsApplication3\bin\Debug\images\play.bmp");
Image bmpPause = Image.FromFile(@"Images\pause.bmp");
Image bmpStop = Image.FromFile(@"Images\stop.bmp");
Image bmpNext = Image.FromFile(@"Images\next.bmp");
Image bmpPrevious = Image.FromFile(@"Images\previous.bmp");
Image bmpPlayRandom = Image.FromFile(@"Images\play_random.bmp");
btnPlay.Image = bmpPlay;
btnPause.Image = bmpPause;
btnStop.Image = bmpStop;
btnPrevious.Image = bmpNext;
btnNext.Image = bmpPrevious;
btnPlayRandom.Image = bmpPlayRandom;
btnPlay.ImageAlign = ContentAlignment.MiddleCenter;
btnPause.ImageAlign = ContentAlignment.MiddleCenter;
btnStop.ImageAlign = ContentAlignment.MiddleCenter;
btnNext.ImageAlign = ContentAlignment.MiddleCenter;
btnPrevious.ImageAlign = ContentAlignment.MiddleCenter;
btnPlayRandom.ImageAlign = ContentAlignment.MiddleCenter;
btnPlay.FlatStyle = FlatStyle.Flat;
btnPlay.FlatStyle = FlatStyle.Flat;
btnPlay.FlatStyle = FlatStyle.Flat;
btnNext.FlatStyle = FlatStyle.Flat;
btnPrevious.FlatStyle = FlatStyle.Flat;
btnPlayRandom.FlatStyle = FlatStyle.Flat;
}
}
}
答案 0 :(得分:0)
不要使用硬编码路径!相反,创建一个资源文件,在那里嵌入图像,然后通常用资源加载它。