2016-06-11 2 views
2

winforms (clickonce 아님) 응용 프로그램은 명령 줄 인수를 한 번만 처리해야합니다. 응용 프로그램은 Application.Restart()을 사용하여 구성을 변경 한 후에 다시 시작합니다. 이 처음 실행될 때 응용 프로그램이 원래 명령 줄 옵션을 제공 한 경우 MSDN on Application.Restart()Application.Restart() 전에 명령 줄 인수를 수정하십시오.

에 따르면

, 다시는 같은 옵션으로 응용 프로그램을 다시 시작합니다.

이로 인해 명령 줄 인수가 두 번 이상 처리됩니다.

Application.Restart()을 호출하기 전에 (저장된) 명령 줄 인수를 수정하는 방법이 있습니까?

+1

저는 C# winforms 전문가가 아니지만,'Application.Restart()'없이 어플리케이션을 시작하는 것은 어떨까요? 'System.Diagnostics.Process.Start ("yourapp.exe");'와 같은 것을 사용해보십시오. 그리고 시작한 후에는 현재 프로세스 (인자를 취한 프로세스)를 죽이게됩니다. – Alisson

+2

분명히'Application.Restart'가 작동하는 방식에 따라 더 안정적입니다. 먼저'Application' 클래스의 private static'ExitInternal' 메소드를 호출하고 프로세스를 시작합니다. –

+0

@RezaAghaei 이것은 광산과 같이 두 프로세스간에 겹치지 않는 리소스를 사용하는 응용 프로그램의 중요한 구분이며 처음부터 완전히 처리해야합니다. – khargoosh

답변

2

당신은 같은 방법을 사용하여 원래의 명령 줄 인수없이 응용 프로그램을 다시 시작할 수 있습니다 : 당신이 Environment.GetCommandLineArgs 방법을 사용하여 명령 줄 인수를 발견하고 새로운 명령 줄을 만들려면 그만큼 명령 줄 인수를 수정해야하는 경우도

// using System.Diagnostics; 
// using System.Windows.Forms; 

public static void Restart() 
{ 
    ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo; 
    startInfo.FileName = Application.ExecutablePath; 
    var exit = typeof(Application).GetMethod("ExitInternal", 
         System.Reflection.BindingFlags.NonPublic | 
         System.Reflection.BindingFlags.Static); 
    exit.Invoke(null, null); 
    Process.Start(startInfo); 
} 

을 인수 문자열을 Arguments 속성 인 startInfo으로 전달합니다. GetCommandLineArgs이 반환하는 배열의 첫 번째 항목은 응용 프로그램 실행 경로이므로 무시합니다. Application.Restart 작품, Application.Restartsource code에서 살펴 방법에 대한 자세한 내용은

var args = Environment.GetCommandLineArgs().Skip(1); 
var newArgs = string.Join(" ", args.Where(x => x != @"/x").Select(x => @"""" + x + @"""")); 
startInfo.Arguments = newArgs; 

: 아래의 예는, 가능한 경우 원래의 명령 줄에서 매개 변수 /x을 제거합니다.

관련 문제