Prompt Dialog in Windows Forms

前端 未结 11 1453
名媛妹妹
名媛妹妹 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:24

    here's my refactored version which accepts multiline/single as an option

       public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
            {
                var prompt = new Form
                {
                    Width = formWidth,
                    Height = isMultiline ? formHeight : formHeight - 70,
                    FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
                    Text = caption,
                    StartPosition = FormStartPosition.CenterScreen,
                    MaximizeBox = isMultiline
                };
    
                var textLabel = new Label
                {
                    Left = 10,
                    Padding = new Padding(0, 3, 0, 0),
                    Text = text,
                    Dock = DockStyle.Top
                };
    
                var textBox = new TextBox
                {
                    Left = isMultiline ? 50 : 4,
                    Top = isMultiline ? 50 : textLabel.Height + 4,
                    Multiline = isMultiline,
                    Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
                    Width = prompt.Width - 24,
                    Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
                };
    
                var confirmationButton = new Button
                {
                    Text = @"OK",
                    Cursor = Cursors.Hand,
                    DialogResult = DialogResult.OK,
                    Dock = DockStyle.Bottom,
                };
    
                confirmationButton.Click += (sender, e) =>
                {
                    prompt.Close();
                };
    
                prompt.Controls.Add(textBox);
                prompt.Controls.Add(confirmationButton);
                prompt.Controls.Add(textLabel);
    
                return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
            }
    

提交回复
热议问题