컴퓨터/c#

c# 실행 파일 인자 전달 방법 (Winform)

k1asd1 2021. 12. 10. 13:12
728x90
반응형

Colsole에 이어 Winform도 작성합니다. 방법은 비슷합니다.


2021.12.10 - [컴퓨터/c#] - c# 실행 파일 인자 전달 방법 (Console)

 

c# 실행 파일 인자 전달 방법 (Console)

거의 없는 일이지만 개인 프로젝트에 사용할 일이 있었고 꼭 독립적인 실행 파일로 실행이 된 상태에서 어떠한 값을 받아야만 했던 상황에 적절하게 사용하였습니다. Console과 Winform에 사용하는

k1asd1.tistory.com


Winform 역시 2가지 방법 (Main, Environment.GetCommandLineArgs())을 다 사용할 수 있습니다.

 

* Main 메소드 매개 변수

- 우선 프로젝트 내 Program.cs 파일을 열고 Main 메소드를 수정합니다.

 

static void Main(string[] args) //string[] args 추가
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1(args)); //args 추가
}

: 그리고 해당 form을 열고 매개 변수를 수정합니다.

public Form1(string[] args) //string[] args 추가
{
    InitializeComponent();

    foreach (string str in args)
    {
        txtResult.Text += str + Environment.NewLine;
    }
    
    //for(int i = 0; i< args.Length; i++)
    //{
    //    txtResult.Text += args[i] + Environment.NewLine;
    //}
}

- 결과

인자 입력
결과

 


* 'Environment.GetCommandLineArgs()' 사용
- 역시 마찬가지로 이 방법은 배열의 0번째 값은 해당 프로그램의 출력 파일명(어셈블리 이름)으로 입력되어 있습니다.

- Program.cs의 내용은 최초 내용 그대로 두고 수정하지 않습니다.

 

- 해당 form을 열고 내용을 수정합니다.

public Form1()
{
    InitializeComponent();

    string[] args = Environment.GetCommandLineArgs(); // Environment.GetCommandLineArgs() 추가

    txtResult.Text = Textout(args);
}

private string Textout(string[] result)
{
    string strtxt = string.Empty;

    foreach (string str in result)
    {
        strtxt += str + Environment.NewLine;
    }

    return strtxt;
}

* 결과

인자 입력
결과


이상입니다.

 

728x90
반응형