This is an old revision of the document!
using System; using System.Drawing; using System.Windows.Forms; public class MainForm : Form { public MainForm() { this.Text = "主視窗"; this.Size = new Size(400, 300); Button button = new Button(); button.Text = "顯示訊息框"; button.Click += (sender, e) => ShowCenteredMessageBox("這是一個自訂訊息框"); Controls.Add(button); } private void ShowCenteredMessageBox(string para_ShowString) { // 創建自訂的訊息框 Form messageBox = new Form(); messageBox.StartPosition = FormStartPosition.Manual; // 設定訊息框內容 Label messageLabel = new Label(); messageLabel.Text = para_ShowString; messageLabel.AutoSize = true; // 自動調整大小 messageLabel.Location = new Point(10, 10); // 添加關閉按鈕 Button okButton = new Button(); okButton.Text = "確定"; okButton.DialogResult = DialogResult.OK; okButton.AutoSize = true; // 按鈕自動調整大小 okButton.Location = new Point(10, messageLabel.Bottom + 10); okButton.Click += (sender, e) => messageBox.Close(); // 將控件添加到訊息框 messageBox.Controls.Add(messageLabel); messageBox.Controls.Add(okButton); // 計算顯示位置 int x = this.Location.X + (this.Width / 2) - (messageBox.Width / 2); int y = this.Location.Y + (this.Height / 2) - (messageBox.Height / 2); messageBox.Location = new Point(x, y); // 設定訊息框大小 messageBox.AutoSize = true; messageBox.AutoSizeMode = AutoSizeMode.GrowAndShrink; messageBox.ShowDialog(); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } }