使用文字編輯器建立簡單的 C WinForms 應用程式
-
開啟文字編輯器(如記事本),然後鍵入以下程式碼:
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace SampleApp { public class MainForm : Form { private Button btnHello; // The form's constructor: this initializes the form and its controls. public MainForm() { // Set the form's caption, which will appear in the title bar. this.Text = "MainForm"; // Create a button control and set its properties. btnHello = new Button(); btnHello.Location = new Point(89, 12); btnHello.Name = "btnHello"; btnHello.Size = new Size(105, 30); btnHello.Text = "Say Hello"; // Wire up an event handler to the button's "Click" event // (see the code in the btnHello_Click function below). btnHello.Click += new EventHandler(btnHello_Click); // Add the button to the form's control collection, // so that it will appear on the form. this.Controls.Add(btnHello); } // When the button is clicked, display a message. private void btnHello_Click(object sender, EventArgs e) { MessageBox.Show("Hello, World!"); } // This is the main entry point for the application. // All C# applications have one and only one of these methods. [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } }
-
將檔案儲存到你具有讀/寫訪問許可權的路徑。在包含它的類之後命名檔案是常規的 - 例如,
X:\MainForm.cs
。 -
從命令列執行 C#編譯器,將路徑作為引數傳遞給程式碼檔案:
%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:winexe "X:\MainForm.cs"
注意: 要將 C#編譯器的一個版本用於其他 .NET 框架版本,請檢視路徑
%WINDIR%\Microsoft.NET
並相應地修改上面的示例。有關編譯 C#應用程式的更多資訊,請參閱編譯並執行第一個 C#程式 。 -
編譯完成後,將在與程式碼檔案相同的目錄中建立名為
MainForm.exe
的應用程式。你可以從命令列執行此應用程式,也可以在資源管理器中雙擊它。