2012-03-27 7 views
8

콘솔을 닫을 때 파일을 업로드해야하는 C# 응용 프로그램을 작성 중입니다 (X 버튼을 클릭하거나 컴퓨터가 종료 된 경우).콘솔에서 코드 실행을 닫으시겠습니까?

어떻게하면됩니까? 나는 빨간 닫기 버튼을 명중하지 않을 경우, 콘솔에 exit 명령을 실행할 때

AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnExit); 

만 실행됩니다.

X 버튼을 통해 콘솔을 닫았을 때와 컴퓨터를 종료 할 때 (일반적으로 Windows를 통해 해결할 때 모두 솔루션이 실행되는 경우에만 대답하십시오) 전원이 꺼져 있으면 x4를 끌 수 없습니다.

+3

죄송 할하지만 프로세스가이 어쩌면 당신이 Win7에 위치에 그것을 본 적이 (가능한 모든 경우에 동작하지 않습니다 수 있도록 살해 시나리오가 말한다 당신은 shutdown을 쳤고 시스템은 어떤 프로세스가 shutdown을 막고 종료를 선택할 수 있다고 알려줍니다.) – Carsten

+0

@ CarstenKönig 나는 그런 상황이 있음을 알고 있습니다 만, 적어도 정상적인 종료 프로세스 하에서는 사용자가 앱을 강제 종료하지 않습니다. –

+0

가능한 중복 http://stackoverflow.com/questions/474679/capture-console-exit-c-sharp –

답변

10

이 작업을 수행하기 위해, 그냥 거기에서 당신을위한 관련 코드를 복사 여기이 게시물 http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/707e9ae1-a53f-4918-8ac4-62a1eddb3c4a/

한 번 봐 가지고는 Win32 API를 호출 할 수 있습니다

class Program 

{ 
    private static bool isclosing = false; 

    static void Main(string[] args) 
    { 
     SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true); 

     Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit"); 

     while (!isclosing) ; 
    } 

    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) 
    { 
     // Put your own handler here 

     switch (ctrlType) 
     { 
      case CtrlTypes.CTRL_CLOSE_EVENT: 
       isclosing = true; 
       Console.WriteLine("Program being closed!"); 
       break; 
     } 

     return true; 
    } 

    #region unmanaged 
    // Declare the SetConsoleCtrlHandler function 
    // as external and receiving a delegate. 

    [DllImport("Kernel32")] 
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); 

    // A delegate type to be used as the handler routine 
    // for SetConsoleCtrlHandler. 
    public delegate bool HandlerRoutine(CtrlTypes CtrlType); 

    // An enumerated type for the control messages 
    // sent to the handler routine. 

    public enum CtrlTypes 
    { 
     CTRL_C_EVENT = 0, 
     CTRL_BREAK_EVENT, 
     CTRL_CLOSE_EVENT, 
     CTRL_LOGOFF_EVENT = 5, 
     CTRL_SHUTDOWN_EVENT 
    } 

    #endregion 
} 

그것은 정확하게 수행을 당신이 필요로하는 것.

인사말,

+0

이것은 완벽하게 작동합니다! –

0

이 같은 뭔가

//get all command windows in the system 
Process[] processes = Process.GetProcessesByName("cmd"); 


// find that one you interested in 
Process mypro; 

당신을 위해

mypro.Exited += (s,e) => 
{ 
    //here upload the file 
} 

해야하는 일처럼의 Process.Exited 이벤트를 구독 (내가 바로 당신이 요청 이해 가정) 할 수 있습니다.

+0

제 생각에, 당신은 그렇게하지 않아도됩니다! 왜냐하면 "cmd"라고 불리는 하나 이상의 프로세스가 있다면? 프로세스에 가입하려면 코드에 필터링을 추가하십시오 (예 : e.h). Process-Window의 이름이지 Process 자체는 아닙니다. –

+0

@ MarioFraiß : 확실합니다. 실제로 * 그 * cmd 프로세스가 내 게시물에서 건너 뛴 방법에 대한 이야기. cmd.exe가 필요하다는 것을 알기 위해서는 "강한 키"가 필요합니다. – Tigran

1

나는 또한 당신이 업로드 나중에 그래서 당신은/고장이없는 잘못된 파일을 업로드하려면 무엇을 저장해야합니다 제안하고자합니다. 그러면 다음에 응용 프로그램이 시작될 때 업로드를 수행 할 수 있습니다. 이 사람은 적어도 시스템 로그 오프/종료 작동 :

SystemEvents.SessionEnding += (SystemEvents_SessionEnding); 

private static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) 
{ 
    //code to run on when user is about to logoff or shutdown 
}