首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# GUI 開發實戰範例:溫度轉換器完整程式碼(四)

     編輯:關於C語言

完整原始碼:TempConverter


using System;
using System.Windows.Forms;

public class TempConverter : Form {
  Label lblC = new Label(), lblF = new Label();
  TextBox txtC = new TextBox(), txtF = new TextBox();
  Button btnCtoF = new Button(), btnFtoC = new Button();

  public TempConverter() {
    this.ClientSize = new Size(180, 90);
    this.FormBorderStyle = FormBorderStyle.FixedDialog;
    this.Text = "°C→°F / °F→°C";
    this.StartPosition = FormStartPosition.CenterScreen;
    this.MaximizeBox = false;

    txtC.TabIndex = 0; txtC.SetBounds(13, 5, 50, 25);
    lblC.TabStop = false; lblC.Text = "°C"; lblC.SetBounds(65, 5, 25, 25);
    txtF.TabIndex = 1; txtF.SetBounds(90, 5, 50, 25);
    lblF.TabStop = false; lblF.Text = "°F"; lblF.SetBounds(142, 5, 25, 25);

    btnCtoF.TabIndex = 2; btnCtoF.Text = "°C to °F"; btnCtoF.SetBounds(13, 35, 70, 25);
    btnCtoF.Click += new EventHandler(btnCtoF_Click);
    btnFtoC.TabIndex = 3; btnFtoC.Text = "°F to °C"; btnFtoC.SetBounds(90, 35, 70, 25);
    btnFtoC.Click += new EventHandler(btnFtoC_Click);

    this.Controls.AddRange(new Control[] { txtC, lblC, txtF, lblF, btnCtoF, btnFtoC });
  }

  [STAThread]
  static void Main() { Application.Run(new TempConverter()); }

  void btnCtoF_Click(object sender, EventArgs e) {
    double c, f;
    try { c = double.Parse(txtC.Text); }
    catch { txtC.Clear(); txtF.Clear(); return; }
    f = 1.8 * c + 32;
    txtF.Text = f.ToString();
    txtF.Focus(); txtF.SelectionStart = 0; txtF.SelectionLength = 0;
    txtC.Focus(); txtC.SelectionStart = 0; txtC.SelectionLength = 0;
  }

  void btnFtoC_Click(object sender, EventArgs e) {
    double c, f;
    try { f = double.Parse(txtF.Text); }
    catch { txtC.Clear(); txtF.Clear(); return; }
    c = (f - 32) / 1.8;
    txtC.Text = c.ToString();
    txtC.Focus(); txtC.SelectionStart = 0; txtC.SelectionLength = 0;
    txtF.Focus(); txtF.SelectionStart = 0; txtF.SelectionLength = 0;
  }
}

關鍵 API 與模式

  • SetBounds(x, y, w, h):一次設定位置與大小(現代 WinForms 推薦用法)。
  • TabIndex / TabStop:控制鍵盤導航順序,標籤設 TabStop=false 避免焦點停留。
  • Controls.AddRange:批次加入控件陣列。
  • double.Parse + try/catch:安全解析使用者輸入,失敗清空雙欄位並返回。
  • Focus() + SelectionStart/Length:計算後將游標重置至欄位開頭,提升使用體驗。

此範例展示 WinForms 絕對定位佈局、事件驅動、輸入驗證與焦點管理的基礎模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved