프로그램/C#

javascript 의 prompt 와 같은 , 메시지 입력창 기능의 코드

(주)CKBcorp., 2016. 1. 9. 06:00
반응형


설명이 좀 병맛같은데, 구글에서 검색할때는 "C# prompt messagebox" 로 검색하면 된다.


javascript 의 alert() 은 뭔지 알지? C# 에서 messageBox.Show() 잖아.





javascript 의 confirm() 은? C# 에서 messageBox.Show() 에서 옵션으로 처리 가능. ( 여기 검색하면 많다. )




     DialogResult dr = MessageBox.Show("Message.", "Title", MessageBoxButtons.YesNoCancel, 
        MessageBoxIcon.Information);

    if (dr == DialogResult.Yes)
    {
        // Do something
    }

[ 요런 코드 쓰면 됨. stackOverflow 에 있는 코드다.]



그럼, prompt() 는 어떻게 처리할래?



안타깝게도, C# 에서 prompt 에 해당하는 기능은 MessageBox 에서 제공하지 않는다. = 너님이 Form 으로 만들어 써야 됨.




고로, 여기에 대한 대안으로 2가지 중 하나를 쓰자. 



1. VB 명령을 끌어다 쓰면, 코드 한 줄로 해결 가능.

프로젝트에 visual basic 코드를 참조로 낑궈 넣으면, 아래의 한 줄로 가능하다.

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


방법은 다음과 같다. 
1. VB 의 InputBox 를 C#에서 끌어와서 사용. 

 1.1. 프로젝트 > 참조 추가 > .NET > MicrosoftVisualBasic 을 선택, 추가한다.



 1.2. 위의 코드를 사용.

string input = Microsoft.VisualBasic.Interaction.InputBox("Title", "Prompt", "Default", 0, 0);
그냥 한줄로 끝난다.




근데 VB모듈을 추가하는게 껄끄럽다? 그럼 아래 방법을 쓰면 된다.



2.  역시나 StackOverflow 를 참고해서, 해당 코드를 사용한다.



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 : "";
    }
}

And calling it:

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


뭘 선택할지는 너님의 선택이다. 나는 1번 추천.



[ 여긴 1번이 없네.] 


반응형