2011-06-13 36 views
0

現在我試圖動態改變MainForm的backgroundimage。 我寫了下面的代碼段...如何在C#.Net中動態更改backgroundimage?

this.BackgroundImage = Image.FromFile("Bar1.png"); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;

形象地說,我要改變位於我當前的項目。 但我不知道如何使用FromFile方法?

回答

1

請閱讀有關FromFile方法的文檔here

如果你在你的資源文件中有圖像,你可以這樣訪問:

this.BackgroundImage = Properties.Resources.yourImageName; 
4

嘗試是這樣的:

string path = System.IO.Path.GetDirectoryName( 
     System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); 



string filename="yourfilename"; 

this.BackgroundImage = Image.FromFile(Path.Combine(path ,filename)); 

或:

string customPath = "d:\testpath"; 

string filename="yourfilename"; 

this.BackgroundImage = Image.FromFile(Path.Combine(customPath ,filename)); 
+0

我在試着回答..但是那個錯誤發生了 URI格式不被支持。 – Soge 2011-06-13 11:21:31

+0

你能發佈錯誤嗎?如果您正在調試,請確保您的映像位於bin/debug文件夾中 – danyolgiax 2011-06-13 11:22:03

+0

也檢查,在VS中選擇您的映像,「複製到輸出dyrectory」屬性。將其設置爲「始終複製」 – danyolgiax 2011-06-13 11:34:33

2

你可以使用此代碼獲取應用程序啓動路徑:

Application.StartupPath + "\yourimage" 

,或者您可以使用

System.Reflection.Assembly.GetExecutingAssembly().Location + "\yourimage"; 
-1
OpenFileDialog dialog = new OpenFileDialog(); 

if (dialog.ShowDialog() == DialogResult.OK) 
{ 
    this.BackgroundImage = Image.FromFile(dialog.FileName); 
    this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; 
} 
+1

的問題不在於用戶選擇背景圖片... – 2013-04-10 13:27:26

-1
  1. 做了一個名爲背景在您的exe所在。在窗體加載事件

    串路徑= System.IO.Directory.GetCurrentDirectory()+ 「\背景\」 以下在該目錄

  2. 附加

  3. 拷貝背景JPG文件; string filename =「back.jpg」; this.BackgroundImage = Image.FromFile(Path.Combine(path,filename));

如果您更改了背景jpg文件保持相同的文件名,背景將被更改。