Programing

WPF 명령 줄

lottogame 2020. 8. 23. 09:36
반응형

WPF 명령 줄


명령 줄 인수를 사용하는 WPF 응용 프로그램을 만들려고합니다. 인수가 제공되지 않으면 기본 창이 나타납니다. 특정 명령 줄 인수의 경우 GUI없이 코드를 실행하고 완료되면 종료해야합니다. 이것이 어떻게 적절하게 수행되어야하는지에 대한 모든 제안을 주시면 감사하겠습니다.


먼저 App.xaml 파일 상단에서이 속성을 찾아 제거합니다.

StartupUri="Window1.xaml"

즉, 응용 프로그램이 기본 창을 자동으로 인스턴스화하여 표시하지 않습니다.

다음으로 App 클래스에서 OnStartup 메서드를 재정 의하여 논리를 수행합니다.

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    if ( /* test command-line params */ )
    {
        /* do stuff without a GUI */
    }
    else
    {
        new Window1().ShowDialog();
    }
    this.Shutdown();
}

인수의 존재를 확인하려면 Matt의 솔루션에서 테스트에 다음을 사용하십시오.

e.Args.Contains ( "MyTriggerArg")


.NET 4.0+ 용 위 솔루션과 콘솔 출력의 조합 :

[DllImport("Kernel32.dll")]
public static extern bool AttachConsole(int processID);

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    if (e.Args.Contains("--GUI"))
    {
        // Launch GUI and pass arguments in case you want to use them.
        new MainWindow(e).ShowDialog();
    }
    else
    {
        //Do command line stuff
        if (e.Args.Length > 0)
        {
            string parameter = e.Args[0].ToString();
            WriteToConsole(parameter);
        }
    }
    Shutdown();
}

public void WriteToConsole(string message)
{
    AttachConsole(-1);
    Console.WriteLine(message);
}

MainWindow의 생성자를 변경하여 인수를 허용합니다.

public partial class MainWindow : Window
{
    public MainWindow(StartupEventArgs e)
    {
        InitializeComponent();
    }
}

And don't forget to remove:

StartupUri="MainWindow.xaml"

You can use the below in app.xaml.cs file :

private void Application_Startup(object sender, StartupEventArgs e)
{
    MainWindow WindowToDisplay = new MainWindow();

    if (e.Args.Length == 0)
    {
        WindowToDisplay.Show();
    }
    else
    {
        string FirstArgument = e.Args[0].ToString();
        string SecondArgument = e.Args[1].ToString();
        //your logic here
    }
}

참고URL : https://stackoverflow.com/questions/426421/wpf-command-line

반응형