更新:2007 年 11 月
當程式設計用戶端表單應用程式時,可使用在 C# 中 .NET Framework 豐富的 Windows Form 元件集。
Java
表單在進行程式設計時,大部分 Java 應用程式都是使用 Abstract Windowing ToolKit (AWT) 或 Swing (使用 AWT 基礎架構),其中包括 AWT 事件模型。AWT 提供所有基本 GUI 功能和類別。
Java 範例
框架 (具有標題和框線的視窗) 通常用來加入元件。
JFrame aframe = new JFrame();
Component 類別是以圖形表示的物件,通常已進行擴充,其繼承方法可供使用但通常會被覆寫,例如下列程式碼中 Shape 元件的 paint 方法。
import java.awt.*;
import javax.swing.*;
class aShape extends JComponent {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
// Draw the shape.
}
public static void main(String[] args) {
JFrame aframe = new JFrame();
frame.getContentPane().add(new aShape ());
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}
}
可以註冊接聽元件的動作事件,以進行事件處理。例如,藉由呼叫按鈕上的 processEvent,AWT 便會在按下和釋放按鈕時將 ActionEvent 的執行個體傳送至該按鈕。按鈕的 processEvent 方法會接收該按鈕的所有事件,按鈕呼叫本身的 processActionEvent 方法時則是會傳遞動作事件。其中第二個方法會將動作事件傳遞至任何已註冊為與此按鈕所產生之動作事件相關的接聽程式。
C#
在 C# 中,System.Windows.Forms 命名空間和 .NET Framework 的類別會提供完整的元件集以便進行 Windows Form 程式開發。例如,下列程式碼使用了 Label、Button 和 MenuStrip。
C# 範例
僅從 Form 類別衍生,如下所示:
public partial class Form1 : System.Windows.Forms.Form
然後加入元件:
this.button1 = new System.Windows.Forms.Button();
this.Controls.Add(this.button1);
下列程式碼說明如何在表單中加入標籤、按鈕和功能表。
namespace WindowsFormApp
{
public partial class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.MenuStrip menu1;
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label1 = new System.Windows.Forms.Label();
this.Controls.Add(this.label1);
this.button1 = new System.Windows.Forms.Button();
this.Controls.Add(this.button1);
this.menu1 = new System.Windows.Forms.MenuStrip();
this.Controls.Add(this.menu1);
}
static void Main()
{
System.Windows.Forms.Application.Run(new Form1());
}
}
}
就像 Java 一樣,在 C# 中也可以註冊接聽元件的事件。例如,當按下和釋放按鈕時,執行階段會將 Click 事件傳送至任何已註冊為與此按鈕之 Click 事件相關的接聽程式。
private void button1_Click(object sender, System.EventArgs e)
{
}
您可以使用下列程式碼註冊 button1_Click 以處理名為 button1 之 Button 執行個體的 Click 事件。
// this code can go in InitializeComponent()
button1.Click += button1_Click;
如需詳細資訊,請參閱建立 ASP.NET Web 應用程式 (Visual C#)。
如需 Forms 類別的詳細資訊,請參閱 依功能區分 Windows Form 控制項 和 System.Windows.Forms。