gotdotnet網(wǎng)站上有個(gè)Pocket PC的例子程序,就是Background Image on Form,地址為:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/bkgndimage.aspx
因?yàn)槭堑谝淮巫鲞@樣的程序,摸索了好久發(fā)現(xiàn)了兩個(gè)關(guān)鍵的地方,放上來與大家分享一下。轉(zhuǎn)載的朋友請注明來源于西部e網(wǎng),AD一下,網(wǎng)址為weste.net。下面我們就共同來學(xué)習(xí)一下吧!
代碼都已經(jīng)是現(xiàn)成的了:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
namespace BkgndImage
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.MainMenu mainMenu1;
private Image backgroundImage;
public Form1()
{
//
// Required for Windows Form Designer support
//
backgroundImage = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("BkgndImage.MyBkgnd.jpg"));
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.button1 = new System.Windows.Forms.Button();
//
// button1
//
this.button1.Location = new System.Drawing.Point(144, 184);
this.button1.Size = new System.Drawing.Size(64, 24);
this.button1.Text = "button1";
//
// Form1
//
this.Controls.Add(this.button1);
this.Menu = this.mainMenu1;
this.Text = "Form1";
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
//Draws the image to fit the ClientRectangle area of the form.
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(backgroundImage, this.ClientRectangle, new Rectangle(0, 0, this.backgroundImage.Width, this.backgroundImage.Height), GraphicsUnit.Pixel);
}
}
}
關(guān)鍵的地方已經(jīng)設(shè)成粗字體了。
代碼是正確的,可以直接使用,但是這里面有兩個(gè)地方需要注意:
1、GetManifestResourceStream方法
從此程序集加載指定清單資源,清單資源的范圍由指定類型的命名空間確定。如果你的圖片文件名為 MyBkgnd.jpg,那么你需要寫成 BkgndImage.MyBkgnd.jpg 才能夠搜索到資源。
還有一種寫法更好:
Assembly asm = Assembly.GetExecutingAssembly();
backgroundImage = new Bitmap(asm.GetManifestResourceStream(asm.GetName().Name+ ".MyBkgnd.jpg"));
這樣就不用考慮命名空間的問題了。
2、如果你發(fā)現(xiàn)即使文件名寫正確了,但是出現(xiàn)
未處理的“System.ArgumentException”類型的異常出現(xiàn)在 system.drawing.dll 中
這種錯(cuò)誤,就說明還是沒有找到資源文件,這個(gè)時(shí)候就是我要說的第二個(gè)技巧了,其實(shí)路徑是對(duì)的,但是要加載的圖片的確沒有找到。
方法是:在項(xiàng)目中找到圖片,屬性-生成操作(選擇“嵌入的資源”)
重新編譯部署,呵呵,看看效果就出來了吧!