Java 早期以 Applet 闻名,透過 `
// BallGame.cs
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace BallGame
{
public class BallControl : Control
{
private Rectangle _ball = new Rectangle(0, 0, 50, 50);
private Thread _thread;
private Image _buffer;
private int _vx = 4, _vy = 6;
public BallControl()
{
ClientSize = new Size(200, 300);
BackColor = Color.Gray;
DoubleBuffered = true; // 減少閃爍
_thread = new Thread(Run) { IsBackground = true };
_thread.Start();
}
protected override void OnPaint(PaintEventArgs e)
{
if (_buffer != null) e.Graphics.DrawImage(_buffer, 0, 0);
}
private void Run()
{
while (true)
{
_buffer = new Bitmap(ClientSize.Width, ClientSize.Height);
using (var g = Graphics.FromImage(_buffer))
{
g.FillEllipse(Brushes.Blue, _ball);
}
// 邊界反彈
if (_ball.X <= 0 || _ball.Right >= ClientSize.Width) _vx = -_vx;
if (_ball.Y <= 0 || _ball.Bottom >= ClientSize.Height) _vy = -_vy;
_ball.X += _vx;
_ball.Y += _vy;
Invalidate(); // 觸發重繪
Thread.Sleep(30);
}
}
protected override void Dispose(bool disposing)
{
if (disposing) _thread?.Join(100);
base.Dispose(disposing);
}
}
}
csc /t:library /out:BallGame.dll /r:System.dll,System.Drawing.dll,System.Windows.Forms.dll BallGame.cs
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /><title>C# 彈跳球</title></head>
<body>
<h3>C# WinForms 控制項嵌入網頁</h3>
<object id="ball" classid="BallGame.dll#BallGame.BallControl" width="300" height="200" VIEWASTEXT>
<p>無法載入控制項,請確認已安裝 .NET Framework 並使用相容瀏覽器。</p>
</object>
</body>
</html>
| 項目 | 說明 |
|---|---|
| 基底類別 | 必須繼承 System.Windows.Forms.Control |
| 輸出類型 | Class Library (.dll),非 .exe |
| classid 格式 | 檔案名.dll#命名空間.類別名 (相對/絕對路徑皆可) |
| 尺寸同步 | HTML width/height 需與控制項 ClientSize 一致,否則會有縮放或裁切 |
| 執行緒 | UI 執行緒不可阻塞,動畫請另開 Thread/Task 並用 Invalidate() 觸發重繪 |
| 資源釋放 | 覆寫 Dispose 停止背景執行緒,避免網頁卸載時殘留 |
舊式 `