Prompt Dialog in Windows Forms

前端 未结 11 1427
名媛妹妹
名媛妹妹 2020-11-30 19:47

I am using System.Windows.Forms but strangely enough don\'t have the ability to create them.

How can I get something like a javascript prompt dialog, wi

11条回答
  •  借酒劲吻你
    2020-11-30 20:03

    The answer of Bas can get you in memorytrouble theoretically, since ShowDialog won't be disposed. I think this is a more proper way. Also mention the textLabel being readable with longer text.

    public class Prompt : IDisposable
    {
        private Form prompt { get; set; }
        public string Result { get; }
    
        public Prompt(string text, string caption)
        {
            Result = ShowDialog(text, caption);
        }
        //use a using statement
        private string ShowDialog(string text, string caption)
        {
            prompt = new Form()
            {
                Width = 500,
                Height = 150,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                Text = caption,
                StartPosition = FormStartPosition.CenterScreen,
                TopMost = true
            };
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter };
            TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
            Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;
    
            return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
        }
    
        public void Dispose()
        {
            //See Marcus comment
            if (prompt != null) { 
                prompt.Dispose(); 
            }
        }
    }
    

    Implementation:

    using(Prompt prompt = new Prompt("text", "caption")){
        string result = prompt.Result;
    }
    

提交回复
热议问题