gotdotnet网站上有个Pocket PC的例子程序,就是Background Image on Form,地址为:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/bkgndimage.aspx
因为是第一次做这样的程序,摸索了好久发现了两个关键的地方,放上来与大家分享一下。转载的朋友请注明来源于西部e网,AD一下,网址为weste.net。下面我们就共同来学习一下吧!
代码都已经是现成的了:
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);
}
}
}
关键的地方已经设成粗字体了。
代码是正确的,可以直接使用,但是这里面有两个地方需要注意:
1、GetManifestResourceStream方法
从此程序集加载指定清单资源,清单资源的范围由指定类型的命名空间确定。如果你的图片文件名为 MyBkgnd.jpg,那么你需要写成 BkgndImage.MyBkgnd.jpg 才能够搜索到资源。
还有一种写法更好:
Assembly asm = Assembly.GetExecutingAssembly();
backgroundImage = new Bitmap(asm.GetManifestResourceStream(asm.GetName().Name+ ".MyBkgnd.jpg"));
这样就不用考虑命名空间的问题了。
2、如果你发现即使文件名写正确了,但是出现
未处理的“System.ArgumentException”类型的异常出现在 system.drawing.dll 中
这种错误,就说明还是没有找到资源文件,这个时候就是我要说的第二个技巧了,其实路径是对的,但是要加载的图片的确没有找到。
方法是:在项目中找到图片,属性-生成操作(选择“嵌入的资源”)
重新编译部署,呵呵,看看效果就出来了吧!
