User Tools

Site Tools


Action disabled: revisions
blog:2025-08-06-002



2025-08-06 C# 中指定 MessageBox.Show() 的顯示位置

  • 要在 C# 中指定 MessageBox.Show() 的顯示位置,您需要使用自訂的 Form 來取代標準的 MessageBox。這樣可以讓您自由地設置顯示位置。以下是如何實現的範例程式碼:
  • 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());
        }
    }
    

說明

  • 要使 Dialog 視窗的大小根據顯示內容自動調整,可以使用 AutoSize 和 AutoSizeMode 屬性。
    • AutoSize:將 messageBox.AutoSize 設定為 true,使訊息框根據內容自動調整大小。
    • AutoSizeMode:設定 messageBox.AutoSizeMode 為 AutoSizeMode.GrowAndShrink,這樣訊息框會根據內容增長或縮小。
    • 按鈕自動調整:將按鈕的 AutoSize 設定為 true,這樣按鈕的大小會根據其內容自動調整。
  • 自訂訊息框:創建一個新的 Form 作為訊息框,而不是使用 MessageBox.Show()。
  • 內容顯示:使用 Label 控件來顯示傳遞的字串,並設置 AutoSize 為 true,使其根據內容自動調整大小。
  • 顯示位置:計算訊息框的位置,使其顯示在母視窗的中央。
  • 關閉按鈕:添加一個按鈕來關閉訊息框,並設置其位置。
  • 這樣,就可以在自訂的訊息框中顯示內容,並且可以指定它的顯示位置。

TAGS

  • 1 person(s) visited this page until now.

blog/2025-08-06-002.txt · Last modified: 2025/08/06 16:23 by jethro