Welcome

首页 / 软件开发 / C# / 用C#编写网页小应用程序(Applet)

用C#编写网页小应用程序(Applet)2011-05-03周公学过Java的朋友可能都听说过Java的历史:当初Java是为机顶盒设备和手持设备设计的,可惜理念在当时太朝前,结果没有被人所接受,于是Java的创始人James Gosling想到在网络上碰碰运气,当时吸引大家眼球的就是用Java编写的一个Applet,早期Java的应用很多时用来编写Applet,后来慢慢发展到J2ME/J2SE/J2EE三个分支。

现在RIA(Rich Internet Application,富互联网应用系统)方面已经是Flash和sliverlight的天下了,所以微软推出C#的时候没有对类似Applet这样的网页小应用程序的支持,不过利用.net我们还是可以做出一些类似于Applet的网页小应用程序来。当然,就像Java编写的Applet需要客户端安装相应的JRE一样,我们用C#编写的小网页应用程序也需要客户端安装相应版本的.net framework,否则网页中小程序是没有办法正常运行的。

说明:写这个程序只为娱乐,好像没有太多实际用途,下面的效果其实用Flash或者sliverlight很将简单就实现了。

且看一个在网页上不停跳动的小球的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace BallGame
{
/// <summary>
/// 程序说明:这是一个弹球的程序代码。程序的运行效果是
/// 一个蓝色的小球在控件显示区域运动,当小球超出屏幕显示区域
/// 后,会自动反弹。
/// 作者:周公
/// 日期:2008-08-01
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/01/2755502.aspx
/// </summary>
public class BallControl : Control
{
private Rectangle ballRegion = new Rectangle(0, 0, 50, 50);//在显示区域的球的尺寸
private Thread thread;//绘制线程
private Image image;//即将要在显示区域绘制的图象
private int speedX = 4;//球的水平移动速度
private int speedY = 6;//球的垂直移动速度
public BallControl()
{
ClientSize = new Size(200, 300);
BackColor = Color.Gray;
thread = new Thread(new ThreadStart(Run));
thread.Start();
}
protected override void OnPaint(PaintEventArgs e)
{
if (image != null)
{
e.Graphics.DrawImage(image, 0, 0);
}
}
/// <summary>
/// 绘制球在显示区域移动的线程
/// </summary>
public void Run()
{
while (true)
{
image = new Bitmap(ClientSize.Width, ClientSize.Height);
Graphics g = Graphics.FromImage(image);
g.FillEllipse(Brushes.Blue, ballRegion);
g.Dispose();
if ((ballRegion.X < 0) || (ballRegion.X + ballRegion.Width >= ClientSize.Width))
{
speedX = -speedX;
}
if ((ballRegion.Y < 0) || (ballRegion.Y + ballRegion.Height >= ClientSize.Height))
{
speedY = -speedY;
}
ballRegion.X += speedX;
ballRegion.Y += speedY;
Invalidate();//重新绘制
Thread.Sleep(300);
}
}
}
}