[c#] Windows Forms의 프롬프트 대화 상자

나는 사용하고있다 System.Windows.Forms 있지만 이상하게도 그것들을 만들 능력이 없습니다.

자바 스크립트없이 자바 스크립트 프롬프트 대화 상자와 같은 것을 어떻게 얻을 수 있습니까?

MessageBox는 좋지만 사용자가 입력을 입력 할 방법이 없습니다.

사용자가 가능한 모든 텍스트 입력을 원합니다.



답변

고유 한 프롬프트 대화 상자를 만들어야합니다. 이것에 대한 클래스를 만들 수 있습니다.

public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form()
        {
            Width = 500,
            Height = 150,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = caption,
            StartPosition = FormStartPosition.CenterScreen
        };
        Label textLabel = new Label() { Left = 50, Top=20, Text=text };
        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 : "";
    }
}

그리고 그것을 부릅니다.

string promptValue = Prompt.ShowDialog("Test", "123");

업데이트 :

코멘트와 다른 질문을 기반으로 기본 버튼 ( Enter 키 )과 초기 포커스를 추가했습니다 .


답변

참조를 추가 Microsoft.VisualBasic하고이를 C # 코드에 사용합니다.

string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt",
                       "Title",
                       "Default",
                       0,
                       0);

참조를 추가하려면 프로젝트 탐색기 창에서 참조를 마우스 오른쪽 단추로 클릭 한 다음 참조 추가를 클릭하고 해당 목록에서 VisualBasic을 확인합니다.


답변

Windows Forms에는 기본적으로 그러한 것이 없습니다.

이를 위해 자신의 양식을 작성하거나 다음을 수행해야합니다.

Microsoft.VisualBasic참조를 사용하십시오 .

Inputbox는 VB6 호환성을 위해 .Net으로 가져온 레거시 코드이므로이 작업을 수행하지 않는 것이 좋습니다.


답변

일반적으로 VisualBasic 라이브러리를 C # 프로그램으로 가져 오는 것은 좋은 생각이 아니지만 (작동하지 않기 때문이 아니라 호환성, 스타일 및 업그레이드 기능을 위해서만) Microsoft.VisualBasic.Interaction.InputBox ()를 호출 할 수 있습니다. 찾고있는 상자의 종류를 표시합니다.

Windows.Forms 개체를 만들 수 있다면 가장 좋겠지 만 그렇게 할 수 없다고 말합니다.


답변

이를 수행하는 다른 방법 : TextBox 입력 유형이 있고 양식을 작성하고 공용 속성으로 텍스트 상자 값이 있다고 가정합니다.

public partial class TextPrompt : Form
{
    public string Value
    {
        get { return tbText.Text.Trim(); }
    }

    public TextPrompt(string promptInstructions)
    {
        InitializeComponent();

        lblPromptText.Text = promptInstructions;
    }

    private void BtnSubmitText_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void TextPrompt_Load(object sender, EventArgs e)
    {
        CenterToParent();
    }
}

기본 양식에서 다음은 코드입니다.

var t = new TextPrompt(this, "Type the name of the settings file:");
t.ShowDialog()

;

이렇게하면 코드가 더 깔끔해 보입니다.

  1. 유효성 검사 로직이 추가 된 경우.
  2. 기타 다양한 입력 유형이 추가 된 경우.

답변

Bas의 대답은 ShowDialog가 폐기되지 않기 때문에 이론적으로 메모리 문제를 일으킬 수 있습니다. 나는 이것이 더 적절한 방법이라고 생각합니다. 또한 textLabel이 긴 텍스트로 읽을 수 있음을 언급하십시오.

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();
        }
    }
}

이행:

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


답변

위의 Bas Brekelmans의 작업을 기반으로 사용자로부터 텍스트 값과 부울 (TextBox 및 CheckBox)을 수신 할 수있는 두 가지 파생-> “입력”대화 상자도 만들었습니다.

public static class PromptForTextAndBoolean
{
    public static string ShowDialog(string caption, string text, string boolStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
        Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(ckbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
    }
}

… 여러 옵션 (TextBox 및 ComboBox) 중 하나의 선택과 함께 텍스트 :

public static class PromptForTextAndSelection
{
    public static string ShowDialog(string caption, string text, string selStr)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 160;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
        Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
        ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
        cmbx.Items.Add("Dark Grey");
        cmbx.Items.Add("Orange");
        cmbx.Items.Add("None");
        Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(selLabel);
        prompt.Controls.Add(cmbx);
        prompt.Controls.Add(confirmation);
        prompt.AcceptButton = confirmation;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
    }
}

둘 다 동일한 용도가 필요합니다.

using System;
using System.Windows.Forms;

그렇게 부르십시오.

그렇게 부르십시오.

PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing");

PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");